1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis for declarations.
11 //===----------------------------------------------------------------------===//
13 #include "TreeTransform.h"
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.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/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
52 using namespace clang;
55 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57 Decl *Group[2] = { OwnedType, Ptr };
58 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
61 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
66 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
69 bool AllowTemplates = false,
70 bool AllowNonTemplates = true)
71 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
72 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
73 WantExpressionKeywords = false;
74 WantCXXNamedCasts = false;
75 WantRemainingKeywords = false;
78 bool ValidateCandidate(const TypoCorrection &candidate) override {
79 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
80 if (!AllowInvalidDecl && ND->isInvalidDecl())
83 if (getAsTypeTemplateDecl(ND))
84 return AllowTemplates;
86 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
90 if (AllowNonTemplates)
93 // An injected-class-name of a class template (specialization) is valid
94 // as a template or as a non-template.
96 auto *RD = dyn_cast<CXXRecordDecl>(ND);
97 if (!RD || !RD->isInjectedClassName())
99 RD = cast<CXXRecordDecl>(RD->getDeclContext());
100 return RD->getDescribedClassTemplate() ||
101 isa<ClassTemplateSpecializationDecl>(RD);
107 return !WantClassName && candidate.isKeyword();
110 std::unique_ptr<CorrectionCandidateCallback> clone() override {
111 return std::make_unique<TypeNameValidatorCCC>(*this);
115 bool AllowInvalidDecl;
118 bool AllowNonTemplates;
121 } // end anonymous namespace
123 /// Determine whether the token kind starts a simple-type-specifier.
124 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126 // FIXME: Take into account the current language when deciding whether a
127 // token kind is a valid type specifier
130 case tok::kw___int64:
131 case tok::kw___int128:
133 case tok::kw_unsigned:
140 case tok::kw__Float16:
141 case tok::kw___float128:
142 case tok::kw_wchar_t:
144 case tok::kw___underlying_type:
145 case tok::kw___auto_type:
148 case tok::annot_typename:
149 case tok::kw_char16_t:
150 case tok::kw_char32_t:
152 case tok::annot_decltype:
153 case tok::kw_decltype:
154 return getLangOpts().CPlusPlus;
156 case tok::kw_char8_t:
157 return getLangOpts().Char8;
167 enum class UnqualifiedTypeNameLookupResult {
172 } // end anonymous namespace
174 /// Tries to perform unqualified lookup of the type decls in bases for
176 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
177 /// type decl, \a FoundType if only type decls are found.
178 static UnqualifiedTypeNameLookupResult
179 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
180 SourceLocation NameLoc,
181 const CXXRecordDecl *RD) {
182 if (!RD->hasDefinition())
183 return UnqualifiedTypeNameLookupResult::NotFound;
184 // Look for type decls in base classes.
185 UnqualifiedTypeNameLookupResult FoundTypeDecl =
186 UnqualifiedTypeNameLookupResult::NotFound;
187 for (const auto &Base : RD->bases()) {
188 const CXXRecordDecl *BaseRD = nullptr;
189 if (auto *BaseTT = Base.getType()->getAs<TagType>())
190 BaseRD = BaseTT->getAsCXXRecordDecl();
191 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
192 // Look for type decls in dependent base classes that have known primary
194 if (!TST || !TST->isDependentType())
196 auto *TD = TST->getTemplateName().getAsTemplateDecl();
199 if (auto *BasePrimaryTemplate =
200 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
201 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
202 BaseRD = BasePrimaryTemplate;
203 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
204 if (const ClassTemplatePartialSpecializationDecl *PS =
205 CTD->findPartialSpecialization(Base.getType()))
206 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
212 for (NamedDecl *ND : BaseRD->lookup(&II)) {
213 if (!isa<TypeDecl>(ND))
214 return UnqualifiedTypeNameLookupResult::FoundNonType;
215 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
217 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
218 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
219 case UnqualifiedTypeNameLookupResult::FoundNonType:
220 return UnqualifiedTypeNameLookupResult::FoundNonType;
221 case UnqualifiedTypeNameLookupResult::FoundType:
222 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
224 case UnqualifiedTypeNameLookupResult::NotFound:
231 return FoundTypeDecl;
234 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
235 const IdentifierInfo &II,
236 SourceLocation NameLoc) {
237 // Lookup in the parent class template context, if any.
238 const CXXRecordDecl *RD = nullptr;
239 UnqualifiedTypeNameLookupResult FoundTypeDecl =
240 UnqualifiedTypeNameLookupResult::NotFound;
241 for (DeclContext *DC = S.CurContext;
242 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
243 DC = DC->getParent()) {
244 // Look for type decls in dependent base classes that have known primary
246 RD = dyn_cast<CXXRecordDecl>(DC);
247 if (RD && RD->getDescribedClassTemplate())
248 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
250 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253 // We found some types in dependent base classes. Recover as if the user
254 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
255 // lookup during template instantiation.
256 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
258 ASTContext &Context = S.Context;
259 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
260 cast<Type>(Context.getRecordType(RD)));
261 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
264 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
266 TypeLocBuilder Builder;
267 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
268 DepTL.setNameLoc(NameLoc);
269 DepTL.setElaboratedKeywordLoc(SourceLocation());
270 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
271 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274 /// If the identifier refers to a type name within this scope,
275 /// return the declaration of that type.
277 /// This routine performs ordinary name lookup of the identifier II
278 /// within the given scope, with optional C++ scope specifier SS, to
279 /// determine whether the name refers to a type. If so, returns an
280 /// opaque pointer (actually a QualType) corresponding to that
281 /// type. Otherwise, returns NULL.
282 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
283 Scope *S, CXXScopeSpec *SS,
284 bool isClassName, bool HasTrailingDot,
285 ParsedType ObjectTypePtr,
286 bool IsCtorOrDtorName,
287 bool WantNontrivialTypeSourceInfo,
288 bool IsClassTemplateDeductionContext,
289 IdentifierInfo **CorrectedII) {
290 // FIXME: Consider allowing this outside C++1z mode as an extension.
291 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
292 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
293 !isClassName && !HasTrailingDot;
295 // Determine where we will perform name lookup.
296 DeclContext *LookupCtx = nullptr;
298 QualType ObjectType = ObjectTypePtr.get();
299 if (ObjectType->isRecordType())
300 LookupCtx = computeDeclContext(ObjectType);
301 } else if (SS && SS->isNotEmpty()) {
302 LookupCtx = computeDeclContext(*SS, false);
305 if (isDependentScopeSpecifier(*SS)) {
307 // A qualified-id that refers to a type and in which the
308 // nested-name-specifier depends on a template-parameter (14.6.2)
309 // shall be prefixed by the keyword typename to indicate that the
310 // qualified-id denotes a type, forming an
311 // elaborated-type-specifier (7.1.5.3).
313 // We therefore do not perform any name lookup if the result would
314 // refer to a member of an unknown specialization.
315 if (!isClassName && !IsCtorOrDtorName)
318 // We know from the grammar that this name refers to a type,
319 // so build a dependent node to describe the type.
320 if (WantNontrivialTypeSourceInfo)
321 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
323 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
324 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
326 return ParsedType::make(T);
332 if (!LookupCtx->isDependentContext() &&
333 RequireCompleteDeclContext(*SS, LookupCtx))
337 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
338 // lookup for class-names.
339 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
341 LookupResult Result(*this, &II, NameLoc, Kind);
343 // Perform "qualified" name lookup into the declaration context we
344 // computed, which is either the type of the base of a member access
345 // expression or the declaration context associated with a prior
346 // nested-name-specifier.
347 LookupQualifiedName(Result, LookupCtx);
349 if (ObjectTypePtr && Result.empty()) {
350 // C++ [basic.lookup.classref]p3:
351 // If the unqualified-id is ~type-name, the type-name is looked up
352 // in the context of the entire postfix-expression. If the type T of
353 // the object expression is of a class type C, the type-name is also
354 // looked up in the scope of class C. At least one of the lookups shall
355 // find a name that refers to (possibly cv-qualified) T.
356 LookupName(Result, S);
359 // Perform unqualified name lookup.
360 LookupName(Result, S);
362 // For unqualified lookup in a class template in MSVC mode, look into
363 // dependent base classes where the primary class template is known.
364 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
365 if (ParsedType TypeInBase =
366 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
371 NamedDecl *IIDecl = nullptr;
372 switch (Result.getResultKind()) {
373 case LookupResult::NotFound:
374 case LookupResult::NotFoundInCurrentInstantiation:
376 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
377 AllowDeducedTemplate);
378 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
379 S, SS, CCC, CTK_ErrorRecovery);
380 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
382 bool MemberOfUnknownSpecialization;
383 UnqualifiedId TemplateName;
384 TemplateName.setIdentifier(NewII, NameLoc);
385 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
386 CXXScopeSpec NewSS, *NewSSPtr = SS;
388 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
391 if (Correction && (NNS || NewII != &II) &&
392 // Ignore a correction to a template type as the to-be-corrected
393 // identifier is not a template (typo correction for template names
394 // is handled elsewhere).
395 !(getLangOpts().CPlusPlus && NewSSPtr &&
396 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
397 Template, MemberOfUnknownSpecialization))) {
398 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
399 isClassName, HasTrailingDot, ObjectTypePtr,
401 WantNontrivialTypeSourceInfo,
402 IsClassTemplateDeductionContext);
404 diagnoseTypo(Correction,
405 PDiag(diag::err_unknown_type_or_class_name_suggest)
406 << Result.getLookupName() << isClassName);
408 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
409 *CorrectedII = NewII;
414 // If typo correction failed or was not performed, fall through
416 case LookupResult::FoundOverloaded:
417 case LookupResult::FoundUnresolvedValue:
418 Result.suppressDiagnostics();
421 case LookupResult::Ambiguous:
422 // Recover from type-hiding ambiguities by hiding the type. We'll
423 // do the lookup again when looking for an object, and we can
424 // diagnose the error then. If we don't do this, then the error
425 // about hiding the type will be immediately followed by an error
426 // that only makes sense if the identifier was treated like a type.
427 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
428 Result.suppressDiagnostics();
432 // Look to see if we have a type anywhere in the list of results.
433 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
434 Res != ResEnd; ++Res) {
435 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
436 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
438 (*Res)->getLocation().getRawEncoding() <
439 IIDecl->getLocation().getRawEncoding())
445 // None of the entities we found is a type, so there is no way
446 // to even assume that the result is a type. In this case, don't
447 // complain about the ambiguity. The parser will either try to
448 // perform this lookup again (e.g., as an object name), which
449 // will produce the ambiguity, or will complain that it expected
451 Result.suppressDiagnostics();
455 // We found a type within the ambiguous lookup; diagnose the
456 // ambiguity and then return that type. This might be the right
457 // answer, or it might not be, but it suppresses any attempt to
458 // perform the name lookup again.
461 case LookupResult::Found:
462 IIDecl = Result.getFoundDecl();
466 assert(IIDecl && "Didn't find decl");
469 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
470 // C++ [class.qual]p2: A lookup that would find the injected-class-name
471 // instead names the constructors of the class, except when naming a class.
472 // This is ill-formed when we're not actually forming a ctor or dtor name.
473 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
474 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
475 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
476 FoundRD->isInjectedClassName() &&
477 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
478 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
481 DiagnoseUseOfDecl(IIDecl, NameLoc);
483 T = Context.getTypeDeclType(TD);
484 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
485 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
486 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
488 T = Context.getObjCInterfaceType(IDecl);
489 } else if (AllowDeducedTemplate) {
490 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
491 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
496 // If it's not plausibly a type, suppress diagnostics.
497 Result.suppressDiagnostics();
501 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
502 // constructor or destructor name (in such a case, the scope specifier
503 // will be attached to the enclosing Expr or Decl node).
504 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
505 !isa<ObjCInterfaceDecl>(IIDecl)) {
506 if (WantNontrivialTypeSourceInfo) {
507 // Construct a type with type-source information.
508 TypeLocBuilder Builder;
509 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
511 T = getElaboratedType(ETK_None, *SS, T);
512 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
513 ElabTL.setElaboratedKeywordLoc(SourceLocation());
514 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
515 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
517 T = getElaboratedType(ETK_None, *SS, T);
521 return ParsedType::make(T);
524 // Builds a fake NNS for the given decl context.
525 static NestedNameSpecifier *
526 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
527 for (;; DC = DC->getLookupParent()) {
528 DC = DC->getPrimaryContext();
529 auto *ND = dyn_cast<NamespaceDecl>(DC);
530 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
531 return NestedNameSpecifier::Create(Context, nullptr, ND);
532 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
533 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
534 RD->getTypeForDecl());
535 else if (isa<TranslationUnitDecl>(DC))
536 return NestedNameSpecifier::GlobalSpecifier(Context);
538 llvm_unreachable("something isn't in TU scope?");
541 /// Find the parent class with dependent bases of the innermost enclosing method
542 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
543 /// up allowing unqualified dependent type names at class-level, which MSVC
544 /// correctly rejects.
545 static const CXXRecordDecl *
546 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
547 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
548 DC = DC->getPrimaryContext();
549 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
550 if (MD->getParent()->hasAnyDependentBases())
551 return MD->getParent();
556 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
557 SourceLocation NameLoc,
558 bool IsTemplateTypeArg) {
559 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
561 NestedNameSpecifier *NNS = nullptr;
562 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
563 // If we weren't able to parse a default template argument, delay lookup
564 // until instantiation time by making a non-dependent DependentTypeName. We
565 // pretend we saw a NestedNameSpecifier referring to the current scope, and
566 // lookup is retried.
567 // FIXME: This hurts our diagnostic quality, since we get errors like "no
568 // type named 'Foo' in 'current_namespace'" when the user didn't write any
570 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
571 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
572 } else if (const CXXRecordDecl *RD =
573 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
574 // Build a DependentNameType that will perform lookup into RD at
575 // instantiation time.
576 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
577 RD->getTypeForDecl());
579 // Diagnose that this identifier was undeclared, and retry the lookup during
580 // template instantiation.
581 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
584 // This is not a situation that we should recover from.
588 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
590 // Build type location information. We synthesized the qualifier, so we have
591 // to build a fake NestedNameSpecifierLoc.
592 NestedNameSpecifierLocBuilder NNSLocBuilder;
593 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
594 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
596 TypeLocBuilder Builder;
597 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
598 DepTL.setNameLoc(NameLoc);
599 DepTL.setElaboratedKeywordLoc(SourceLocation());
600 DepTL.setQualifierLoc(QualifierLoc);
601 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
604 /// isTagName() - This method is called *for error recovery purposes only*
605 /// to determine if the specified name is a valid tag name ("struct foo"). If
606 /// so, this returns the TST for the tag corresponding to it (TST_enum,
607 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
608 /// cases in C where the user forgot to specify the tag.
609 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
610 // Do a tag name lookup in this scope.
611 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
612 LookupName(R, S, false);
613 R.suppressDiagnostics();
614 if (R.getResultKind() == LookupResult::Found)
615 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
616 switch (TD->getTagKind()) {
617 case TTK_Struct: return DeclSpec::TST_struct;
618 case TTK_Interface: return DeclSpec::TST_interface;
619 case TTK_Union: return DeclSpec::TST_union;
620 case TTK_Class: return DeclSpec::TST_class;
621 case TTK_Enum: return DeclSpec::TST_enum;
625 return DeclSpec::TST_unspecified;
628 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
629 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
630 /// then downgrade the missing typename error to a warning.
631 /// This is needed for MSVC compatibility; Example:
633 /// template<class T> class A {
635 /// typedef int TYPE;
637 /// template<class T> class B : public A<T> {
639 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
642 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
643 if (CurContext->isRecord()) {
644 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
647 const Type *Ty = SS->getScopeRep()->getAsType();
649 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
650 for (const auto &Base : RD->bases())
651 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
653 return S->isFunctionPrototypeScope();
655 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
658 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
659 SourceLocation IILoc,
662 ParsedType &SuggestedType,
663 bool IsTemplateName) {
664 // Don't report typename errors for editor placeholders.
665 if (II->isEditorPlaceholder())
667 // We don't have anything to suggest (yet).
668 SuggestedType = nullptr;
670 // There may have been a typo in the name of the type. Look up typo
671 // results, in case we have something that we can suggest.
672 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
673 /*AllowTemplates=*/IsTemplateName,
674 /*AllowNonTemplates=*/!IsTemplateName);
675 if (TypoCorrection Corrected =
676 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
677 CCC, CTK_ErrorRecovery)) {
678 // FIXME: Support error recovery for the template-name case.
679 bool CanRecover = !IsTemplateName;
680 if (Corrected.isKeyword()) {
681 // We corrected to a keyword.
682 diagnoseTypo(Corrected,
683 PDiag(IsTemplateName ? diag::err_no_template_suggest
684 : diag::err_unknown_typename_suggest)
686 II = Corrected.getCorrectionAsIdentifierInfo();
688 // We found a similarly-named type or interface; suggest that.
689 if (!SS || !SS->isSet()) {
690 diagnoseTypo(Corrected,
691 PDiag(IsTemplateName ? diag::err_no_template_suggest
692 : diag::err_unknown_typename_suggest)
694 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
695 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
696 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
697 II->getName().equals(CorrectedStr);
698 diagnoseTypo(Corrected,
700 ? diag::err_no_member_template_suggest
701 : diag::err_unknown_nested_typename_suggest)
702 << II << DC << DroppedSpecifier << SS->getRange(),
705 llvm_unreachable("could not have corrected a typo here");
712 if (Corrected.getCorrectionSpecifier())
713 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
715 // FIXME: Support class template argument deduction here.
717 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
718 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
719 /*IsCtorOrDtorName=*/false,
720 /*WantNontrivialTypeSourceInfo=*/true);
725 if (getLangOpts().CPlusPlus && !IsTemplateName) {
726 // See if II is a class template that the user forgot to pass arguments to.
728 Name.setIdentifier(II, IILoc);
729 CXXScopeSpec EmptySS;
730 TemplateTy TemplateResult;
731 bool MemberOfUnknownSpecialization;
732 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
733 Name, nullptr, true, TemplateResult,
734 MemberOfUnknownSpecialization) == TNK_Type_template) {
735 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
740 // FIXME: Should we move the logic that tries to recover from a missing tag
741 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
743 if (!SS || (!SS->isSet() && !SS->isInvalid()))
744 Diag(IILoc, IsTemplateName ? diag::err_no_template
745 : diag::err_unknown_typename)
747 else if (DeclContext *DC = computeDeclContext(*SS, false))
748 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
749 : diag::err_typename_nested_not_found)
750 << II << DC << SS->getRange();
751 else if (isDependentScopeSpecifier(*SS)) {
752 unsigned DiagID = diag::err_typename_missing;
753 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
754 DiagID = diag::ext_typename_missing;
756 Diag(SS->getRange().getBegin(), DiagID)
757 << SS->getScopeRep() << II->getName()
758 << SourceRange(SS->getRange().getBegin(), IILoc)
759 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
760 SuggestedType = ActOnTypenameType(S, SourceLocation(),
761 *SS, *II, IILoc).get();
763 assert(SS && SS->isInvalid() &&
764 "Invalid scope specifier has already been diagnosed");
768 /// Determine whether the given result set contains either a type name
770 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
771 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
772 NextToken.is(tok::less);
774 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
775 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
778 if (CheckTemplate && isa<TemplateDecl>(*I))
785 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
786 Scope *S, CXXScopeSpec &SS,
787 IdentifierInfo *&Name,
788 SourceLocation NameLoc) {
789 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
790 SemaRef.LookupParsedName(R, S, &SS);
791 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
792 StringRef FixItTagName;
793 switch (Tag->getTagKind()) {
795 FixItTagName = "class ";
799 FixItTagName = "enum ";
803 FixItTagName = "struct ";
807 FixItTagName = "__interface ";
811 FixItTagName = "union ";
815 StringRef TagName = FixItTagName.drop_back();
816 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
817 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
818 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
820 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
822 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
825 // Replace lookup results with just the tag decl.
826 Result.clear(Sema::LookupTagName);
827 SemaRef.LookupParsedName(Result, S, &SS);
834 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
835 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
836 QualType T, SourceLocation NameLoc) {
837 ASTContext &Context = S.Context;
839 TypeLocBuilder Builder;
840 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
842 T = S.getElaboratedType(ETK_None, SS, T);
843 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
844 ElabTL.setElaboratedKeywordLoc(SourceLocation());
845 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
846 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
849 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
850 IdentifierInfo *&Name,
851 SourceLocation NameLoc,
852 const Token &NextToken,
853 CorrectionCandidateCallback *CCC) {
854 DeclarationNameInfo NameInfo(Name, NameLoc);
855 ObjCMethodDecl *CurMethod = getCurMethodDecl();
857 assert(NextToken.isNot(tok::coloncolon) &&
858 "parse nested name specifiers before calling ClassifyName");
859 if (getLangOpts().CPlusPlus && SS.isSet() &&
860 isCurrentClassName(*Name, S, &SS)) {
861 // Per [class.qual]p2, this names the constructors of SS, not the
862 // injected-class-name. We don't have a classification for that.
863 // There's not much point caching this result, since the parser
864 // will reject it later.
865 return NameClassification::Unknown();
868 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
869 LookupParsedName(Result, S, &SS, !CurMethod);
872 return NameClassification::Error();
874 // For unqualified lookup in a class template in MSVC mode, look into
875 // dependent base classes where the primary class template is known.
876 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
877 if (ParsedType TypeInBase =
878 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
882 // Perform lookup for Objective-C instance variables (including automatically
883 // synthesized instance variables), if we're in an Objective-C method.
884 // FIXME: This lookup really, really needs to be folded in to the normal
885 // unqualified lookup mechanism.
886 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
887 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
888 if (Ivar.isInvalid())
889 return NameClassification::Error();
891 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
893 // We defer builtin creation until after ivar lookup inside ObjC methods.
895 LookupBuiltin(Result);
898 bool SecondTry = false;
899 bool IsFilteredTemplateName = false;
902 switch (Result.getResultKind()) {
903 case LookupResult::NotFound:
904 // If an unqualified-id is followed by a '(', then we have a function
906 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
907 // In C++, this is an ADL-only call.
909 if (getLangOpts().CPlusPlus)
910 return NameClassification::UndeclaredNonType();
913 // If the expression that precedes the parenthesized argument list in a
914 // function call consists solely of an identifier, and if no
915 // declaration is visible for this identifier, the identifier is
916 // implicitly declared exactly as if, in the innermost block containing
917 // the function call, the declaration
919 // extern int identifier ();
923 // We also allow this in C99 as an extension.
924 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
925 return NameClassification::NonType(D);
928 if (getLangOpts().CPlusPlus2a && SS.isEmpty() && NextToken.is(tok::less)) {
929 // In C++20 onwards, this could be an ADL-only call to a function
930 // template, and we're required to assume that this is a template name.
932 // FIXME: Find a way to still do typo correction in this case.
933 TemplateName Template =
934 Context.getAssumedTemplateName(NameInfo.getName());
935 return NameClassification::UndeclaredTemplate(Template);
938 // In C, we first see whether there is a tag type by the same name, in
939 // which case it's likely that the user just forgot to write "enum",
940 // "struct", or "union".
941 if (!getLangOpts().CPlusPlus && !SecondTry &&
942 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
946 // Perform typo correction to determine if there is another name that is
947 // close to this name.
948 if (!SecondTry && CCC) {
950 if (TypoCorrection Corrected =
951 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
952 &SS, *CCC, CTK_ErrorRecovery)) {
953 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
954 unsigned QualifiedDiag = diag::err_no_member_suggest;
956 NamedDecl *FirstDecl = Corrected.getFoundDecl();
957 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
958 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
959 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
960 UnqualifiedDiag = diag::err_no_template_suggest;
961 QualifiedDiag = diag::err_no_member_template_suggest;
962 } else if (UnderlyingFirstDecl &&
963 (isa<TypeDecl>(UnderlyingFirstDecl) ||
964 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
965 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
966 UnqualifiedDiag = diag::err_unknown_typename_suggest;
967 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
971 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
972 } else {// FIXME: is this even reachable? Test it.
973 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
974 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
975 Name->getName().equals(CorrectedStr);
976 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
977 << Name << computeDeclContext(SS, false)
978 << DroppedSpecifier << SS.getRange());
981 // Update the name, so that the caller has the new name.
982 Name = Corrected.getCorrectionAsIdentifierInfo();
984 // Typo correction corrected to a keyword.
985 if (Corrected.isKeyword())
988 // Also update the LookupResult...
989 // FIXME: This should probably go away at some point
991 Result.setLookupName(Corrected.getCorrection());
993 Result.addDecl(FirstDecl);
995 // If we found an Objective-C instance variable, let
996 // LookupInObjCMethod build the appropriate expression to
997 // reference the ivar.
998 // FIXME: This is a gross hack.
999 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1001 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1003 return NameClassification::Error();
1005 return NameClassification::NonType(Ivar);
1012 // We failed to correct; just fall through and let the parser deal with it.
1013 Result.suppressDiagnostics();
1014 return NameClassification::Unknown();
1016 case LookupResult::NotFoundInCurrentInstantiation: {
1017 // We performed name lookup into the current instantiation, and there were
1018 // dependent bases, so we treat this result the same way as any other
1019 // dependent nested-name-specifier.
1021 // C++ [temp.res]p2:
1022 // A name used in a template declaration or definition and that is
1023 // dependent on a template-parameter is assumed not to name a type
1024 // unless the applicable name lookup finds a type name or the name is
1025 // qualified by the keyword typename.
1027 // FIXME: If the next token is '<', we might want to ask the parser to
1028 // perform some heroics to see if we actually have a
1029 // template-argument-list, which would indicate a missing 'template'
1031 return NameClassification::DependentNonType();
1034 case LookupResult::Found:
1035 case LookupResult::FoundOverloaded:
1036 case LookupResult::FoundUnresolvedValue:
1039 case LookupResult::Ambiguous:
1040 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1041 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1042 /*AllowDependent=*/false)) {
1043 // C++ [temp.local]p3:
1044 // A lookup that finds an injected-class-name (10.2) can result in an
1045 // ambiguity in certain cases (for example, if it is found in more than
1046 // one base class). If all of the injected-class-names that are found
1047 // refer to specializations of the same class template, and if the name
1048 // is followed by a template-argument-list, the reference refers to the
1049 // class template itself and not a specialization thereof, and is not
1052 // This filtering can make an ambiguous result into an unambiguous one,
1053 // so try again after filtering out template names.
1054 FilterAcceptableTemplateNames(Result);
1055 if (!Result.isAmbiguous()) {
1056 IsFilteredTemplateName = true;
1061 // Diagnose the ambiguity and return an error.
1062 return NameClassification::Error();
1065 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1066 (IsFilteredTemplateName ||
1067 hasAnyAcceptableTemplateNames(
1068 Result, /*AllowFunctionTemplates=*/true,
1069 /*AllowDependent=*/false,
1070 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1071 getLangOpts().CPlusPlus2a))) {
1072 // C++ [temp.names]p3:
1073 // After name lookup (3.4) finds that a name is a template-name or that
1074 // an operator-function-id or a literal- operator-id refers to a set of
1075 // overloaded functions any member of which is a function template if
1076 // this is followed by a <, the < is always taken as the delimiter of a
1077 // template-argument-list and never as the less-than operator.
1078 // C++2a [temp.names]p2:
1079 // A name is also considered to refer to a template if it is an
1080 // unqualified-id followed by a < and name lookup finds either one
1081 // or more functions or finds nothing.
1082 if (!IsFilteredTemplateName)
1083 FilterAcceptableTemplateNames(Result);
1085 bool IsFunctionTemplate;
1087 TemplateName Template;
1088 if (Result.end() - Result.begin() > 1) {
1089 IsFunctionTemplate = true;
1090 Template = Context.getOverloadedTemplateName(Result.begin(),
1092 } else if (!Result.empty()) {
1093 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1094 *Result.begin(), /*AllowFunctionTemplates=*/true,
1095 /*AllowDependent=*/false));
1096 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1097 IsVarTemplate = isa<VarTemplateDecl>(TD);
1099 if (SS.isNotEmpty())
1101 Context.getQualifiedTemplateName(SS.getScopeRep(),
1102 /*TemplateKeyword=*/false, TD);
1104 Template = TemplateName(TD);
1106 // All results were non-template functions. This is a function template
1108 IsFunctionTemplate = true;
1109 Template = Context.getAssumedTemplateName(NameInfo.getName());
1112 if (IsFunctionTemplate) {
1113 // Function templates always go through overload resolution, at which
1114 // point we'll perform the various checks (e.g., accessibility) we need
1115 // to based on which function we selected.
1116 Result.suppressDiagnostics();
1118 return NameClassification::FunctionTemplate(Template);
1121 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1122 : NameClassification::TypeTemplate(Template);
1125 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1126 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1127 DiagnoseUseOfDecl(Type, NameLoc);
1128 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1129 QualType T = Context.getTypeDeclType(Type);
1130 if (SS.isNotEmpty())
1131 return buildNestedType(*this, SS, T, NameLoc);
1132 return ParsedType::make(T);
1135 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1137 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1138 if (ObjCCompatibleAliasDecl *Alias =
1139 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1140 Class = Alias->getClassInterface();
1144 DiagnoseUseOfDecl(Class, NameLoc);
1146 if (NextToken.is(tok::period)) {
1147 // Interface. <something> is parsed as a property reference expression.
1148 // Just return "unknown" as a fall-through for now.
1149 Result.suppressDiagnostics();
1150 return NameClassification::Unknown();
1153 QualType T = Context.getObjCInterfaceType(Class);
1154 return ParsedType::make(T);
1157 if (isa<ConceptDecl>(FirstDecl))
1158 return NameClassification::Concept(
1159 TemplateName(cast<TemplateDecl>(FirstDecl)));
1161 // We can have a type template here if we're classifying a template argument.
1162 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1163 !isa<VarTemplateDecl>(FirstDecl))
1164 return NameClassification::TypeTemplate(
1165 TemplateName(cast<TemplateDecl>(FirstDecl)));
1167 // Check for a tag type hidden by a non-type decl in a few cases where it
1168 // seems likely a type is wanted instead of the non-type that was found.
1169 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1170 if ((NextToken.is(tok::identifier) ||
1172 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1173 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1174 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1175 DiagnoseUseOfDecl(Type, NameLoc);
1176 QualType T = Context.getTypeDeclType(Type);
1177 if (SS.isNotEmpty())
1178 return buildNestedType(*this, SS, T, NameLoc);
1179 return ParsedType::make(T);
1182 // FIXME: This is context-dependent. We need to defer building the member
1183 // expression until the classification is consumed.
1184 if (FirstDecl->isCXXClassMember())
1185 return NameClassification::ContextIndependentExpr(
1186 BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr,
1189 // If we already know which single declaration is referenced, just annotate
1190 // that declaration directly.
1191 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1192 if (Result.isSingleResult() && !ADL)
1193 return NameClassification::NonType(Result.getRepresentativeDecl());
1195 // Build an UnresolvedLookupExpr. Note that this doesn't depend on the
1196 // context in which we performed classification, so it's safe to do now.
1197 return NameClassification::ContextIndependentExpr(
1198 BuildDeclarationNameExpr(SS, Result, ADL));
1202 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1203 SourceLocation NameLoc) {
1204 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1206 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1207 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1211 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1212 IdentifierInfo *Name,
1213 SourceLocation NameLoc,
1214 bool IsAddressOfOperand) {
1215 DeclarationNameInfo NameInfo(Name, NameLoc);
1216 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1217 NameInfo, IsAddressOfOperand,
1218 /*TemplateArgs=*/nullptr);
1221 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1223 SourceLocation NameLoc,
1224 const Token &NextToken) {
1225 if (getCurMethodDecl() && SS.isEmpty())
1226 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1227 return BuildIvarRefExpr(S, NameLoc, Ivar);
1229 // Reconstruct the lookup result.
1230 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1231 Result.addDecl(Found);
1232 Result.resolveKind();
1234 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1235 return BuildDeclarationNameExpr(SS, Result, ADL);
1238 Sema::TemplateNameKindForDiagnostics
1239 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1240 auto *TD = Name.getAsTemplateDecl();
1242 return TemplateNameKindForDiagnostics::DependentTemplate;
1243 if (isa<ClassTemplateDecl>(TD))
1244 return TemplateNameKindForDiagnostics::ClassTemplate;
1245 if (isa<FunctionTemplateDecl>(TD))
1246 return TemplateNameKindForDiagnostics::FunctionTemplate;
1247 if (isa<VarTemplateDecl>(TD))
1248 return TemplateNameKindForDiagnostics::VarTemplate;
1249 if (isa<TypeAliasTemplateDecl>(TD))
1250 return TemplateNameKindForDiagnostics::AliasTemplate;
1251 if (isa<TemplateTemplateParmDecl>(TD))
1252 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1253 if (isa<ConceptDecl>(TD))
1254 return TemplateNameKindForDiagnostics::Concept;
1255 return TemplateNameKindForDiagnostics::DependentTemplate;
1258 // Determines the context to return to after temporarily entering a
1259 // context. This depends in an unnecessarily complicated way on the
1260 // exact ordering of callbacks from the parser.
1261 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1263 // Functions defined inline within classes aren't parsed until we've
1264 // finished parsing the top-level class, so the top-level class is
1265 // the context we'll need to return to.
1266 // A Lambda call operator whose parent is a class must not be treated
1267 // as an inline member function. A Lambda can be used legally
1268 // either as an in-class member initializer or a default argument. These
1269 // are parsed once the class has been marked complete and so the containing
1270 // context would be the nested class (when the lambda is defined in one);
1271 // If the class is not complete, then the lambda is being used in an
1272 // ill-formed fashion (such as to specify the width of a bit-field, or
1273 // in an array-bound) - in which case we still want to return the
1274 // lexically containing DC (which could be a nested class).
1275 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1276 DC = DC->getLexicalParent();
1278 // A function not defined within a class will always return to its
1280 if (!isa<CXXRecordDecl>(DC))
1283 // A C++ inline method/friend is parsed *after* the topmost class
1284 // it was declared in is fully parsed ("complete"); the topmost
1285 // class is the context we need to return to.
1286 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1289 // Return the declaration context of the topmost class the inline method is
1294 return DC->getLexicalParent();
1297 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1298 assert(getContainingDC(DC) == CurContext &&
1299 "The next DeclContext should be lexically contained in the current one.");
1304 void Sema::PopDeclContext() {
1305 assert(CurContext && "DeclContext imbalance!");
1307 CurContext = getContainingDC(CurContext);
1308 assert(CurContext && "Popped translation unit!");
1311 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1313 // Unlike PushDeclContext, the context to which we return is not necessarily
1314 // the containing DC of TD, because the new context will be some pre-existing
1315 // TagDecl definition instead of a fresh one.
1316 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1317 CurContext = cast<TagDecl>(D)->getDefinition();
1318 assert(CurContext && "skipping definition of undefined tag");
1319 // Start lookups from the parent of the current context; we don't want to look
1320 // into the pre-existing complete definition.
1321 S->setEntity(CurContext->getLookupParent());
1325 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1326 CurContext = static_cast<decltype(CurContext)>(Context);
1329 /// EnterDeclaratorContext - Used when we must lookup names in the context
1330 /// of a declarator's nested name specifier.
1332 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1333 // C++0x [basic.lookup.unqual]p13:
1334 // A name used in the definition of a static data member of class
1335 // X (after the qualified-id of the static member) is looked up as
1336 // if the name was used in a member function of X.
1337 // C++0x [basic.lookup.unqual]p14:
1338 // If a variable member of a namespace is defined outside of the
1339 // scope of its namespace then any name used in the definition of
1340 // the variable member (after the declarator-id) is looked up as
1341 // if the definition of the variable member occurred in its
1343 // Both of these imply that we should push a scope whose context
1344 // is the semantic context of the declaration. We can't use
1345 // PushDeclContext here because that context is not necessarily
1346 // lexically contained in the current context. Fortunately,
1347 // the containing scope should have the appropriate information.
1349 assert(!S->getEntity() && "scope already has entity");
1352 Scope *Ancestor = S->getParent();
1353 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1354 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1361 void Sema::ExitDeclaratorContext(Scope *S) {
1362 assert(S->getEntity() == CurContext && "Context imbalance!");
1364 // Switch back to the lexical context. The safety of this is
1365 // enforced by an assert in EnterDeclaratorContext.
1366 Scope *Ancestor = S->getParent();
1367 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1368 CurContext = Ancestor->getEntity();
1370 // We don't need to do anything with the scope, which is going to
1374 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1375 // We assume that the caller has already called
1376 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1377 FunctionDecl *FD = D->getAsFunction();
1381 // Same implementation as PushDeclContext, but enters the context
1382 // from the lexical parent, rather than the top-level class.
1383 assert(CurContext == FD->getLexicalParent() &&
1384 "The next DeclContext should be lexically contained in the current one.");
1386 S->setEntity(CurContext);
1388 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1389 ParmVarDecl *Param = FD->getParamDecl(P);
1390 // If the parameter has an identifier, then add it to the scope
1391 if (Param->getIdentifier()) {
1393 IdResolver.AddDecl(Param);
1398 void Sema::ActOnExitFunctionContext() {
1399 // Same implementation as PopDeclContext, but returns to the lexical parent,
1400 // rather than the top-level class.
1401 assert(CurContext && "DeclContext imbalance!");
1402 CurContext = CurContext->getLexicalParent();
1403 assert(CurContext && "Popped translation unit!");
1406 /// Determine whether we allow overloading of the function
1407 /// PrevDecl with another declaration.
1409 /// This routine determines whether overloading is possible, not
1410 /// whether some new function is actually an overload. It will return
1411 /// true in C++ (where we can always provide overloads) or, as an
1412 /// extension, in C when the previous function is already an
1413 /// overloaded function declaration or has the "overloadable"
1415 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1416 ASTContext &Context,
1417 const FunctionDecl *New) {
1418 if (Context.getLangOpts().CPlusPlus)
1421 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1424 return Previous.getResultKind() == LookupResult::Found &&
1425 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1426 New->hasAttr<OverloadableAttr>());
1429 /// Add this decl to the scope shadowed decl chains.
1430 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1431 // Move up the scope chain until we find the nearest enclosing
1432 // non-transparent context. The declaration will be introduced into this
1434 while (S->getEntity() && S->getEntity()->isTransparentContext())
1437 // Add scoped declarations into their context, so that they can be
1438 // found later. Declarations without a context won't be inserted
1439 // into any context.
1441 CurContext->addDecl(D);
1443 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1444 // are function-local declarations.
1445 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1446 !D->getDeclContext()->getRedeclContext()->Equals(
1447 D->getLexicalDeclContext()->getRedeclContext()) &&
1448 !D->getLexicalDeclContext()->isFunctionOrMethod())
1451 // Template instantiations should also not be pushed into scope.
1452 if (isa<FunctionDecl>(D) &&
1453 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1456 // If this replaces anything in the current scope,
1457 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1458 IEnd = IdResolver.end();
1459 for (; I != IEnd; ++I) {
1460 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1462 IdResolver.RemoveDecl(*I);
1464 // Should only need to replace one decl.
1471 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1472 // Implicitly-generated labels may end up getting generated in an order that
1473 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1474 // the label at the appropriate place in the identifier chain.
1475 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1476 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1477 if (IDC == CurContext) {
1478 if (!S->isDeclScope(*I))
1480 } else if (IDC->Encloses(CurContext))
1484 IdResolver.InsertDeclAfter(I, D);
1486 IdResolver.AddDecl(D);
1490 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1491 bool AllowInlineNamespace) {
1492 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1495 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1496 DeclContext *TargetDC = DC->getPrimaryContext();
1498 if (DeclContext *ScopeDC = S->getEntity())
1499 if (ScopeDC->getPrimaryContext() == TargetDC)
1501 } while ((S = S->getParent()));
1506 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1510 /// Filters out lookup results that don't fall within the given scope
1511 /// as determined by isDeclInScope.
1512 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1513 bool ConsiderLinkage,
1514 bool AllowInlineNamespace) {
1515 LookupResult::Filter F = R.makeFilter();
1516 while (F.hasNext()) {
1517 NamedDecl *D = F.next();
1519 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1522 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1531 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1532 /// have compatible owning modules.
1533 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1534 // FIXME: The Modules TS is not clear about how friend declarations are
1535 // to be treated. It's not meaningful to have different owning modules for
1536 // linkage in redeclarations of the same entity, so for now allow the
1537 // redeclaration and change the owning modules to match.
1538 if (New->getFriendObjectKind() &&
1539 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1540 New->setLocalOwningModule(Old->getOwningModule());
1541 makeMergedDefinitionVisible(New);
1545 Module *NewM = New->getOwningModule();
1546 Module *OldM = Old->getOwningModule();
1548 if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1549 NewM = NewM->Parent;
1550 if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1551 OldM = OldM->Parent;
1556 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1557 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1558 if (NewIsModuleInterface || OldIsModuleInterface) {
1559 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1560 // if a declaration of D [...] appears in the purview of a module, all
1561 // other such declarations shall appear in the purview of the same module
1562 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1564 << NewIsModuleInterface
1565 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1566 << OldIsModuleInterface
1567 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1568 Diag(Old->getLocation(), diag::note_previous_declaration);
1569 New->setInvalidDecl();
1576 static bool isUsingDecl(NamedDecl *D) {
1577 return isa<UsingShadowDecl>(D) ||
1578 isa<UnresolvedUsingTypenameDecl>(D) ||
1579 isa<UnresolvedUsingValueDecl>(D);
1582 /// Removes using shadow declarations from the lookup results.
1583 static void RemoveUsingDecls(LookupResult &R) {
1584 LookupResult::Filter F = R.makeFilter();
1586 if (isUsingDecl(F.next()))
1592 /// Check for this common pattern:
1595 /// S(const S&); // DO NOT IMPLEMENT
1596 /// void operator=(const S&); // DO NOT IMPLEMENT
1599 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1600 // FIXME: Should check for private access too but access is set after we get
1602 if (D->doesThisDeclarationHaveABody())
1605 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1606 return CD->isCopyConstructor();
1607 return D->isCopyAssignmentOperator();
1610 // We need this to handle
1613 // void *foo() { return 0; }
1616 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1617 // for example. If 'A', foo will have external linkage. If we have '*A',
1618 // foo will have no linkage. Since we can't know until we get to the end
1619 // of the typedef, this function finds out if D might have non-external linkage.
1620 // Callers should verify at the end of the TU if it D has external linkage or
1622 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1623 const DeclContext *DC = D->getDeclContext();
1624 while (!DC->isTranslationUnit()) {
1625 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1626 if (!RD->hasNameForLinkage())
1629 DC = DC->getParent();
1632 return !D->isExternallyVisible();
1635 // FIXME: This needs to be refactored; some other isInMainFile users want
1637 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1638 if (S.TUKind != TU_Complete)
1640 return S.SourceMgr.isInMainFile(Loc);
1643 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1646 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1649 // Ignore all entities declared within templates, and out-of-line definitions
1650 // of members of class templates.
1651 if (D->getDeclContext()->isDependentContext() ||
1652 D->getLexicalDeclContext()->isDependentContext())
1655 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1656 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1658 // A non-out-of-line declaration of a member specialization was implicitly
1659 // instantiated; it's the out-of-line declaration that we're interested in.
1660 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1661 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1664 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1665 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1668 // 'static inline' functions are defined in headers; don't warn.
1669 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1673 if (FD->doesThisDeclarationHaveABody() &&
1674 Context.DeclMustBeEmitted(FD))
1676 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1677 // Constants and utility variables are defined in headers with internal
1678 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1680 if (!isMainFileLoc(*this, VD->getLocation()))
1683 if (Context.DeclMustBeEmitted(VD))
1686 if (VD->isStaticDataMember() &&
1687 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1689 if (VD->isStaticDataMember() &&
1690 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1691 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1694 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1700 // Only warn for unused decls internal to the translation unit.
1701 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1702 // for inline functions defined in the main source file, for instance.
1703 return mightHaveNonExternalLinkage(D);
1706 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1710 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1711 const FunctionDecl *First = FD->getFirstDecl();
1712 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1713 return; // First should already be in the vector.
1716 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1717 const VarDecl *First = VD->getFirstDecl();
1718 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1719 return; // First should already be in the vector.
1722 if (ShouldWarnIfUnusedFileScopedDecl(D))
1723 UnusedFileScopedDecls.push_back(D);
1726 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1727 if (D->isInvalidDecl())
1730 bool Referenced = false;
1731 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1732 // For a decomposition declaration, warn if none of the bindings are
1733 // referenced, instead of if the variable itself is referenced (which
1734 // it is, by the bindings' expressions).
1735 for (auto *BD : DD->bindings()) {
1736 if (BD->isReferenced()) {
1741 } else if (!D->getDeclName()) {
1743 } else if (D->isReferenced() || D->isUsed()) {
1747 if (Referenced || D->hasAttr<UnusedAttr>() ||
1748 D->hasAttr<ObjCPreciseLifetimeAttr>())
1751 if (isa<LabelDecl>(D))
1754 // Except for labels, we only care about unused decls that are local to
1756 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1757 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1758 // For dependent types, the diagnostic is deferred.
1760 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1761 if (!WithinFunction)
1764 if (isa<TypedefNameDecl>(D))
1767 // White-list anything that isn't a local variable.
1768 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1771 // Types of valid local variables should be complete, so this should succeed.
1772 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1774 // White-list anything with an __attribute__((unused)) type.
1775 const auto *Ty = VD->getType().getTypePtr();
1777 // Only look at the outermost level of typedef.
1778 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1779 if (TT->getDecl()->hasAttr<UnusedAttr>())
1783 // If we failed to complete the type for some reason, or if the type is
1784 // dependent, don't diagnose the variable.
1785 if (Ty->isIncompleteType() || Ty->isDependentType())
1788 // Look at the element type to ensure that the warning behaviour is
1789 // consistent for both scalars and arrays.
1790 Ty = Ty->getBaseElementTypeUnsafe();
1792 if (const TagType *TT = Ty->getAs<TagType>()) {
1793 const TagDecl *Tag = TT->getDecl();
1794 if (Tag->hasAttr<UnusedAttr>())
1797 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1798 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1801 if (const Expr *Init = VD->getInit()) {
1802 if (const ExprWithCleanups *Cleanups =
1803 dyn_cast<ExprWithCleanups>(Init))
1804 Init = Cleanups->getSubExpr();
1805 const CXXConstructExpr *Construct =
1806 dyn_cast<CXXConstructExpr>(Init);
1807 if (Construct && !Construct->isElidable()) {
1808 CXXConstructorDecl *CD = Construct->getConstructor();
1809 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1810 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1814 // Suppress the warning if we don't know how this is constructed, and
1815 // it could possibly be non-trivial constructor.
1816 if (Init->isTypeDependent())
1817 for (const CXXConstructorDecl *Ctor : RD->ctors())
1818 if (!Ctor->isTrivial())
1824 // TODO: __attribute__((unused)) templates?
1830 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1832 if (isa<LabelDecl>(D)) {
1833 SourceLocation AfterColon = Lexer::findLocationAfterToken(
1834 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1836 if (AfterColon.isInvalid())
1838 Hint = FixItHint::CreateRemoval(
1839 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1843 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1844 if (D->getTypeForDecl()->isDependentType())
1847 for (auto *TmpD : D->decls()) {
1848 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1849 DiagnoseUnusedDecl(T);
1850 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1851 DiagnoseUnusedNestedTypedefs(R);
1855 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1856 /// unless they are marked attr(unused).
1857 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1858 if (!ShouldDiagnoseUnusedDecl(D))
1861 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1862 // typedefs can be referenced later on, so the diagnostics are emitted
1863 // at end-of-translation-unit.
1864 UnusedLocalTypedefNameCandidates.insert(TD);
1869 GenerateFixForUnusedDecl(D, Context, Hint);
1872 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1873 DiagID = diag::warn_unused_exception_param;
1874 else if (isa<LabelDecl>(D))
1875 DiagID = diag::warn_unused_label;
1877 DiagID = diag::warn_unused_variable;
1879 Diag(D->getLocation(), DiagID) << D << Hint;
1882 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1883 // Verify that we have no forward references left. If so, there was a goto
1884 // or address of a label taken, but no definition of it. Label fwd
1885 // definitions are indicated with a null substmt which is also not a resolved
1886 // MS inline assembly label name.
1887 bool Diagnose = false;
1888 if (L->isMSAsmLabel())
1889 Diagnose = !L->isResolvedMSAsmLabel();
1891 Diagnose = L->getStmt() == nullptr;
1893 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1896 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1897 S->mergeNRVOIntoParent();
1899 if (S->decl_empty()) return;
1900 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1901 "Scope shouldn't contain decls!");
1903 for (auto *TmpD : S->decls()) {
1904 assert(TmpD && "This decl didn't get pushed??");
1906 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1907 NamedDecl *D = cast<NamedDecl>(TmpD);
1909 // Diagnose unused variables in this scope.
1910 if (!S->hasUnrecoverableErrorOccurred()) {
1911 DiagnoseUnusedDecl(D);
1912 if (const auto *RD = dyn_cast<RecordDecl>(D))
1913 DiagnoseUnusedNestedTypedefs(RD);
1916 if (!D->getDeclName()) continue;
1918 // If this was a forward reference to a label, verify it was defined.
1919 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1920 CheckPoppedLabel(LD, *this);
1922 // Remove this name from our lexical scope, and warn on it if we haven't
1924 IdResolver.RemoveDecl(D);
1925 auto ShadowI = ShadowingDecls.find(D);
1926 if (ShadowI != ShadowingDecls.end()) {
1927 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1928 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1929 << D << FD << FD->getParent();
1930 Diag(FD->getLocation(), diag::note_previous_declaration);
1932 ShadowingDecls.erase(ShadowI);
1937 /// Look for an Objective-C class in the translation unit.
1939 /// \param Id The name of the Objective-C class we're looking for. If
1940 /// typo-correction fixes this name, the Id will be updated
1941 /// to the fixed name.
1943 /// \param IdLoc The location of the name in the translation unit.
1945 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1946 /// if there is no class with the given name.
1948 /// \returns The declaration of the named Objective-C class, or NULL if the
1949 /// class could not be found.
1950 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1951 SourceLocation IdLoc,
1952 bool DoTypoCorrection) {
1953 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1954 // creation from this context.
1955 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1957 if (!IDecl && DoTypoCorrection) {
1958 // Perform typo correction at the given location, but only if we
1959 // find an Objective-C class name.
1960 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1961 if (TypoCorrection C =
1962 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1963 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1964 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1965 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1966 Id = IDecl->getIdentifier();
1969 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1970 // This routine must always return a class definition, if any.
1971 if (Def && Def->getDefinition())
1972 Def = Def->getDefinition();
1976 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1977 /// from S, where a non-field would be declared. This routine copes
1978 /// with the difference between C and C++ scoping rules in structs and
1979 /// unions. For example, the following code is well-formed in C but
1980 /// ill-formed in C++:
1986 /// void test_S6() {
1991 /// For the declaration of BAR, this routine will return a different
1992 /// scope. The scope S will be the scope of the unnamed enumeration
1993 /// within S6. In C++, this routine will return the scope associated
1994 /// with S6, because the enumeration's scope is a transparent
1995 /// context but structures can contain non-field names. In C, this
1996 /// routine will return the translation unit scope, since the
1997 /// enumeration's scope is a transparent context and structures cannot
1998 /// contain non-field names.
1999 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2000 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2001 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2002 (S->isClassScope() && !getLangOpts().CPlusPlus))
2007 /// Looks up the declaration of "struct objc_super" and
2008 /// saves it for later use in building builtin declaration of
2009 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
2010 /// pre-existing declaration exists no action takes place.
2011 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
2012 IdentifierInfo *II) {
2013 if (!II->isStr("objc_msgSendSuper"))
2015 ASTContext &Context = ThisSema.Context;
2017 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2018 SourceLocation(), Sema::LookupTagName);
2019 ThisSema.LookupName(Result, S);
2020 if (Result.getResultKind() == LookupResult::Found)
2021 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2022 Context.setObjCSuperType(Context.getTagDeclType(TD));
2025 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2026 ASTContext::GetBuiltinTypeError Error) {
2028 case ASTContext::GE_None:
2030 case ASTContext::GE_Missing_type:
2031 return BuiltinInfo.getHeaderName(ID);
2032 case ASTContext::GE_Missing_stdio:
2034 case ASTContext::GE_Missing_setjmp:
2036 case ASTContext::GE_Missing_ucontext:
2037 return "ucontext.h";
2039 llvm_unreachable("unhandled error kind");
2042 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2043 /// file scope. lazily create a decl for it. ForRedeclaration is true
2044 /// if we're creating this built-in in anticipation of redeclaring the
2046 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2047 Scope *S, bool ForRedeclaration,
2048 SourceLocation Loc) {
2049 LookupPredefedObjCSuperType(*this, S, II);
2051 ASTContext::GetBuiltinTypeError Error;
2052 QualType R = Context.GetBuiltinType(ID, Error);
2054 if (!ForRedeclaration)
2057 // If we have a builtin without an associated type we should not emit a
2058 // warning when we were not able to find a type for it.
2059 if (Error == ASTContext::GE_Missing_type)
2062 // If we could not find a type for setjmp it is because the jmp_buf type was
2063 // not defined prior to the setjmp declaration.
2064 if (Error == ASTContext::GE_Missing_setjmp) {
2065 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2066 << Context.BuiltinInfo.getName(ID);
2070 // Generally, we emit a warning that the declaration requires the
2071 // appropriate header.
2072 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2073 << getHeaderName(Context.BuiltinInfo, ID, Error)
2074 << Context.BuiltinInfo.getName(ID);
2078 if (!ForRedeclaration &&
2079 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2080 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2081 Diag(Loc, diag::ext_implicit_lib_function_decl)
2082 << Context.BuiltinInfo.getName(ID) << R;
2083 if (Context.BuiltinInfo.getHeaderName(ID) &&
2084 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2085 Diag(Loc, diag::note_include_header_or_declare)
2086 << Context.BuiltinInfo.getHeaderName(ID)
2087 << Context.BuiltinInfo.getName(ID);
2093 DeclContext *Parent = Context.getTranslationUnitDecl();
2094 if (getLangOpts().CPlusPlus) {
2095 LinkageSpecDecl *CLinkageDecl =
2096 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2097 LinkageSpecDecl::lang_c, false);
2098 CLinkageDecl->setImplicit();
2099 Parent->addDecl(CLinkageDecl);
2100 Parent = CLinkageDecl;
2103 FunctionDecl *New = FunctionDecl::Create(Context,
2105 Loc, Loc, II, R, /*TInfo=*/nullptr,
2108 R->isFunctionProtoType());
2111 // Create Decl objects for each parameter, adding them to the
2113 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2114 SmallVector<ParmVarDecl*, 16> Params;
2115 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2117 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2118 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2120 parm->setScopeInfo(0, i);
2121 Params.push_back(parm);
2123 New->setParams(Params);
2126 AddKnownFunctionAttributes(New);
2127 RegisterLocallyScopedExternCDecl(New, S);
2129 // TUScope is the translation-unit scope to insert this function into.
2130 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2131 // relate Scopes to DeclContexts, and probably eliminate CurContext
2132 // entirely, but we're not there yet.
2133 DeclContext *SavedContext = CurContext;
2134 CurContext = Parent;
2135 PushOnScopeChains(New, TUScope);
2136 CurContext = SavedContext;
2140 /// Typedef declarations don't have linkage, but they still denote the same
2141 /// entity if their types are the same.
2142 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2144 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2145 TypedefNameDecl *Decl,
2146 LookupResult &Previous) {
2147 // This is only interesting when modules are enabled.
2148 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2151 // Empty sets are uninteresting.
2152 if (Previous.empty())
2155 LookupResult::Filter Filter = Previous.makeFilter();
2156 while (Filter.hasNext()) {
2157 NamedDecl *Old = Filter.next();
2159 // Non-hidden declarations are never ignored.
2160 if (S.isVisible(Old))
2163 // Declarations of the same entity are not ignored, even if they have
2164 // different linkages.
2165 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2166 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2167 Decl->getUnderlyingType()))
2170 // If both declarations give a tag declaration a typedef name for linkage
2171 // purposes, then they declare the same entity.
2172 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2173 Decl->getAnonDeclWithTypedefName())
2183 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2185 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2186 OldType = OldTypedef->getUnderlyingType();
2188 OldType = Context.getTypeDeclType(Old);
2189 QualType NewType = New->getUnderlyingType();
2191 if (NewType->isVariablyModifiedType()) {
2192 // Must not redefine a typedef with a variably-modified type.
2193 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2194 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2196 if (Old->getLocation().isValid())
2197 notePreviousDefinition(Old, New->getLocation());
2198 New->setInvalidDecl();
2202 if (OldType != NewType &&
2203 !OldType->isDependentType() &&
2204 !NewType->isDependentType() &&
2205 !Context.hasSameType(OldType, NewType)) {
2206 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2207 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2208 << Kind << NewType << OldType;
2209 if (Old->getLocation().isValid())
2210 notePreviousDefinition(Old, New->getLocation());
2211 New->setInvalidDecl();
2217 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2218 /// same name and scope as a previous declaration 'Old'. Figure out
2219 /// how to resolve this situation, merging decls or emitting
2220 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2222 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2223 LookupResult &OldDecls) {
2224 // If the new decl is known invalid already, don't bother doing any
2226 if (New->isInvalidDecl()) return;
2228 // Allow multiple definitions for ObjC built-in typedefs.
2229 // FIXME: Verify the underlying types are equivalent!
2230 if (getLangOpts().ObjC) {
2231 const IdentifierInfo *TypeID = New->getIdentifier();
2232 switch (TypeID->getLength()) {
2236 if (!TypeID->isStr("id"))
2238 QualType T = New->getUnderlyingType();
2239 if (!T->isPointerType())
2241 if (!T->isVoidPointerType()) {
2242 QualType PT = T->castAs<PointerType>()->getPointeeType();
2243 if (!PT->isStructureType())
2246 Context.setObjCIdRedefinitionType(T);
2247 // Install the built-in type for 'id', ignoring the current definition.
2248 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2252 if (!TypeID->isStr("Class"))
2254 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2255 // Install the built-in type for 'Class', ignoring the current definition.
2256 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2259 if (!TypeID->isStr("SEL"))
2261 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2262 // Install the built-in type for 'SEL', ignoring the current definition.
2263 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2266 // Fall through - the typedef name was not a builtin type.
2269 // Verify the old decl was also a type.
2270 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2272 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2273 << New->getDeclName();
2275 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2276 if (OldD->getLocation().isValid())
2277 notePreviousDefinition(OldD, New->getLocation());
2279 return New->setInvalidDecl();
2282 // If the old declaration is invalid, just give up here.
2283 if (Old->isInvalidDecl())
2284 return New->setInvalidDecl();
2286 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2287 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2288 auto *NewTag = New->getAnonDeclWithTypedefName();
2289 NamedDecl *Hidden = nullptr;
2290 if (OldTag && NewTag &&
2291 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2292 !hasVisibleDefinition(OldTag, &Hidden)) {
2293 // There is a definition of this tag, but it is not visible. Use it
2294 // instead of our tag.
2295 New->setTypeForDecl(OldTD->getTypeForDecl());
2296 if (OldTD->isModed())
2297 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2298 OldTD->getUnderlyingType());
2300 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2302 // Make the old tag definition visible.
2303 makeMergedDefinitionVisible(Hidden);
2305 // If this was an unscoped enumeration, yank all of its enumerators
2306 // out of the scope.
2307 if (isa<EnumDecl>(NewTag)) {
2308 Scope *EnumScope = getNonFieldDeclScope(S);
2309 for (auto *D : NewTag->decls()) {
2310 auto *ED = cast<EnumConstantDecl>(D);
2311 assert(EnumScope->isDeclScope(ED));
2312 EnumScope->RemoveDecl(ED);
2313 IdResolver.RemoveDecl(ED);
2314 ED->getLexicalDeclContext()->removeDecl(ED);
2320 // If the typedef types are not identical, reject them in all languages and
2321 // with any extensions enabled.
2322 if (isIncompatibleTypedef(Old, New))
2325 // The types match. Link up the redeclaration chain and merge attributes if
2326 // the old declaration was a typedef.
2327 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2328 New->setPreviousDecl(Typedef);
2329 mergeDeclAttributes(New, Old);
2332 if (getLangOpts().MicrosoftExt)
2335 if (getLangOpts().CPlusPlus) {
2336 // C++ [dcl.typedef]p2:
2337 // In a given non-class scope, a typedef specifier can be used to
2338 // redefine the name of any type declared in that scope to refer
2339 // to the type to which it already refers.
2340 if (!isa<CXXRecordDecl>(CurContext))
2343 // C++0x [dcl.typedef]p4:
2344 // In a given class scope, a typedef specifier can be used to redefine
2345 // any class-name declared in that scope that is not also a typedef-name
2346 // to refer to the type to which it already refers.
2348 // This wording came in via DR424, which was a correction to the
2349 // wording in DR56, which accidentally banned code like:
2352 // typedef struct A { } A;
2355 // in the C++03 standard. We implement the C++0x semantics, which
2356 // allow the above but disallow
2363 // since that was the intent of DR56.
2364 if (!isa<TypedefNameDecl>(Old))
2367 Diag(New->getLocation(), diag::err_redefinition)
2368 << New->getDeclName();
2369 notePreviousDefinition(Old, New->getLocation());
2370 return New->setInvalidDecl();
2373 // Modules always permit redefinition of typedefs, as does C11.
2374 if (getLangOpts().Modules || getLangOpts().C11)
2377 // If we have a redefinition of a typedef in C, emit a warning. This warning
2378 // is normally mapped to an error, but can be controlled with
2379 // -Wtypedef-redefinition. If either the original or the redefinition is
2380 // in a system header, don't emit this for compatibility with GCC.
2381 if (getDiagnostics().getSuppressSystemWarnings() &&
2382 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2383 (Old->isImplicit() ||
2384 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2385 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2388 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2389 << New->getDeclName();
2390 notePreviousDefinition(Old, New->getLocation());
2393 /// DeclhasAttr - returns true if decl Declaration already has the target
2395 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2396 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2397 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2398 for (const auto *i : D->attrs())
2399 if (i->getKind() == A->getKind()) {
2401 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2405 // FIXME: Don't hardcode this check
2406 if (OA && isa<OwnershipAttr>(i))
2407 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2414 static bool isAttributeTargetADefinition(Decl *D) {
2415 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2416 return VD->isThisDeclarationADefinition();
2417 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2418 return TD->isCompleteDefinition() || TD->isBeingDefined();
2422 /// Merge alignment attributes from \p Old to \p New, taking into account the
2423 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2425 /// \return \c true if any attributes were added to \p New.
2426 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2427 // Look for alignas attributes on Old, and pick out whichever attribute
2428 // specifies the strictest alignment requirement.
2429 AlignedAttr *OldAlignasAttr = nullptr;
2430 AlignedAttr *OldStrictestAlignAttr = nullptr;
2431 unsigned OldAlign = 0;
2432 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2433 // FIXME: We have no way of representing inherited dependent alignments
2435 // template<int A, int B> struct alignas(A) X;
2436 // template<int A, int B> struct alignas(B) X {};
2437 // For now, we just ignore any alignas attributes which are not on the
2438 // definition in such a case.
2439 if (I->isAlignmentDependent())
2445 unsigned Align = I->getAlignment(S.Context);
2446 if (Align > OldAlign) {
2448 OldStrictestAlignAttr = I;
2452 // Look for alignas attributes on New.
2453 AlignedAttr *NewAlignasAttr = nullptr;
2454 unsigned NewAlign = 0;
2455 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2456 if (I->isAlignmentDependent())
2462 unsigned Align = I->getAlignment(S.Context);
2463 if (Align > NewAlign)
2467 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2468 // Both declarations have 'alignas' attributes. We require them to match.
2469 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2470 // fall short. (If two declarations both have alignas, they must both match
2471 // every definition, and so must match each other if there is a definition.)
2473 // If either declaration only contains 'alignas(0)' specifiers, then it
2474 // specifies the natural alignment for the type.
2475 if (OldAlign == 0 || NewAlign == 0) {
2477 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2480 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2483 OldAlign = S.Context.getTypeAlign(Ty);
2485 NewAlign = S.Context.getTypeAlign(Ty);
2488 if (OldAlign != NewAlign) {
2489 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2490 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2491 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2492 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2496 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2497 // C++11 [dcl.align]p6:
2498 // if any declaration of an entity has an alignment-specifier,
2499 // every defining declaration of that entity shall specify an
2500 // equivalent alignment.
2502 // If the definition of an object does not have an alignment
2503 // specifier, any other declaration of that object shall also
2504 // have no alignment specifier.
2505 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2507 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2511 bool AnyAdded = false;
2513 // Ensure we have an attribute representing the strictest alignment.
2514 if (OldAlign > NewAlign) {
2515 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2516 Clone->setInherited(true);
2517 New->addAttr(Clone);
2521 // Ensure we have an alignas attribute if the old declaration had one.
2522 if (OldAlignasAttr && !NewAlignasAttr &&
2523 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2524 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2525 Clone->setInherited(true);
2526 New->addAttr(Clone);
2533 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2534 const InheritableAttr *Attr,
2535 Sema::AvailabilityMergeKind AMK) {
2536 // This function copies an attribute Attr from a previous declaration to the
2537 // new declaration D if the new declaration doesn't itself have that attribute
2538 // yet or if that attribute allows duplicates.
2539 // If you're adding a new attribute that requires logic different from
2540 // "use explicit attribute on decl if present, else use attribute from
2541 // previous decl", for example if the attribute needs to be consistent
2542 // between redeclarations, you need to call a custom merge function here.
2543 InheritableAttr *NewAttr = nullptr;
2544 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2545 NewAttr = S.mergeAvailabilityAttr(
2546 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2547 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2548 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2550 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2551 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2552 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2553 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2554 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2555 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2556 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2557 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2558 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2559 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2561 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2562 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2563 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2564 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2565 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2566 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2567 IA->getInheritanceModel());
2568 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2569 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2570 &S.Context.Idents.get(AA->getSpelling()));
2571 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2572 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2573 isa<CUDAGlobalAttr>(Attr))) {
2574 // CUDA target attributes are part of function signature for
2575 // overloading purposes and must not be merged.
2577 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2578 NewAttr = S.mergeMinSizeAttr(D, *MA);
2579 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2580 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2581 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2582 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2583 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2584 NewAttr = S.mergeCommonAttr(D, *CommonA);
2585 else if (isa<AlignedAttr>(Attr))
2586 // AlignedAttrs are handled separately, because we need to handle all
2587 // such attributes on a declaration at the same time.
2589 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2590 (AMK == Sema::AMK_Override ||
2591 AMK == Sema::AMK_ProtocolImplementation))
2593 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2594 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid());
2595 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2596 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2597 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2598 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2599 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2600 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2603 NewAttr->setInherited(true);
2604 D->addAttr(NewAttr);
2605 if (isa<MSInheritanceAttr>(NewAttr))
2606 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2613 static const NamedDecl *getDefinition(const Decl *D) {
2614 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2615 return TD->getDefinition();
2616 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2617 const VarDecl *Def = VD->getDefinition();
2620 return VD->getActingDefinition();
2622 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2623 return FD->getDefinition();
2627 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2628 for (const auto *Attribute : D->attrs())
2629 if (Attribute->getKind() == Kind)
2634 /// checkNewAttributesAfterDef - If we already have a definition, check that
2635 /// there are no new attributes in this declaration.
2636 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2637 if (!New->hasAttrs())
2640 const NamedDecl *Def = getDefinition(Old);
2641 if (!Def || Def == New)
2644 AttrVec &NewAttributes = New->getAttrs();
2645 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2646 const Attr *NewAttribute = NewAttributes[I];
2648 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2649 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2650 Sema::SkipBodyInfo SkipBody;
2651 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2653 // If we're skipping this definition, drop the "alias" attribute.
2654 if (SkipBody.ShouldSkip) {
2655 NewAttributes.erase(NewAttributes.begin() + I);
2660 VarDecl *VD = cast<VarDecl>(New);
2661 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2662 VarDecl::TentativeDefinition
2663 ? diag::err_alias_after_tentative
2664 : diag::err_redefinition;
2665 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2666 if (Diag == diag::err_redefinition)
2667 S.notePreviousDefinition(Def, VD->getLocation());
2669 S.Diag(Def->getLocation(), diag::note_previous_definition);
2670 VD->setInvalidDecl();
2676 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2677 // Tentative definitions are only interesting for the alias check above.
2678 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2684 if (hasAttribute(Def, NewAttribute->getKind())) {
2686 continue; // regular attr merging will take care of validating this.
2689 if (isa<C11NoReturnAttr>(NewAttribute)) {
2690 // C's _Noreturn is allowed to be added to a function after it is defined.
2693 } else if (isa<UuidAttr>(NewAttribute)) {
2694 // msvc will allow a subsequent definition to add an uuid to a class
2697 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2698 if (AA->isAlignas()) {
2699 // C++11 [dcl.align]p6:
2700 // if any declaration of an entity has an alignment-specifier,
2701 // every defining declaration of that entity shall specify an
2702 // equivalent alignment.
2704 // If the definition of an object does not have an alignment
2705 // specifier, any other declaration of that object shall also
2706 // have no alignment specifier.
2707 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2709 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2711 NewAttributes.erase(NewAttributes.begin() + I);
2715 } else if (isa<SelectAnyAttr>(NewAttribute) &&
2716 cast<VarDecl>(New)->isInline() &&
2717 !cast<VarDecl>(New)->isInlineSpecified()) {
2718 // Don't warn about applying selectany to implicitly inline variables.
2719 // Older compilers and language modes would require the use of selectany
2720 // to make such variables inline, and it would have no effect if we
2726 S.Diag(NewAttribute->getLocation(),
2727 diag::warn_attribute_precede_definition);
2728 S.Diag(Def->getLocation(), diag::note_previous_definition);
2729 NewAttributes.erase(NewAttributes.begin() + I);
2734 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2735 const ConstInitAttr *CIAttr,
2736 bool AttrBeforeInit) {
2737 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2739 // Figure out a good way to write this specifier on the old declaration.
2740 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2741 // enough of the attribute list spelling information to extract that without
2743 std::string SuitableSpelling;
2744 if (S.getLangOpts().CPlusPlus2a)
2746 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit});
2747 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2748 SuitableSpelling = S.PP.getLastMacroWithSpelling(
2750 {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"),
2752 S.PP.getIdentifierInfo("require_constant_initialization"),
2753 tok::r_square, tok::r_square});
2754 if (SuitableSpelling.empty())
2755 SuitableSpelling = S.PP.getLastMacroWithSpelling(
2757 {tok::kw___attribute, tok::l_paren, tok::r_paren,
2758 S.PP.getIdentifierInfo("require_constant_initialization"),
2759 tok::r_paren, tok::r_paren});
2760 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a)
2761 SuitableSpelling = "constinit";
2762 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2763 SuitableSpelling = "[[clang::require_constant_initialization]]";
2764 if (SuitableSpelling.empty())
2765 SuitableSpelling = "__attribute__((require_constant_initialization))";
2766 SuitableSpelling += " ";
2768 if (AttrBeforeInit) {
2769 // extern constinit int a;
2770 // int a = 0; // error (missing 'constinit'), accepted as extension
2771 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2772 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2773 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2774 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2777 // constinit extern int a; // error (missing 'constinit')
2778 S.Diag(CIAttr->getLocation(),
2779 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2780 : diag::warn_require_const_init_added_too_late)
2781 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2782 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2783 << CIAttr->isConstinit()
2784 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2788 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2789 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2790 AvailabilityMergeKind AMK) {
2791 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2792 UsedAttr *NewAttr = OldAttr->clone(Context);
2793 NewAttr->setInherited(true);
2794 New->addAttr(NewAttr);
2797 if (!Old->hasAttrs() && !New->hasAttrs())
2800 // [dcl.constinit]p1:
2801 // If the [constinit] specifier is applied to any declaration of a
2802 // variable, it shall be applied to the initializing declaration.
2803 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2804 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2805 if (bool(OldConstInit) != bool(NewConstInit)) {
2806 const auto *OldVD = cast<VarDecl>(Old);
2807 auto *NewVD = cast<VarDecl>(New);
2809 // Find the initializing declaration. Note that we might not have linked
2810 // the new declaration into the redeclaration chain yet.
2811 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2813 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2816 if (InitDecl == NewVD) {
2817 // This is the initializing declaration. If it would inherit 'constinit',
2818 // that's ill-formed. (Note that we do not apply this to the attribute
2820 if (OldConstInit && OldConstInit->isConstinit())
2821 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2822 /*AttrBeforeInit=*/true);
2823 } else if (NewConstInit) {
2824 // This is the first time we've been told that this declaration should
2825 // have a constant initializer. If we already saw the initializing
2826 // declaration, this is too late.
2827 if (InitDecl && InitDecl != NewVD) {
2828 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2829 /*AttrBeforeInit=*/false);
2830 NewVD->dropAttr<ConstInitAttr>();
2835 // Attributes declared post-definition are currently ignored.
2836 checkNewAttributesAfterDef(*this, New, Old);
2838 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2839 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2840 if (!OldA->isEquivalent(NewA)) {
2841 // This redeclaration changes __asm__ label.
2842 Diag(New->getLocation(), diag::err_different_asm_label);
2843 Diag(OldA->getLocation(), diag::note_previous_declaration);
2845 } else if (Old->isUsed()) {
2846 // This redeclaration adds an __asm__ label to a declaration that has
2847 // already been ODR-used.
2848 Diag(New->getLocation(), diag::err_late_asm_label_name)
2849 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2853 // Re-declaration cannot add abi_tag's.
2854 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2855 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2856 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2857 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2858 NewTag) == OldAbiTagAttr->tags_end()) {
2859 Diag(NewAbiTagAttr->getLocation(),
2860 diag::err_new_abi_tag_on_redeclaration)
2862 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2866 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2867 Diag(Old->getLocation(), diag::note_previous_declaration);
2871 // This redeclaration adds a section attribute.
2872 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2873 if (auto *VD = dyn_cast<VarDecl>(New)) {
2874 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2875 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2876 Diag(Old->getLocation(), diag::note_previous_declaration);
2881 // Redeclaration adds code-seg attribute.
2882 const auto *NewCSA = New->getAttr<CodeSegAttr>();
2883 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2884 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2885 Diag(New->getLocation(), diag::warn_mismatched_section)
2887 Diag(Old->getLocation(), diag::note_previous_declaration);
2890 if (!Old->hasAttrs())
2893 bool foundAny = New->hasAttrs();
2895 // Ensure that any moving of objects within the allocated map is done before
2897 if (!foundAny) New->setAttrs(AttrVec());
2899 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2900 // Ignore deprecated/unavailable/availability attributes if requested.
2901 AvailabilityMergeKind LocalAMK = AMK_None;
2902 if (isa<DeprecatedAttr>(I) ||
2903 isa<UnavailableAttr>(I) ||
2904 isa<AvailabilityAttr>(I)) {
2909 case AMK_Redeclaration:
2911 case AMK_ProtocolImplementation:
2918 if (isa<UsedAttr>(I))
2921 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2925 if (mergeAlignedAttrs(*this, New, Old))
2928 if (!foundAny) New->dropAttrs();
2931 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2933 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2934 const ParmVarDecl *oldDecl,
2936 // C++11 [dcl.attr.depend]p2:
2937 // The first declaration of a function shall specify the
2938 // carries_dependency attribute for its declarator-id if any declaration
2939 // of the function specifies the carries_dependency attribute.
2940 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2941 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2942 S.Diag(CDA->getLocation(),
2943 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2944 // Find the first declaration of the parameter.
2945 // FIXME: Should we build redeclaration chains for function parameters?
2946 const FunctionDecl *FirstFD =
2947 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2948 const ParmVarDecl *FirstVD =
2949 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2950 S.Diag(FirstVD->getLocation(),
2951 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2954 if (!oldDecl->hasAttrs())
2957 bool foundAny = newDecl->hasAttrs();
2959 // Ensure that any moving of objects within the allocated map is
2960 // done before we process them.
2961 if (!foundAny) newDecl->setAttrs(AttrVec());
2963 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2964 if (!DeclHasAttr(newDecl, I)) {
2965 InheritableAttr *newAttr =
2966 cast<InheritableParamAttr>(I->clone(S.Context));
2967 newAttr->setInherited(true);
2968 newDecl->addAttr(newAttr);
2973 if (!foundAny) newDecl->dropAttrs();
2976 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2977 const ParmVarDecl *OldParam,
2979 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2980 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2981 if (*Oldnullability != *Newnullability) {
2982 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2983 << DiagNullabilityKind(
2985 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2987 << DiagNullabilityKind(
2989 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2991 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2994 QualType NewT = NewParam->getType();
2995 NewT = S.Context.getAttributedType(
2996 AttributedType::getNullabilityAttrKind(*Oldnullability),
2998 NewParam->setType(NewT);
3005 /// Used in MergeFunctionDecl to keep track of function parameters in
3007 struct GNUCompatibleParamWarning {
3008 ParmVarDecl *OldParm;
3009 ParmVarDecl *NewParm;
3010 QualType PromotedType;
3013 } // end anonymous namespace
3015 // Determine whether the previous declaration was a definition, implicit
3016 // declaration, or a declaration.
3017 template <typename T>
3018 static std::pair<diag::kind, SourceLocation>
3019 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3020 diag::kind PrevDiag;
3021 SourceLocation OldLocation = Old->getLocation();
3022 if (Old->isThisDeclarationADefinition())
3023 PrevDiag = diag::note_previous_definition;
3024 else if (Old->isImplicit()) {
3025 PrevDiag = diag::note_previous_implicit_declaration;
3026 if (OldLocation.isInvalid())
3027 OldLocation = New->getLocation();
3029 PrevDiag = diag::note_previous_declaration;
3030 return std::make_pair(PrevDiag, OldLocation);
3033 /// canRedefineFunction - checks if a function can be redefined. Currently,
3034 /// only extern inline functions can be redefined, and even then only in
3036 static bool canRedefineFunction(const FunctionDecl *FD,
3037 const LangOptions& LangOpts) {
3038 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3039 !LangOpts.CPlusPlus &&
3040 FD->isInlineSpecified() &&
3041 FD->getStorageClass() == SC_Extern);
3044 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3045 const AttributedType *AT = T->getAs<AttributedType>();
3046 while (AT && !AT->isCallingConv())
3047 AT = AT->getModifiedType()->getAs<AttributedType>();
3051 template <typename T>
3052 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3053 const DeclContext *DC = Old->getDeclContext();
3057 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3058 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3060 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3065 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3066 static bool isExternC(VarTemplateDecl *) { return false; }
3068 /// Check whether a redeclaration of an entity introduced by a
3069 /// using-declaration is valid, given that we know it's not an overload
3070 /// (nor a hidden tag declaration).
3071 template<typename ExpectedDecl>
3072 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3073 ExpectedDecl *New) {
3074 // C++11 [basic.scope.declarative]p4:
3075 // Given a set of declarations in a single declarative region, each of
3076 // which specifies the same unqualified name,
3077 // -- they shall all refer to the same entity, or all refer to functions
3078 // and function templates; or
3079 // -- exactly one declaration shall declare a class name or enumeration
3080 // name that is not a typedef name and the other declarations shall all
3081 // refer to the same variable or enumerator, or all refer to functions
3082 // and function templates; in this case the class name or enumeration
3083 // name is hidden (3.3.10).
3085 // C++11 [namespace.udecl]p14:
3086 // If a function declaration in namespace scope or block scope has the
3087 // same name and the same parameter-type-list as a function introduced
3088 // by a using-declaration, and the declarations do not declare the same
3089 // function, the program is ill-formed.
3091 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3093 !Old->getDeclContext()->getRedeclContext()->Equals(
3094 New->getDeclContext()->getRedeclContext()) &&
3095 !(isExternC(Old) && isExternC(New)))
3099 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3100 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3101 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3107 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3108 const FunctionDecl *B) {
3109 assert(A->getNumParams() == B->getNumParams());
3111 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3112 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3113 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3116 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3117 AttrA->isDynamic() == AttrB->isDynamic();
3120 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3123 /// If necessary, adjust the semantic declaration context for a qualified
3124 /// declaration to name the correct inline namespace within the qualifier.
3125 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3126 DeclaratorDecl *OldD) {
3127 // The only case where we need to update the DeclContext is when
3128 // redeclaration lookup for a qualified name finds a declaration
3129 // in an inline namespace within the context named by the qualifier:
3131 // inline namespace N { int f(); }
3132 // int ::f(); // Sema DC needs adjusting from :: to N::.
3134 // For unqualified declarations, the semantic context *can* change
3135 // along the redeclaration chain (for local extern declarations,
3136 // extern "C" declarations, and friend declarations in particular).
3137 if (!NewD->getQualifier())
3140 // NewD is probably already in the right context.
3141 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3142 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3143 if (NamedDC->Equals(SemaDC))
3146 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3147 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3148 "unexpected context for redeclaration");
3150 auto *LexDC = NewD->getLexicalDeclContext();
3151 auto FixSemaDC = [=](NamedDecl *D) {
3154 D->setDeclContext(SemaDC);
3155 D->setLexicalDeclContext(LexDC);
3159 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3160 FixSemaDC(FD->getDescribedFunctionTemplate());
3161 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3162 FixSemaDC(VD->getDescribedVarTemplate());
3165 /// MergeFunctionDecl - We just parsed a function 'New' from
3166 /// declarator D which has the same name and scope as a previous
3167 /// declaration 'Old'. Figure out how to resolve this situation,
3168 /// merging decls or emitting diagnostics as appropriate.
3170 /// In C++, New and Old must be declarations that are not
3171 /// overloaded. Use IsOverload to determine whether New and Old are
3172 /// overloaded, and to select the Old declaration that New should be
3175 /// Returns true if there was an error, false otherwise.
3176 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3177 Scope *S, bool MergeTypeWithOld) {
3178 // Verify the old decl was also a function.
3179 FunctionDecl *Old = OldD->getAsFunction();
3181 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3182 if (New->getFriendObjectKind()) {
3183 Diag(New->getLocation(), diag::err_using_decl_friend);
3184 Diag(Shadow->getTargetDecl()->getLocation(),
3185 diag::note_using_decl_target);
3186 Diag(Shadow->getUsingDecl()->getLocation(),
3187 diag::note_using_decl) << 0;
3191 // Check whether the two declarations might declare the same function.
3192 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3194 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3196 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3197 << New->getDeclName();
3198 notePreviousDefinition(OldD, New->getLocation());
3203 // If the old declaration is invalid, just give up here.
3204 if (Old->isInvalidDecl())
3207 // Disallow redeclaration of some builtins.
3208 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3209 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3210 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3211 << Old << Old->getType();
3215 diag::kind PrevDiag;
3216 SourceLocation OldLocation;
3217 std::tie(PrevDiag, OldLocation) =
3218 getNoteDiagForInvalidRedeclaration(Old, New);
3220 // Don't complain about this if we're in GNU89 mode and the old function
3221 // is an extern inline function.
3222 // Don't complain about specializations. They are not supposed to have
3224 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3225 New->getStorageClass() == SC_Static &&
3226 Old->hasExternalFormalLinkage() &&
3227 !New->getTemplateSpecializationInfo() &&
3228 !canRedefineFunction(Old, getLangOpts())) {
3229 if (getLangOpts().MicrosoftExt) {
3230 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3231 Diag(OldLocation, PrevDiag);
3233 Diag(New->getLocation(), diag::err_static_non_static) << New;
3234 Diag(OldLocation, PrevDiag);
3239 if (New->hasAttr<InternalLinkageAttr>() &&
3240 !Old->hasAttr<InternalLinkageAttr>()) {
3241 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3242 << New->getDeclName();
3243 notePreviousDefinition(Old, New->getLocation());
3244 New->dropAttr<InternalLinkageAttr>();
3247 if (CheckRedeclarationModuleOwnership(New, Old))
3250 if (!getLangOpts().CPlusPlus) {
3251 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3252 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3253 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3256 // Try our best to find a decl that actually has the overloadable
3257 // attribute for the note. In most cases (e.g. programs with only one
3258 // broken declaration/definition), this won't matter.
3260 // FIXME: We could do this if we juggled some extra state in
3261 // OverloadableAttr, rather than just removing it.
3262 const Decl *DiagOld = Old;
3264 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3265 const auto *A = D->getAttr<OverloadableAttr>();
3266 return A && !A->isImplicit();
3268 // If we've implicitly added *all* of the overloadable attrs to this
3269 // chain, emitting a "previous redecl" note is pointless.
3270 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3274 Diag(DiagOld->getLocation(),
3275 diag::note_attribute_overloadable_prev_overload)
3279 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3281 New->dropAttr<OverloadableAttr>();
3285 // If a function is first declared with a calling convention, but is later
3286 // declared or defined without one, all following decls assume the calling
3287 // convention of the first.
3289 // It's OK if a function is first declared without a calling convention,
3290 // but is later declared or defined with the default calling convention.
3292 // To test if either decl has an explicit calling convention, we look for
3293 // AttributedType sugar nodes on the type as written. If they are missing or
3294 // were canonicalized away, we assume the calling convention was implicit.
3296 // Note also that we DO NOT return at this point, because we still have
3297 // other tests to run.
3298 QualType OldQType = Context.getCanonicalType(Old->getType());
3299 QualType NewQType = Context.getCanonicalType(New->getType());
3300 const FunctionType *OldType = cast<FunctionType>(OldQType);
3301 const FunctionType *NewType = cast<FunctionType>(NewQType);
3302 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3303 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3304 bool RequiresAdjustment = false;
3306 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3307 FunctionDecl *First = Old->getFirstDecl();
3308 const FunctionType *FT =
3309 First->getType().getCanonicalType()->castAs<FunctionType>();
3310 FunctionType::ExtInfo FI = FT->getExtInfo();
3311 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3312 if (!NewCCExplicit) {
3313 // Inherit the CC from the previous declaration if it was specified
3314 // there but not here.
3315 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3316 RequiresAdjustment = true;
3317 } else if (New->getBuiltinID()) {
3318 // Calling Conventions on a Builtin aren't really useful and setting a
3319 // default calling convention and cdecl'ing some builtin redeclarations is
3320 // common, so warn and ignore the calling convention on the redeclaration.
3321 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3322 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3323 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3324 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3325 RequiresAdjustment = true;
3327 // Calling conventions aren't compatible, so complain.
3328 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3329 Diag(New->getLocation(), diag::err_cconv_change)
3330 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3332 << (!FirstCCExplicit ? "" :
3333 FunctionType::getNameForCallConv(FI.getCC()));
3335 // Put the note on the first decl, since it is the one that matters.
3336 Diag(First->getLocation(), diag::note_previous_declaration);
3341 // FIXME: diagnose the other way around?
3342 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3343 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3344 RequiresAdjustment = true;
3347 // Merge regparm attribute.
3348 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3349 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3350 if (NewTypeInfo.getHasRegParm()) {
3351 Diag(New->getLocation(), diag::err_regparm_mismatch)
3352 << NewType->getRegParmType()
3353 << OldType->getRegParmType();
3354 Diag(OldLocation, diag::note_previous_declaration);
3358 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3359 RequiresAdjustment = true;
3362 // Merge ns_returns_retained attribute.
3363 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3364 if (NewTypeInfo.getProducesResult()) {
3365 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3366 << "'ns_returns_retained'";
3367 Diag(OldLocation, diag::note_previous_declaration);
3371 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3372 RequiresAdjustment = true;
3375 if (OldTypeInfo.getNoCallerSavedRegs() !=
3376 NewTypeInfo.getNoCallerSavedRegs()) {
3377 if (NewTypeInfo.getNoCallerSavedRegs()) {
3378 AnyX86NoCallerSavedRegistersAttr *Attr =
3379 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3380 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3381 Diag(OldLocation, diag::note_previous_declaration);
3385 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3386 RequiresAdjustment = true;
3389 if (RequiresAdjustment) {
3390 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3391 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3392 New->setType(QualType(AdjustedType, 0));
3393 NewQType = Context.getCanonicalType(New->getType());
3396 // If this redeclaration makes the function inline, we may need to add it to
3397 // UndefinedButUsed.
3398 if (!Old->isInlined() && New->isInlined() &&
3399 !New->hasAttr<GNUInlineAttr>() &&
3400 !getLangOpts().GNUInline &&
3401 Old->isUsed(false) &&
3402 !Old->isDefined() && !New->isThisDeclarationADefinition())
3403 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3406 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3408 if (New->hasAttr<GNUInlineAttr>() &&
3409 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3410 UndefinedButUsed.erase(Old->getCanonicalDecl());
3413 // If pass_object_size params don't match up perfectly, this isn't a valid
3415 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3416 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3417 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3418 << New->getDeclName();
3419 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3423 if (getLangOpts().CPlusPlus) {
3424 // C++1z [over.load]p2
3425 // Certain function declarations cannot be overloaded:
3426 // -- Function declarations that differ only in the return type,
3427 // the exception specification, or both cannot be overloaded.
3429 // Check the exception specifications match. This may recompute the type of
3430 // both Old and New if it resolved exception specifications, so grab the
3431 // types again after this. Because this updates the type, we do this before
3432 // any of the other checks below, which may update the "de facto" NewQType
3433 // but do not necessarily update the type of New.
3434 if (CheckEquivalentExceptionSpec(Old, New))
3436 OldQType = Context.getCanonicalType(Old->getType());
3437 NewQType = Context.getCanonicalType(New->getType());
3439 // Go back to the type source info to compare the declared return types,
3440 // per C++1y [dcl.type.auto]p13:
3441 // Redeclarations or specializations of a function or function template
3442 // with a declared return type that uses a placeholder type shall also
3443 // use that placeholder, not a deduced type.
3444 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3445 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3446 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3447 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3448 OldDeclaredReturnType)) {
3450 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3451 OldDeclaredReturnType->isObjCObjectPointerType())
3452 // FIXME: This does the wrong thing for a deduced return type.
3453 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3454 if (ResQT.isNull()) {
3455 if (New->isCXXClassMember() && New->isOutOfLine())
3456 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3457 << New << New->getReturnTypeSourceRange();
3459 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3460 << New->getReturnTypeSourceRange();
3461 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3462 << Old->getReturnTypeSourceRange();
3469 QualType OldReturnType = OldType->getReturnType();
3470 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3471 if (OldReturnType != NewReturnType) {
3472 // If this function has a deduced return type and has already been
3473 // defined, copy the deduced value from the old declaration.
3474 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3475 if (OldAT && OldAT->isDeduced()) {
3477 SubstAutoType(New->getType(),
3478 OldAT->isDependentType() ? Context.DependentTy
3479 : OldAT->getDeducedType()));
3480 NewQType = Context.getCanonicalType(
3481 SubstAutoType(NewQType,
3482 OldAT->isDependentType() ? Context.DependentTy
3483 : OldAT->getDeducedType()));
3487 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3488 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3489 if (OldMethod && NewMethod) {
3490 // Preserve triviality.
3491 NewMethod->setTrivial(OldMethod->isTrivial());
3493 // MSVC allows explicit template specialization at class scope:
3494 // 2 CXXMethodDecls referring to the same function will be injected.
3495 // We don't want a redeclaration error.
3496 bool IsClassScopeExplicitSpecialization =
3497 OldMethod->isFunctionTemplateSpecialization() &&
3498 NewMethod->isFunctionTemplateSpecialization();
3499 bool isFriend = NewMethod->getFriendObjectKind();
3501 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3502 !IsClassScopeExplicitSpecialization) {
3503 // -- Member function declarations with the same name and the
3504 // same parameter types cannot be overloaded if any of them
3505 // is a static member function declaration.
3506 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3507 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3508 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3512 // C++ [class.mem]p1:
3513 // [...] A member shall not be declared twice in the
3514 // member-specification, except that a nested class or member
3515 // class template can be declared and then later defined.
3516 if (!inTemplateInstantiation()) {
3518 if (isa<CXXConstructorDecl>(OldMethod))
3519 NewDiag = diag::err_constructor_redeclared;
3520 else if (isa<CXXDestructorDecl>(NewMethod))
3521 NewDiag = diag::err_destructor_redeclared;
3522 else if (isa<CXXConversionDecl>(NewMethod))
3523 NewDiag = diag::err_conv_function_redeclared;
3525 NewDiag = diag::err_member_redeclared;
3527 Diag(New->getLocation(), NewDiag);
3529 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3530 << New << New->getType();
3532 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3535 // Complain if this is an explicit declaration of a special
3536 // member that was initially declared implicitly.
3538 // As an exception, it's okay to befriend such methods in order
3539 // to permit the implicit constructor/destructor/operator calls.
3540 } else if (OldMethod->isImplicit()) {
3542 NewMethod->setImplicit();
3544 Diag(NewMethod->getLocation(),
3545 diag::err_definition_of_implicitly_declared_member)
3546 << New << getSpecialMember(OldMethod);
3549 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3550 Diag(NewMethod->getLocation(),
3551 diag::err_definition_of_explicitly_defaulted_member)
3552 << getSpecialMember(OldMethod);
3557 // C++11 [dcl.attr.noreturn]p1:
3558 // The first declaration of a function shall specify the noreturn
3559 // attribute if any declaration of that function specifies the noreturn
3561 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3562 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3563 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3564 Diag(Old->getFirstDecl()->getLocation(),
3565 diag::note_noreturn_missing_first_decl);
3568 // C++11 [dcl.attr.depend]p2:
3569 // The first declaration of a function shall specify the
3570 // carries_dependency attribute for its declarator-id if any declaration
3571 // of the function specifies the carries_dependency attribute.
3572 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3573 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3574 Diag(CDA->getLocation(),
3575 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3576 Diag(Old->getFirstDecl()->getLocation(),
3577 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3581 // All declarations for a function shall agree exactly in both the
3582 // return type and the parameter-type-list.
3583 // We also want to respect all the extended bits except noreturn.
3585 // noreturn should now match unless the old type info didn't have it.
3586 QualType OldQTypeForComparison = OldQType;
3587 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3588 auto *OldType = OldQType->castAs<FunctionProtoType>();
3589 const FunctionType *OldTypeForComparison
3590 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3591 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3592 assert(OldQTypeForComparison.isCanonical());
3595 if (haveIncompatibleLanguageLinkages(Old, New)) {
3596 // As a special case, retain the language linkage from previous
3597 // declarations of a friend function as an extension.
3599 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3600 // and is useful because there's otherwise no way to specify language
3601 // linkage within class scope.
3603 // Check cautiously as the friend object kind isn't yet complete.
3604 if (New->getFriendObjectKind() != Decl::FOK_None) {
3605 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3606 Diag(OldLocation, PrevDiag);
3608 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3609 Diag(OldLocation, PrevDiag);
3614 // If the function types are compatible, merge the declarations. Ignore the
3615 // exception specifier because it was already checked above in
3616 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3617 // about incompatible types under -fms-compatibility.
3618 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3620 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3622 // If the types are imprecise (due to dependent constructs in friends or
3623 // local extern declarations), it's OK if they differ. We'll check again
3624 // during instantiation.
3625 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3628 // Fall through for conflicting redeclarations and redefinitions.
3631 // C: Function types need to be compatible, not identical. This handles
3632 // duplicate function decls like "void f(int); void f(enum X);" properly.
3633 if (!getLangOpts().CPlusPlus &&
3634 Context.typesAreCompatible(OldQType, NewQType)) {
3635 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3636 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3637 const FunctionProtoType *OldProto = nullptr;
3638 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3639 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3640 // The old declaration provided a function prototype, but the
3641 // new declaration does not. Merge in the prototype.
3642 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3643 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3645 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3646 OldProto->getExtProtoInfo());
3647 New->setType(NewQType);
3648 New->setHasInheritedPrototype();
3650 // Synthesize parameters with the same types.
3651 SmallVector<ParmVarDecl*, 16> Params;
3652 for (const auto &ParamType : OldProto->param_types()) {
3653 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3654 SourceLocation(), nullptr,
3655 ParamType, /*TInfo=*/nullptr,
3657 Param->setScopeInfo(0, Params.size());
3658 Param->setImplicit();
3659 Params.push_back(Param);
3662 New->setParams(Params);
3665 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3668 // Check if the function types are compatible when pointer size address
3669 // spaces are ignored.
3670 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3673 // GNU C permits a K&R definition to follow a prototype declaration
3674 // if the declared types of the parameters in the K&R definition
3675 // match the types in the prototype declaration, even when the
3676 // promoted types of the parameters from the K&R definition differ
3677 // from the types in the prototype. GCC then keeps the types from
3680 // If a variadic prototype is followed by a non-variadic K&R definition,
3681 // the K&R definition becomes variadic. This is sort of an edge case, but
3682 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3684 if (!getLangOpts().CPlusPlus &&
3685 Old->hasPrototype() && !New->hasPrototype() &&
3686 New->getType()->getAs<FunctionProtoType>() &&
3687 Old->getNumParams() == New->getNumParams()) {
3688 SmallVector<QualType, 16> ArgTypes;
3689 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3690 const FunctionProtoType *OldProto
3691 = Old->getType()->getAs<FunctionProtoType>();
3692 const FunctionProtoType *NewProto
3693 = New->getType()->getAs<FunctionProtoType>();
3695 // Determine whether this is the GNU C extension.
3696 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3697 NewProto->getReturnType());
3698 bool LooseCompatible = !MergedReturn.isNull();
3699 for (unsigned Idx = 0, End = Old->getNumParams();
3700 LooseCompatible && Idx != End; ++Idx) {
3701 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3702 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3703 if (Context.typesAreCompatible(OldParm->getType(),
3704 NewProto->getParamType(Idx))) {
3705 ArgTypes.push_back(NewParm->getType());
3706 } else if (Context.typesAreCompatible(OldParm->getType(),
3708 /*CompareUnqualified=*/true)) {
3709 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3710 NewProto->getParamType(Idx) };
3711 Warnings.push_back(Warn);
3712 ArgTypes.push_back(NewParm->getType());
3714 LooseCompatible = false;
3717 if (LooseCompatible) {
3718 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3719 Diag(Warnings[Warn].NewParm->getLocation(),
3720 diag::ext_param_promoted_not_compatible_with_prototype)
3721 << Warnings[Warn].PromotedType
3722 << Warnings[Warn].OldParm->getType();
3723 if (Warnings[Warn].OldParm->getLocation().isValid())
3724 Diag(Warnings[Warn].OldParm->getLocation(),
3725 diag::note_previous_declaration);
3728 if (MergeTypeWithOld)
3729 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3730 OldProto->getExtProtoInfo()));
3731 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3734 // Fall through to diagnose conflicting types.
3737 // A function that has already been declared has been redeclared or
3738 // defined with a different type; show an appropriate diagnostic.
3740 // If the previous declaration was an implicitly-generated builtin
3741 // declaration, then at the very least we should use a specialized note.
3743 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3744 // If it's actually a library-defined builtin function like 'malloc'
3745 // or 'printf', just warn about the incompatible redeclaration.
3746 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3747 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3748 Diag(OldLocation, diag::note_previous_builtin_declaration)
3749 << Old << Old->getType();
3751 // If this is a global redeclaration, just forget hereafter
3752 // about the "builtin-ness" of the function.
3754 // Doing this for local extern declarations is problematic. If
3755 // the builtin declaration remains visible, a second invalid
3756 // local declaration will produce a hard error; if it doesn't
3757 // remain visible, a single bogus local redeclaration (which is
3758 // actually only a warning) could break all the downstream code.
3759 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3760 New->getIdentifier()->revertBuiltin();
3765 PrevDiag = diag::note_previous_builtin_declaration;
3768 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3769 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3773 /// Completes the merge of two function declarations that are
3774 /// known to be compatible.
3776 /// This routine handles the merging of attributes and other
3777 /// properties of function declarations from the old declaration to
3778 /// the new declaration, once we know that New is in fact a
3779 /// redeclaration of Old.
3782 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3783 Scope *S, bool MergeTypeWithOld) {
3784 // Merge the attributes
3785 mergeDeclAttributes(New, Old);
3787 // Merge "pure" flag.
3791 // Merge "used" flag.
3792 if (Old->getMostRecentDecl()->isUsed(false))
3795 // Merge attributes from the parameters. These can mismatch with K&R
3797 if (New->getNumParams() == Old->getNumParams())
3798 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3799 ParmVarDecl *NewParam = New->getParamDecl(i);
3800 ParmVarDecl *OldParam = Old->getParamDecl(i);
3801 mergeParamDeclAttributes(NewParam, OldParam, *this);
3802 mergeParamDeclTypes(NewParam, OldParam, *this);
3805 if (getLangOpts().CPlusPlus)
3806 return MergeCXXFunctionDecl(New, Old, S);
3808 // Merge the function types so the we get the composite types for the return
3809 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3811 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3812 if (!Merged.isNull() && MergeTypeWithOld)
3813 New->setType(Merged);
3818 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3819 ObjCMethodDecl *oldMethod) {
3820 // Merge the attributes, including deprecated/unavailable
3821 AvailabilityMergeKind MergeKind =
3822 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3823 ? AMK_ProtocolImplementation
3824 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3827 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3829 // Merge attributes from the parameters.
3830 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3831 oe = oldMethod->param_end();
3832 for (ObjCMethodDecl::param_iterator
3833 ni = newMethod->param_begin(), ne = newMethod->param_end();
3834 ni != ne && oi != oe; ++ni, ++oi)
3835 mergeParamDeclAttributes(*ni, *oi, *this);
3837 CheckObjCMethodOverride(newMethod, oldMethod);
3840 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3841 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3843 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3844 ? diag::err_redefinition_different_type
3845 : diag::err_redeclaration_different_type)
3846 << New->getDeclName() << New->getType() << Old->getType();
3848 diag::kind PrevDiag;
3849 SourceLocation OldLocation;
3850 std::tie(PrevDiag, OldLocation)
3851 = getNoteDiagForInvalidRedeclaration(Old, New);
3852 S.Diag(OldLocation, PrevDiag);
3853 New->setInvalidDecl();
3856 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3857 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
3858 /// emitting diagnostics as appropriate.
3860 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3861 /// to here in AddInitializerToDecl. We can't check them before the initializer
3863 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3864 bool MergeTypeWithOld) {
3865 if (New->isInvalidDecl() || Old->isInvalidDecl())
3869 if (getLangOpts().CPlusPlus) {
3870 if (New->getType()->isUndeducedType()) {
3871 // We don't know what the new type is until the initializer is attached.
3873 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3874 // These could still be something that needs exception specs checked.
3875 return MergeVarDeclExceptionSpecs(New, Old);
3877 // C++ [basic.link]p10:
3878 // [...] the types specified by all declarations referring to a given
3879 // object or function shall be identical, except that declarations for an
3880 // array object can specify array types that differ by the presence or
3881 // absence of a major array bound (8.3.4).
3882 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3883 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3884 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3886 // We are merging a variable declaration New into Old. If it has an array
3887 // bound, and that bound differs from Old's bound, we should diagnose the
3889 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3890 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3891 PrevVD = PrevVD->getPreviousDecl()) {
3892 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3893 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3896 if (!Context.hasSameType(NewArray, PrevVDTy))
3897 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3901 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3902 if (Context.hasSameType(OldArray->getElementType(),
3903 NewArray->getElementType()))
3904 MergedT = New->getType();
3906 // FIXME: Check visibility. New is hidden but has a complete type. If New
3907 // has no array bound, it should not inherit one from Old, if Old is not
3909 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3910 if (Context.hasSameType(OldArray->getElementType(),
3911 NewArray->getElementType()))
3912 MergedT = Old->getType();
3915 else if (New->getType()->isObjCObjectPointerType() &&
3916 Old->getType()->isObjCObjectPointerType()) {
3917 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3922 // All declarations that refer to the same object or function shall have
3924 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3926 if (MergedT.isNull()) {
3927 // It's OK if we couldn't merge types if either type is dependent, for a
3928 // block-scope variable. In other cases (static data members of class
3929 // templates, variable templates, ...), we require the types to be
3931 // FIXME: The C++ standard doesn't say anything about this.
3932 if ((New->getType()->isDependentType() ||
3933 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3934 // If the old type was dependent, we can't merge with it, so the new type
3935 // becomes dependent for now. We'll reproduce the original type when we
3936 // instantiate the TypeSourceInfo for the variable.
3937 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3938 New->setType(Context.DependentTy);
3941 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3944 // Don't actually update the type on the new declaration if the old
3945 // declaration was an extern declaration in a different scope.
3946 if (MergeTypeWithOld)
3947 New->setType(MergedT);
3950 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3951 LookupResult &Previous) {
3953 // For an identifier with internal or external linkage declared
3954 // in a scope in which a prior declaration of that identifier is
3955 // visible, if the prior declaration specifies internal or
3956 // external linkage, the type of the identifier at the later
3957 // declaration becomes the composite type.
3959 // If the variable isn't visible, we do not merge with its type.
3960 if (Previous.isShadowed())
3963 if (S.getLangOpts().CPlusPlus) {
3964 // C++11 [dcl.array]p3:
3965 // If there is a preceding declaration of the entity in the same
3966 // scope in which the bound was specified, an omitted array bound
3967 // is taken to be the same as in that earlier declaration.
3968 return NewVD->isPreviousDeclInSameBlockScope() ||
3969 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3970 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3972 // If the old declaration was function-local, don't merge with its
3973 // type unless we're in the same function.
3974 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3975 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3979 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3980 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
3981 /// situation, merging decls or emitting diagnostics as appropriate.
3983 /// Tentative definition rules (C99 6.9.2p2) are checked by
3984 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3985 /// definitions here, since the initializer hasn't been attached.
3987 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3988 // If the new decl is already invalid, don't do any other checking.
3989 if (New->isInvalidDecl())
3992 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3995 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3997 // Verify the old decl was also a variable or variable template.
3998 VarDecl *Old = nullptr;
3999 VarTemplateDecl *OldTemplate = nullptr;
4000 if (Previous.isSingleResult()) {
4002 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4003 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4006 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4007 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4008 return New->setInvalidDecl();
4010 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4013 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4014 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4015 return New->setInvalidDecl();
4019 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4020 << New->getDeclName();
4021 notePreviousDefinition(Previous.getRepresentativeDecl(),
4022 New->getLocation());
4023 return New->setInvalidDecl();
4026 // Ensure the template parameters are compatible.
4028 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4029 OldTemplate->getTemplateParameters(),
4030 /*Complain=*/true, TPL_TemplateMatch))
4031 return New->setInvalidDecl();
4033 // C++ [class.mem]p1:
4034 // A member shall not be declared twice in the member-specification [...]
4036 // Here, we need only consider static data members.
4037 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4038 Diag(New->getLocation(), diag::err_duplicate_member)
4039 << New->getIdentifier();
4040 Diag(Old->getLocation(), diag::note_previous_declaration);
4041 New->setInvalidDecl();
4044 mergeDeclAttributes(New, Old);
4045 // Warn if an already-declared variable is made a weak_import in a subsequent
4047 if (New->hasAttr<WeakImportAttr>() &&
4048 Old->getStorageClass() == SC_None &&
4049 !Old->hasAttr<WeakImportAttr>()) {
4050 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4051 notePreviousDefinition(Old, New->getLocation());
4052 // Remove weak_import attribute on new declaration.
4053 New->dropAttr<WeakImportAttr>();
4056 if (New->hasAttr<InternalLinkageAttr>() &&
4057 !Old->hasAttr<InternalLinkageAttr>()) {
4058 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4059 << New->getDeclName();
4060 notePreviousDefinition(Old, New->getLocation());
4061 New->dropAttr<InternalLinkageAttr>();
4065 VarDecl *MostRecent = Old->getMostRecentDecl();
4066 if (MostRecent != Old) {
4067 MergeVarDeclTypes(New, MostRecent,
4068 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4069 if (New->isInvalidDecl())
4073 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4074 if (New->isInvalidDecl())
4077 diag::kind PrevDiag;
4078 SourceLocation OldLocation;
4079 std::tie(PrevDiag, OldLocation) =
4080 getNoteDiagForInvalidRedeclaration(Old, New);
4082 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4083 if (New->getStorageClass() == SC_Static &&
4084 !New->isStaticDataMember() &&
4085 Old->hasExternalFormalLinkage()) {
4086 if (getLangOpts().MicrosoftExt) {
4087 Diag(New->getLocation(), diag::ext_static_non_static)
4088 << New->getDeclName();
4089 Diag(OldLocation, PrevDiag);
4091 Diag(New->getLocation(), diag::err_static_non_static)
4092 << New->getDeclName();
4093 Diag(OldLocation, PrevDiag);
4094 return New->setInvalidDecl();
4098 // For an identifier declared with the storage-class specifier
4099 // extern in a scope in which a prior declaration of that
4100 // identifier is visible,23) if the prior declaration specifies
4101 // internal or external linkage, the linkage of the identifier at
4102 // the later declaration is the same as the linkage specified at
4103 // the prior declaration. If no prior declaration is visible, or
4104 // if the prior declaration specifies no linkage, then the
4105 // identifier has external linkage.
4106 if (New->hasExternalStorage() && Old->hasLinkage())
4108 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4109 !New->isStaticDataMember() &&
4110 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4111 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4112 Diag(OldLocation, PrevDiag);
4113 return New->setInvalidDecl();
4116 // Check if extern is followed by non-extern and vice-versa.
4117 if (New->hasExternalStorage() &&
4118 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4119 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4120 Diag(OldLocation, PrevDiag);
4121 return New->setInvalidDecl();
4123 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4124 !New->hasExternalStorage()) {
4125 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4126 Diag(OldLocation, PrevDiag);
4127 return New->setInvalidDecl();
4130 if (CheckRedeclarationModuleOwnership(New, Old))
4133 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4135 // FIXME: The test for external storage here seems wrong? We still
4136 // need to check for mismatches.
4137 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4138 // Don't complain about out-of-line definitions of static members.
4139 !(Old->getLexicalDeclContext()->isRecord() &&
4140 !New->getLexicalDeclContext()->isRecord())) {
4141 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4142 Diag(OldLocation, PrevDiag);
4143 return New->setInvalidDecl();
4146 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4147 if (VarDecl *Def = Old->getDefinition()) {
4148 // C++1z [dcl.fcn.spec]p4:
4149 // If the definition of a variable appears in a translation unit before
4150 // its first declaration as inline, the program is ill-formed.
4151 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4152 Diag(Def->getLocation(), diag::note_previous_definition);
4156 // If this redeclaration makes the variable inline, we may need to add it to
4157 // UndefinedButUsed.
4158 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4159 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4160 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4163 if (New->getTLSKind() != Old->getTLSKind()) {
4164 if (!Old->getTLSKind()) {
4165 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4166 Diag(OldLocation, PrevDiag);
4167 } else if (!New->getTLSKind()) {
4168 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4169 Diag(OldLocation, PrevDiag);
4171 // Do not allow redeclaration to change the variable between requiring
4172 // static and dynamic initialization.
4173 // FIXME: GCC allows this, but uses the TLS keyword on the first
4174 // declaration to determine the kind. Do we need to be compatible here?
4175 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4176 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4177 Diag(OldLocation, PrevDiag);
4181 // C++ doesn't have tentative definitions, so go right ahead and check here.
4182 if (getLangOpts().CPlusPlus &&
4183 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4184 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4185 Old->getCanonicalDecl()->isConstexpr()) {
4186 // This definition won't be a definition any more once it's been merged.
4187 Diag(New->getLocation(),
4188 diag::warn_deprecated_redundant_constexpr_static_def);
4189 } else if (VarDecl *Def = Old->getDefinition()) {
4190 if (checkVarDeclRedefinition(Def, New))
4195 if (haveIncompatibleLanguageLinkages(Old, New)) {
4196 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4197 Diag(OldLocation, PrevDiag);
4198 New->setInvalidDecl();
4202 // Merge "used" flag.
4203 if (Old->getMostRecentDecl()->isUsed(false))
4206 // Keep a chain of previous declarations.
4207 New->setPreviousDecl(Old);
4209 NewTemplate->setPreviousDecl(OldTemplate);
4210 adjustDeclContextForDeclaratorDecl(New, Old);
4212 // Inherit access appropriately.
4213 New->setAccess(Old->getAccess());
4215 NewTemplate->setAccess(New->getAccess());
4217 if (Old->isInline())
4218 New->setImplicitlyInline();
4221 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4222 SourceManager &SrcMgr = getSourceManager();
4223 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4224 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4225 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4226 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4227 auto &HSI = PP.getHeaderSearchInfo();
4228 StringRef HdrFilename =
4229 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4231 auto noteFromModuleOrInclude = [&](Module *Mod,
4232 SourceLocation IncLoc) -> bool {
4233 // Redefinition errors with modules are common with non modular mapped
4234 // headers, example: a non-modular header H in module A that also gets
4235 // included directly in a TU. Pointing twice to the same header/definition
4236 // is confusing, try to get better diagnostics when modules is on.
4237 if (IncLoc.isValid()) {
4239 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4240 << HdrFilename.str() << Mod->getFullModuleName();
4241 if (!Mod->DefinitionLoc.isInvalid())
4242 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4243 << Mod->getFullModuleName();
4245 Diag(IncLoc, diag::note_redefinition_include_same_file)
4246 << HdrFilename.str();
4254 // Is it the same file and same offset? Provide more information on why
4255 // this leads to a redefinition error.
4256 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4257 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4258 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4260 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4261 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4263 // If the header has no guards, emit a note suggesting one.
4264 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4265 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4271 // Redefinition coming from different files or couldn't do better above.
4272 if (Old->getLocation().isValid())
4273 Diag(Old->getLocation(), diag::note_previous_definition);
4276 /// We've just determined that \p Old and \p New both appear to be definitions
4277 /// of the same variable. Either diagnose or fix the problem.
4278 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4279 if (!hasVisibleDefinition(Old) &&
4280 (New->getFormalLinkage() == InternalLinkage ||
4282 New->getDescribedVarTemplate() ||
4283 New->getNumTemplateParameterLists() ||
4284 New->getDeclContext()->isDependentContext())) {
4285 // The previous definition is hidden, and multiple definitions are
4286 // permitted (in separate TUs). Demote this to a declaration.
4287 New->demoteThisDefinitionToDeclaration();
4289 // Make the canonical definition visible.
4290 if (auto *OldTD = Old->getDescribedVarTemplate())
4291 makeMergedDefinitionVisible(OldTD);
4292 makeMergedDefinitionVisible(Old);
4295 Diag(New->getLocation(), diag::err_redefinition) << New;
4296 notePreviousDefinition(Old, New->getLocation());
4297 New->setInvalidDecl();
4302 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4303 /// no declarator (e.g. "struct foo;") is parsed.
4305 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4306 RecordDecl *&AnonRecord) {
4307 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4311 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4312 // disambiguate entities defined in different scopes.
4313 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4315 // We will pick our mangling number depending on which version of MSVC is being
4317 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4318 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4319 ? S->getMSCurManglingNumber()
4320 : S->getMSLastManglingNumber();
4323 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4324 if (!Context.getLangOpts().CPlusPlus)
4327 if (isa<CXXRecordDecl>(Tag->getParent())) {
4328 // If this tag is the direct child of a class, number it if
4330 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4332 MangleNumberingContext &MCtx =
4333 Context.getManglingNumberContext(Tag->getParent());
4334 Context.setManglingNumber(
4335 Tag, MCtx.getManglingNumber(
4336 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4340 // If this tag isn't a direct child of a class, number it if it is local.
4341 MangleNumberingContext *MCtx;
4342 Decl *ManglingContextDecl;
4343 std::tie(MCtx, ManglingContextDecl) =
4344 getCurrentMangleNumberContext(Tag->getDeclContext());
4346 Context.setManglingNumber(
4347 Tag, MCtx->getManglingNumber(
4348 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4352 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4353 TypedefNameDecl *NewTD) {
4354 if (TagFromDeclSpec->isInvalidDecl())
4357 // Do nothing if the tag already has a name for linkage purposes.
4358 if (TagFromDeclSpec->hasNameForLinkage())
4361 // A well-formed anonymous tag must always be a TUK_Definition.
4362 assert(TagFromDeclSpec->isThisDeclarationADefinition());
4364 // The type must match the tag exactly; no qualifiers allowed.
4365 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4366 Context.getTagDeclType(TagFromDeclSpec))) {
4367 if (getLangOpts().CPlusPlus)
4368 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4372 // If we've already computed linkage for the anonymous tag, then
4373 // adding a typedef name for the anonymous decl can change that
4374 // linkage, which might be a serious problem. Diagnose this as
4375 // unsupported and ignore the typedef name. TODO: we should
4376 // pursue this as a language defect and establish a formal rule
4377 // for how to handle it.
4378 if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4379 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4381 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4382 tagLoc = getLocForEndOfToken(tagLoc);
4384 llvm::SmallString<40> textToInsert;
4385 textToInsert += ' ';
4386 textToInsert += NewTD->getIdentifier()->getName();
4387 Diag(tagLoc, diag::note_typedef_changes_linkage)
4388 << FixItHint::CreateInsertion(tagLoc, textToInsert);
4392 // Otherwise, set this is the anon-decl typedef for the tag.
4393 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4396 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4398 case DeclSpec::TST_class:
4400 case DeclSpec::TST_struct:
4402 case DeclSpec::TST_interface:
4404 case DeclSpec::TST_union:
4406 case DeclSpec::TST_enum:
4409 llvm_unreachable("unexpected type specifier");
4413 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4414 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4415 /// parameters to cope with template friend declarations.
4417 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4418 MultiTemplateParamsArg TemplateParams,
4419 bool IsExplicitInstantiation,
4420 RecordDecl *&AnonRecord) {
4421 Decl *TagD = nullptr;
4422 TagDecl *Tag = nullptr;
4423 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4424 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4425 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4426 DS.getTypeSpecType() == DeclSpec::TST_union ||
4427 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4428 TagD = DS.getRepAsDecl();
4430 if (!TagD) // We probably had an error
4433 // Note that the above type specs guarantee that the
4434 // type rep is a Decl, whereas in many of the others
4436 if (isa<TagDecl>(TagD))
4437 Tag = cast<TagDecl>(TagD);
4438 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4439 Tag = CTD->getTemplatedDecl();
4443 handleTagNumbering(Tag, S);
4444 Tag->setFreeStanding();
4445 if (Tag->isInvalidDecl())
4449 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4450 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4451 // or incomplete types shall not be restrict-qualified."
4452 if (TypeQuals & DeclSpec::TQ_restrict)
4453 Diag(DS.getRestrictSpecLoc(),
4454 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4455 << DS.getSourceRange();
4458 if (DS.isInlineSpecified())
4459 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4460 << getLangOpts().CPlusPlus17;
4462 if (DS.hasConstexprSpecifier()) {
4463 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4464 // and definitions of functions and variables.
4465 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4466 // the declaration of a function or function template
4468 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4469 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4470 << DS.getConstexprSpecifier();
4472 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4473 << DS.getConstexprSpecifier();
4474 // Don't emit warnings after this error.
4478 DiagnoseFunctionSpecifiers(DS);
4480 if (DS.isFriendSpecified()) {
4481 // If we're dealing with a decl but not a TagDecl, assume that
4482 // whatever routines created it handled the friendship aspect.
4485 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4488 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4489 bool IsExplicitSpecialization =
4490 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4491 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4492 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4493 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4494 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4495 // nested-name-specifier unless it is an explicit instantiation
4496 // or an explicit specialization.
4498 // FIXME: We allow class template partial specializations here too, per the
4499 // obvious intent of DR1819.
4501 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4502 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4503 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4507 // Track whether this decl-specifier declares anything.
4508 bool DeclaresAnything = true;
4510 // Handle anonymous struct definitions.
4511 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4512 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4513 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4514 if (getLangOpts().CPlusPlus ||
4515 Record->getDeclContext()->isRecord()) {
4516 // If CurContext is a DeclContext that can contain statements,
4517 // RecursiveASTVisitor won't visit the decls that
4518 // BuildAnonymousStructOrUnion() will put into CurContext.
4519 // Also store them here so that they can be part of the
4520 // DeclStmt that gets created in this case.
4521 // FIXME: Also return the IndirectFieldDecls created by
4522 // BuildAnonymousStructOr union, for the same reason?
4523 if (CurContext->isFunctionOrMethod())
4524 AnonRecord = Record;
4525 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4526 Context.getPrintingPolicy());
4529 DeclaresAnything = false;
4534 // A struct-declaration that does not declare an anonymous structure or
4535 // anonymous union shall contain a struct-declarator-list.
4537 // This rule also existed in C89 and C99; the grammar for struct-declaration
4538 // did not permit a struct-declaration without a struct-declarator-list.
4539 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4540 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4541 // Check for Microsoft C extension: anonymous struct/union member.
4542 // Handle 2 kinds of anonymous struct/union:
4546 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4547 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4548 if ((Tag && Tag->getDeclName()) ||
4549 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4550 RecordDecl *Record = nullptr;
4552 Record = dyn_cast<RecordDecl>(Tag);
4553 else if (const RecordType *RT =
4554 DS.getRepAsType().get()->getAsStructureType())
4555 Record = RT->getDecl();
4556 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4557 Record = UT->getDecl();
4559 if (Record && getLangOpts().MicrosoftExt) {
4560 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4561 << Record->isUnion() << DS.getSourceRange();
4562 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4565 DeclaresAnything = false;
4569 // Skip all the checks below if we have a type error.
4570 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4571 (TagD && TagD->isInvalidDecl()))
4574 if (getLangOpts().CPlusPlus &&
4575 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4576 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4577 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4578 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4579 DeclaresAnything = false;
4581 if (!DS.isMissingDeclaratorOk()) {
4582 // Customize diagnostic for a typedef missing a name.
4583 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4584 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4585 << DS.getSourceRange();
4587 DeclaresAnything = false;
4590 if (DS.isModulePrivateSpecified() &&
4591 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4592 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4593 << Tag->getTagKind()
4594 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4596 ActOnDocumentableDecl(TagD);
4599 // A declaration [...] shall declare at least a declarator [...], a tag,
4600 // or the members of an enumeration.
4602 // [If there are no declarators], and except for the declaration of an
4603 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4604 // names into the program, or shall redeclare a name introduced by a
4605 // previous declaration.
4606 if (!DeclaresAnything) {
4607 // In C, we allow this as a (popular) extension / bug. Don't bother
4608 // producing further diagnostics for redundant qualifiers after this.
4609 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4614 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4615 // init-declarator-list of the declaration shall not be empty.
4616 // C++ [dcl.fct.spec]p1:
4617 // If a cv-qualifier appears in a decl-specifier-seq, the
4618 // init-declarator-list of the declaration shall not be empty.
4620 // Spurious qualifiers here appear to be valid in C.
4621 unsigned DiagID = diag::warn_standalone_specifier;
4622 if (getLangOpts().CPlusPlus)
4623 DiagID = diag::ext_standalone_specifier;
4625 // Note that a linkage-specification sets a storage class, but
4626 // 'extern "C" struct foo;' is actually valid and not theoretically
4628 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4629 if (SCS == DeclSpec::SCS_mutable)
4630 // Since mutable is not a viable storage class specifier in C, there is
4631 // no reason to treat it as an extension. Instead, diagnose as an error.
4632 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4633 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4634 Diag(DS.getStorageClassSpecLoc(), DiagID)
4635 << DeclSpec::getSpecifierName(SCS);
4638 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4639 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4640 << DeclSpec::getSpecifierName(TSCS);
4641 if (DS.getTypeQualifiers()) {
4642 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4643 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4644 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4645 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4646 // Restrict is covered above.
4647 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4648 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4649 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4650 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4653 // Warn about ignored type attributes, for example:
4654 // __attribute__((aligned)) struct A;
4655 // Attributes should be placed after tag to apply to type declaration.
4656 if (!DS.getAttributes().empty()) {
4657 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4658 if (TypeSpecType == DeclSpec::TST_class ||
4659 TypeSpecType == DeclSpec::TST_struct ||
4660 TypeSpecType == DeclSpec::TST_interface ||
4661 TypeSpecType == DeclSpec::TST_union ||
4662 TypeSpecType == DeclSpec::TST_enum) {
4663 for (const ParsedAttr &AL : DS.getAttributes())
4664 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4665 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4672 /// We are trying to inject an anonymous member into the given scope;
4673 /// check if there's an existing declaration that can't be overloaded.
4675 /// \return true if this is a forbidden redeclaration
4676 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4679 DeclarationName Name,
4680 SourceLocation NameLoc,
4682 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4683 Sema::ForVisibleRedeclaration);
4684 if (!SemaRef.LookupName(R, S)) return false;
4686 // Pick a representative declaration.
4687 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4688 assert(PrevDecl && "Expected a non-null Decl");
4690 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4693 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4695 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4700 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4701 /// anonymous struct or union AnonRecord into the owning context Owner
4702 /// and scope S. This routine will be invoked just after we realize
4703 /// that an unnamed union or struct is actually an anonymous union or
4710 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4711 /// // f into the surrounding scope.x
4714 /// This routine is recursive, injecting the names of nested anonymous
4715 /// structs/unions into the owning context and scope as well.
4717 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4718 RecordDecl *AnonRecord, AccessSpecifier AS,
4719 SmallVectorImpl<NamedDecl *> &Chaining) {
4720 bool Invalid = false;
4722 // Look every FieldDecl and IndirectFieldDecl with a name.
4723 for (auto *D : AnonRecord->decls()) {
4724 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4725 cast<NamedDecl>(D)->getDeclName()) {
4726 ValueDecl *VD = cast<ValueDecl>(D);
4727 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4729 AnonRecord->isUnion())) {
4730 // C++ [class.union]p2:
4731 // The names of the members of an anonymous union shall be
4732 // distinct from the names of any other entity in the
4733 // scope in which the anonymous union is declared.
4736 // C++ [class.union]p2:
4737 // For the purpose of name lookup, after the anonymous union
4738 // definition, the members of the anonymous union are
4739 // considered to have been defined in the scope in which the
4740 // anonymous union is declared.
4741 unsigned OldChainingSize = Chaining.size();
4742 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4743 Chaining.append(IF->chain_begin(), IF->chain_end());
4745 Chaining.push_back(VD);
4747 assert(Chaining.size() >= 2);
4748 NamedDecl **NamedChain =
4749 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4750 for (unsigned i = 0; i < Chaining.size(); i++)
4751 NamedChain[i] = Chaining[i];
4753 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4754 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4755 VD->getType(), {NamedChain, Chaining.size()});
4757 for (const auto *Attr : VD->attrs())
4758 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4760 IndirectField->setAccess(AS);
4761 IndirectField->setImplicit();
4762 SemaRef.PushOnScopeChains(IndirectField, S);
4764 // That includes picking up the appropriate access specifier.
4765 if (AS != AS_none) IndirectField->setAccess(AS);
4767 Chaining.resize(OldChainingSize);
4775 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4776 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4777 /// illegal input values are mapped to SC_None.
4779 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4780 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4781 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4782 "Parser allowed 'typedef' as storage class VarDecl.");
4783 switch (StorageClassSpec) {
4784 case DeclSpec::SCS_unspecified: return SC_None;
4785 case DeclSpec::SCS_extern:
4786 if (DS.isExternInLinkageSpec())
4789 case DeclSpec::SCS_static: return SC_Static;
4790 case DeclSpec::SCS_auto: return SC_Auto;
4791 case DeclSpec::SCS_register: return SC_Register;
4792 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4793 // Illegal SCSs map to None: error reporting is up to the caller.
4794 case DeclSpec::SCS_mutable: // Fall through.
4795 case DeclSpec::SCS_typedef: return SC_None;
4797 llvm_unreachable("unknown storage class specifier");
4800 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4801 assert(Record->hasInClassInitializer());
4803 for (const auto *I : Record->decls()) {
4804 const auto *FD = dyn_cast<FieldDecl>(I);
4805 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4806 FD = IFD->getAnonField();
4807 if (FD && FD->hasInClassInitializer())
4808 return FD->getLocation();
4811 llvm_unreachable("couldn't find in-class initializer");
4814 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4815 SourceLocation DefaultInitLoc) {
4816 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4819 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4820 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4823 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4824 CXXRecordDecl *AnonUnion) {
4825 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4828 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4831 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4832 /// anonymous structure or union. Anonymous unions are a C++ feature
4833 /// (C++ [class.union]) and a C11 feature; anonymous structures
4834 /// are a C11 feature and GNU C++ extension.
4835 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4838 const PrintingPolicy &Policy) {
4839 DeclContext *Owner = Record->getDeclContext();
4841 // Diagnose whether this anonymous struct/union is an extension.
4842 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4843 Diag(Record->getLocation(), diag::ext_anonymous_union);
4844 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4845 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4846 else if (!Record->isUnion() && !getLangOpts().C11)
4847 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4849 // C and C++ require different kinds of checks for anonymous
4851 bool Invalid = false;
4852 if (getLangOpts().CPlusPlus) {
4853 const char *PrevSpec = nullptr;
4854 if (Record->isUnion()) {
4855 // C++ [class.union]p6:
4856 // C++17 [class.union.anon]p2:
4857 // Anonymous unions declared in a named namespace or in the
4858 // global namespace shall be declared static.
4860 DeclContext *OwnerScope = Owner->getRedeclContext();
4861 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4862 (OwnerScope->isTranslationUnit() ||
4863 (OwnerScope->isNamespace() &&
4864 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4865 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4866 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4868 // Recover by adding 'static'.
4869 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4870 PrevSpec, DiagID, Policy);
4872 // C++ [class.union]p6:
4873 // A storage class is not allowed in a declaration of an
4874 // anonymous union in a class scope.
4875 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4876 isa<RecordDecl>(Owner)) {
4877 Diag(DS.getStorageClassSpecLoc(),
4878 diag::err_anonymous_union_with_storage_spec)
4879 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4881 // Recover by removing the storage specifier.
4882 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4884 PrevSpec, DiagID, Context.getPrintingPolicy());
4888 // Ignore const/volatile/restrict qualifiers.
4889 if (DS.getTypeQualifiers()) {
4890 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4891 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4892 << Record->isUnion() << "const"
4893 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4894 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4895 Diag(DS.getVolatileSpecLoc(),
4896 diag::ext_anonymous_struct_union_qualified)
4897 << Record->isUnion() << "volatile"
4898 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4899 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4900 Diag(DS.getRestrictSpecLoc(),
4901 diag::ext_anonymous_struct_union_qualified)
4902 << Record->isUnion() << "restrict"
4903 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4904 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4905 Diag(DS.getAtomicSpecLoc(),
4906 diag::ext_anonymous_struct_union_qualified)
4907 << Record->isUnion() << "_Atomic"
4908 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4909 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4910 Diag(DS.getUnalignedSpecLoc(),
4911 diag::ext_anonymous_struct_union_qualified)
4912 << Record->isUnion() << "__unaligned"
4913 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4915 DS.ClearTypeQualifiers();
4918 // C++ [class.union]p2:
4919 // The member-specification of an anonymous union shall only
4920 // define non-static data members. [Note: nested types and
4921 // functions cannot be declared within an anonymous union. ]
4922 for (auto *Mem : Record->decls()) {
4923 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4924 // C++ [class.union]p3:
4925 // An anonymous union shall not have private or protected
4926 // members (clause 11).
4927 assert(FD->getAccess() != AS_none);
4928 if (FD->getAccess() != AS_public) {
4929 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4930 << Record->isUnion() << (FD->getAccess() == AS_protected);
4934 // C++ [class.union]p1
4935 // An object of a class with a non-trivial constructor, a non-trivial
4936 // copy constructor, a non-trivial destructor, or a non-trivial copy
4937 // assignment operator cannot be a member of a union, nor can an
4938 // array of such objects.
4939 if (CheckNontrivialField(FD))
4941 } else if (Mem->isImplicit()) {
4942 // Any implicit members are fine.
4943 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4944 // This is a type that showed up in an
4945 // elaborated-type-specifier inside the anonymous struct or
4946 // union, but which actually declares a type outside of the
4947 // anonymous struct or union. It's okay.
4948 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4949 if (!MemRecord->isAnonymousStructOrUnion() &&
4950 MemRecord->getDeclName()) {
4951 // Visual C++ allows type definition in anonymous struct or union.
4952 if (getLangOpts().MicrosoftExt)
4953 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4954 << Record->isUnion();
4956 // This is a nested type declaration.
4957 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4958 << Record->isUnion();
4962 // This is an anonymous type definition within another anonymous type.
4963 // This is a popular extension, provided by Plan9, MSVC and GCC, but
4964 // not part of standard C++.
4965 Diag(MemRecord->getLocation(),
4966 diag::ext_anonymous_record_with_anonymous_type)
4967 << Record->isUnion();
4969 } else if (isa<AccessSpecDecl>(Mem)) {
4970 // Any access specifier is fine.
4971 } else if (isa<StaticAssertDecl>(Mem)) {
4972 // In C++1z, static_assert declarations are also fine.
4974 // We have something that isn't a non-static data
4975 // member. Complain about it.
4976 unsigned DK = diag::err_anonymous_record_bad_member;
4977 if (isa<TypeDecl>(Mem))
4978 DK = diag::err_anonymous_record_with_type;
4979 else if (isa<FunctionDecl>(Mem))
4980 DK = diag::err_anonymous_record_with_function;
4981 else if (isa<VarDecl>(Mem))
4982 DK = diag::err_anonymous_record_with_static;
4984 // Visual C++ allows type definition in anonymous struct or union.
4985 if (getLangOpts().MicrosoftExt &&
4986 DK == diag::err_anonymous_record_with_type)
4987 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4988 << Record->isUnion();
4990 Diag(Mem->getLocation(), DK) << Record->isUnion();
4996 // C++11 [class.union]p8 (DR1460):
4997 // At most one variant member of a union may have a
4998 // brace-or-equal-initializer.
4999 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5001 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5002 cast<CXXRecordDecl>(Record));
5005 if (!Record->isUnion() && !Owner->isRecord()) {
5006 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5007 << getLangOpts().CPlusPlus;
5012 // [If there are no declarators], and except for the declaration of an
5013 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5014 // names into the program
5015 // C++ [class.mem]p2:
5016 // each such member-declaration shall either declare at least one member
5017 // name of the class or declare at least one unnamed bit-field
5019 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5020 if (getLangOpts().CPlusPlus && Record->field_empty())
5021 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5023 // Mock up a declarator.
5024 Declarator Dc(DS, DeclaratorContext::MemberContext);
5025 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5026 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5028 // Create a declaration for this anonymous struct/union.
5029 NamedDecl *Anon = nullptr;
5030 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5031 Anon = FieldDecl::Create(
5032 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5033 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5034 /*BitWidth=*/nullptr, /*Mutable=*/false,
5035 /*InitStyle=*/ICIS_NoInit);
5036 Anon->setAccess(AS);
5037 ProcessDeclAttributes(S, Anon, Dc);
5039 if (getLangOpts().CPlusPlus)
5040 FieldCollector->Add(cast<FieldDecl>(Anon));
5042 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5043 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5044 if (SCSpec == DeclSpec::SCS_mutable) {
5045 // mutable can only appear on non-static class members, so it's always
5047 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5052 assert(DS.getAttributes().empty() && "No attribute expected");
5053 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5054 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5055 Context.getTypeDeclType(Record), TInfo, SC);
5057 // Default-initialize the implicit variable. This initialization will be
5058 // trivial in almost all cases, except if a union member has an in-class
5060 // union { int n = 0; };
5061 ActOnUninitializedDecl(Anon);
5063 Anon->setImplicit();
5065 // Mark this as an anonymous struct/union type.
5066 Record->setAnonymousStructOrUnion(true);
5068 // Add the anonymous struct/union object to the current
5069 // context. We'll be referencing this object when we refer to one of
5071 Owner->addDecl(Anon);
5073 // Inject the members of the anonymous struct/union into the owning
5074 // context and into the identifier resolver chain for name lookup
5076 SmallVector<NamedDecl*, 2> Chain;
5077 Chain.push_back(Anon);
5079 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5082 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5083 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5084 MangleNumberingContext *MCtx;
5085 Decl *ManglingContextDecl;
5086 std::tie(MCtx, ManglingContextDecl) =
5087 getCurrentMangleNumberContext(NewVD->getDeclContext());
5089 Context.setManglingNumber(
5090 NewVD, MCtx->getManglingNumber(
5091 NewVD, getMSManglingNumber(getLangOpts(), S)));
5092 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5098 Anon->setInvalidDecl();
5103 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5104 /// Microsoft C anonymous structure.
5105 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5108 /// struct A { int a; };
5109 /// struct B { struct A; int b; };
5116 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5117 RecordDecl *Record) {
5118 assert(Record && "expected a record!");
5120 // Mock up a declarator.
5121 Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5122 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5123 assert(TInfo && "couldn't build declarator info for anonymous struct");
5125 auto *ParentDecl = cast<RecordDecl>(CurContext);
5126 QualType RecTy = Context.getTypeDeclType(Record);
5128 // Create a declaration for this anonymous struct.
5130 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5131 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5132 /*BitWidth=*/nullptr, /*Mutable=*/false,
5133 /*InitStyle=*/ICIS_NoInit);
5134 Anon->setImplicit();
5136 // Add the anonymous struct object to the current context.
5137 CurContext->addDecl(Anon);
5139 // Inject the members of the anonymous struct into the current
5140 // context and into the identifier resolver chain for name lookup
5142 SmallVector<NamedDecl*, 2> Chain;
5143 Chain.push_back(Anon);
5145 RecordDecl *RecordDef = Record->getDefinition();
5146 if (RequireCompleteType(Anon->getLocation(), RecTy,
5147 diag::err_field_incomplete) ||
5148 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5150 Anon->setInvalidDecl();
5151 ParentDecl->setInvalidDecl();
5157 /// GetNameForDeclarator - Determine the full declaration name for the
5158 /// given Declarator.
5159 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5160 return GetNameFromUnqualifiedId(D.getName());
5163 /// Retrieves the declaration name from a parsed unqualified-id.
5165 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5166 DeclarationNameInfo NameInfo;
5167 NameInfo.setLoc(Name.StartLocation);
5169 switch (Name.getKind()) {
5171 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5172 case UnqualifiedIdKind::IK_Identifier:
5173 NameInfo.setName(Name.Identifier);
5176 case UnqualifiedIdKind::IK_DeductionGuideName: {
5177 // C++ [temp.deduct.guide]p3:
5178 // The simple-template-id shall name a class template specialization.
5179 // The template-name shall be the same identifier as the template-name
5180 // of the simple-template-id.
5181 // These together intend to imply that the template-name shall name a
5183 // FIXME: template<typename T> struct X {};
5184 // template<typename T> using Y = X<T>;
5185 // Y(int) -> Y<int>;
5186 // satisfies these rules but does not name a class template.
5187 TemplateName TN = Name.TemplateName.get().get();
5188 auto *Template = TN.getAsTemplateDecl();
5189 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5190 Diag(Name.StartLocation,
5191 diag::err_deduction_guide_name_not_class_template)
5192 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5194 Diag(Template->getLocation(), diag::note_template_decl_here);
5195 return DeclarationNameInfo();
5199 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5203 case UnqualifiedIdKind::IK_OperatorFunctionId:
5204 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5205 Name.OperatorFunctionId.Operator));
5206 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5207 = Name.OperatorFunctionId.SymbolLocations[0];
5208 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5209 = Name.EndLocation.getRawEncoding();
5212 case UnqualifiedIdKind::IK_LiteralOperatorId:
5213 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5215 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5218 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5219 TypeSourceInfo *TInfo;
5220 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5222 return DeclarationNameInfo();
5223 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5224 Context.getCanonicalType(Ty)));
5225 NameInfo.setNamedTypeInfo(TInfo);
5229 case UnqualifiedIdKind::IK_ConstructorName: {
5230 TypeSourceInfo *TInfo;
5231 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5233 return DeclarationNameInfo();
5234 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5235 Context.getCanonicalType(Ty)));
5236 NameInfo.setNamedTypeInfo(TInfo);
5240 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5241 // In well-formed code, we can only have a constructor
5242 // template-id that refers to the current context, so go there
5243 // to find the actual type being constructed.
5244 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5245 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5246 return DeclarationNameInfo();
5248 // Determine the type of the class being constructed.
5249 QualType CurClassType = Context.getTypeDeclType(CurClass);
5251 // FIXME: Check two things: that the template-id names the same type as
5252 // CurClassType, and that the template-id does not occur when the name
5255 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5256 Context.getCanonicalType(CurClassType)));
5257 // FIXME: should we retrieve TypeSourceInfo?
5258 NameInfo.setNamedTypeInfo(nullptr);
5262 case UnqualifiedIdKind::IK_DestructorName: {
5263 TypeSourceInfo *TInfo;
5264 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5266 return DeclarationNameInfo();
5267 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5268 Context.getCanonicalType(Ty)));
5269 NameInfo.setNamedTypeInfo(TInfo);
5273 case UnqualifiedIdKind::IK_TemplateId: {
5274 TemplateName TName = Name.TemplateId->Template.get();
5275 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5276 return Context.getNameForTemplate(TName, TNameLoc);
5279 } // switch (Name.getKind())
5281 llvm_unreachable("Unknown name kind");
5284 static QualType getCoreType(QualType Ty) {
5286 if (Ty->isPointerType() || Ty->isReferenceType())
5287 Ty = Ty->getPointeeType();
5288 else if (Ty->isArrayType())
5289 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5291 return Ty.withoutLocalFastQualifiers();
5295 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5296 /// and Definition have "nearly" matching parameters. This heuristic is
5297 /// used to improve diagnostics in the case where an out-of-line function
5298 /// definition doesn't match any declaration within the class or namespace.
5299 /// Also sets Params to the list of indices to the parameters that differ
5300 /// between the declaration and the definition. If hasSimilarParameters
5301 /// returns true and Params is empty, then all of the parameters match.
5302 static bool hasSimilarParameters(ASTContext &Context,
5303 FunctionDecl *Declaration,
5304 FunctionDecl *Definition,
5305 SmallVectorImpl<unsigned> &Params) {
5307 if (Declaration->param_size() != Definition->param_size())
5309 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5310 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5311 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5313 // The parameter types are identical
5314 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5317 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5318 QualType DefParamBaseTy = getCoreType(DefParamTy);
5319 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5320 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5322 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5323 (DeclTyName && DeclTyName == DefTyName))
5324 Params.push_back(Idx);
5325 else // The two parameters aren't even close
5332 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5333 /// declarator needs to be rebuilt in the current instantiation.
5334 /// Any bits of declarator which appear before the name are valid for
5335 /// consideration here. That's specifically the type in the decl spec
5336 /// and the base type in any member-pointer chunks.
5337 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5338 DeclarationName Name) {
5339 // The types we specifically need to rebuild are:
5340 // - typenames, typeofs, and decltypes
5341 // - types which will become injected class names
5342 // Of course, we also need to rebuild any type referencing such a
5343 // type. It's safest to just say "dependent", but we call out a
5346 DeclSpec &DS = D.getMutableDeclSpec();
5347 switch (DS.getTypeSpecType()) {
5348 case DeclSpec::TST_typename:
5349 case DeclSpec::TST_typeofType:
5350 case DeclSpec::TST_underlyingType:
5351 case DeclSpec::TST_atomic: {
5352 // Grab the type from the parser.
5353 TypeSourceInfo *TSI = nullptr;
5354 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5355 if (T.isNull() || !T->isDependentType()) break;
5357 // Make sure there's a type source info. This isn't really much
5358 // of a waste; most dependent types should have type source info
5359 // attached already.
5361 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5363 // Rebuild the type in the current instantiation.
5364 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5365 if (!TSI) return true;
5367 // Store the new type back in the decl spec.
5368 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5369 DS.UpdateTypeRep(LocType);
5373 case DeclSpec::TST_decltype:
5374 case DeclSpec::TST_typeofExpr: {
5375 Expr *E = DS.getRepAsExpr();
5376 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5377 if (Result.isInvalid()) return true;
5378 DS.UpdateExprRep(Result.get());
5383 // Nothing to do for these decl specs.
5387 // It doesn't matter what order we do this in.
5388 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5389 DeclaratorChunk &Chunk = D.getTypeObject(I);
5391 // The only type information in the declarator which can come
5392 // before the declaration name is the base type of a member
5394 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5397 // Rebuild the scope specifier in-place.
5398 CXXScopeSpec &SS = Chunk.Mem.Scope();
5399 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5406 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5407 D.setFunctionDefinitionKind(FDK_Declaration);
5408 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5410 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5411 Dcl && Dcl->getDeclContext()->isFileContext())
5412 Dcl->setTopLevelDeclInObjCContainer();
5414 if (getLangOpts().OpenCL)
5415 setCurrentOpenCLExtensionForDecl(Dcl);
5420 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5421 /// If T is the name of a class, then each of the following shall have a
5422 /// name different from T:
5423 /// - every static data member of class T;
5424 /// - every member function of class T
5425 /// - every member of class T that is itself a type;
5426 /// \returns true if the declaration name violates these rules.
5427 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5428 DeclarationNameInfo NameInfo) {
5429 DeclarationName Name = NameInfo.getName();
5431 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5432 while (Record && Record->isAnonymousStructOrUnion())
5433 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5434 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5435 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5442 /// Diagnose a declaration whose declarator-id has the given
5443 /// nested-name-specifier.
5445 /// \param SS The nested-name-specifier of the declarator-id.
5447 /// \param DC The declaration context to which the nested-name-specifier
5450 /// \param Name The name of the entity being declared.
5452 /// \param Loc The location of the name of the entity being declared.
5454 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5455 /// we're declaring an explicit / partial specialization / instantiation.
5457 /// \returns true if we cannot safely recover from this error, false otherwise.
5458 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5459 DeclarationName Name,
5460 SourceLocation Loc, bool IsTemplateId) {
5461 DeclContext *Cur = CurContext;
5462 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5463 Cur = Cur->getParent();
5465 // If the user provided a superfluous scope specifier that refers back to the
5466 // class in which the entity is already declared, diagnose and ignore it.
5472 // Note, it was once ill-formed to give redundant qualification in all
5473 // contexts, but that rule was removed by DR482.
5474 if (Cur->Equals(DC)) {
5475 if (Cur->isRecord()) {
5476 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5477 : diag::err_member_extra_qualification)
5478 << Name << FixItHint::CreateRemoval(SS.getRange());
5481 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5486 // Check whether the qualifying scope encloses the scope of the original
5487 // declaration. For a template-id, we perform the checks in
5488 // CheckTemplateSpecializationScope.
5489 if (!Cur->Encloses(DC) && !IsTemplateId) {
5490 if (Cur->isRecord())
5491 Diag(Loc, diag::err_member_qualification)
5492 << Name << SS.getRange();
5493 else if (isa<TranslationUnitDecl>(DC))
5494 Diag(Loc, diag::err_invalid_declarator_global_scope)
5495 << Name << SS.getRange();
5496 else if (isa<FunctionDecl>(Cur))
5497 Diag(Loc, diag::err_invalid_declarator_in_function)
5498 << Name << SS.getRange();
5499 else if (isa<BlockDecl>(Cur))
5500 Diag(Loc, diag::err_invalid_declarator_in_block)
5501 << Name << SS.getRange();
5503 Diag(Loc, diag::err_invalid_declarator_scope)
5504 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5509 if (Cur->isRecord()) {
5510 // Cannot qualify members within a class.
5511 Diag(Loc, diag::err_member_qualification)
5512 << Name << SS.getRange();
5515 // C++ constructors and destructors with incorrect scopes can break
5516 // our AST invariants by having the wrong underlying types. If
5517 // that's the case, then drop this declaration entirely.
5518 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5519 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5520 !Context.hasSameType(Name.getCXXNameType(),
5521 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5527 // C++11 [dcl.meaning]p1:
5528 // [...] "The nested-name-specifier of the qualified declarator-id shall
5529 // not begin with a decltype-specifer"
5530 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5531 while (SpecLoc.getPrefix())
5532 SpecLoc = SpecLoc.getPrefix();
5533 if (dyn_cast_or_null<DecltypeType>(
5534 SpecLoc.getNestedNameSpecifier()->getAsType()))
5535 Diag(Loc, diag::err_decltype_in_declarator)
5536 << SpecLoc.getTypeLoc().getSourceRange();
5541 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5542 MultiTemplateParamsArg TemplateParamLists) {
5543 // TODO: consider using NameInfo for diagnostic.
5544 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5545 DeclarationName Name = NameInfo.getName();
5547 // All of these full declarators require an identifier. If it doesn't have
5548 // one, the ParsedFreeStandingDeclSpec action should be used.
5549 if (D.isDecompositionDeclarator()) {
5550 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5552 if (!D.isInvalidType()) // Reject this if we think it is valid.
5553 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5554 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5556 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5559 // The scope passed in may not be a decl scope. Zip up the scope tree until
5560 // we find one that is.
5561 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5562 (S->getFlags() & Scope::TemplateParamScope) != 0)
5565 DeclContext *DC = CurContext;
5566 if (D.getCXXScopeSpec().isInvalid())
5568 else if (D.getCXXScopeSpec().isSet()) {
5569 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5570 UPPC_DeclarationQualifier))
5573 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5574 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5575 if (!DC || isa<EnumDecl>(DC)) {
5576 // If we could not compute the declaration context, it's because the
5577 // declaration context is dependent but does not refer to a class,
5578 // class template, or class template partial specialization. Complain
5579 // and return early, to avoid the coming semantic disaster.
5580 Diag(D.getIdentifierLoc(),
5581 diag::err_template_qualified_declarator_no_match)
5582 << D.getCXXScopeSpec().getScopeRep()
5583 << D.getCXXScopeSpec().getRange();
5586 bool IsDependentContext = DC->isDependentContext();
5588 if (!IsDependentContext &&
5589 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5592 // If a class is incomplete, do not parse entities inside it.
5593 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5594 Diag(D.getIdentifierLoc(),
5595 diag::err_member_def_undefined_record)
5596 << Name << DC << D.getCXXScopeSpec().getRange();
5599 if (!D.getDeclSpec().isFriendSpecified()) {
5600 if (diagnoseQualifiedDeclaration(
5601 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5602 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5610 // Check whether we need to rebuild the type of the given
5611 // declaration in the current instantiation.
5612 if (EnteringContext && IsDependentContext &&
5613 TemplateParamLists.size() != 0) {
5614 ContextRAII SavedContext(*this, DC);
5615 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5620 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5621 QualType R = TInfo->getType();
5623 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5624 UPPC_DeclarationType))
5627 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5628 forRedeclarationInCurContext());
5630 // See if this is a redefinition of a variable in the same scope.
5631 if (!D.getCXXScopeSpec().isSet()) {
5632 bool IsLinkageLookup = false;
5633 bool CreateBuiltins = false;
5635 // If the declaration we're planning to build will be a function
5636 // or object with linkage, then look for another declaration with
5637 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5639 // If the declaration we're planning to build will be declared with
5640 // external linkage in the translation unit, create any builtin with
5642 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5644 else if (CurContext->isFunctionOrMethod() &&
5645 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5646 R->isFunctionType())) {
5647 IsLinkageLookup = true;
5649 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5650 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5651 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5652 CreateBuiltins = true;
5654 if (IsLinkageLookup) {
5655 Previous.clear(LookupRedeclarationWithLinkage);
5656 Previous.setRedeclarationKind(ForExternalRedeclaration);
5659 LookupName(Previous, S, CreateBuiltins);
5660 } else { // Something like "int foo::x;"
5661 LookupQualifiedName(Previous, DC);
5663 // C++ [dcl.meaning]p1:
5664 // When the declarator-id is qualified, the declaration shall refer to a
5665 // previously declared member of the class or namespace to which the
5666 // qualifier refers (or, in the case of a namespace, of an element of the
5667 // inline namespace set of that namespace (7.3.1)) or to a specialization
5670 // Note that we already checked the context above, and that we do not have
5671 // enough information to make sure that Previous contains the declaration
5672 // we want to match. For example, given:
5679 // void X::f(int) { } // ill-formed
5681 // In this case, Previous will point to the overload set
5682 // containing the two f's declared in X, but neither of them
5685 // C++ [dcl.meaning]p1:
5686 // [...] the member shall not merely have been introduced by a
5687 // using-declaration in the scope of the class or namespace nominated by
5688 // the nested-name-specifier of the declarator-id.
5689 RemoveUsingDecls(Previous);
5692 if (Previous.isSingleResult() &&
5693 Previous.getFoundDecl()->isTemplateParameter()) {
5694 // Maybe we will complain about the shadowed template parameter.
5695 if (!D.isInvalidType())
5696 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5697 Previous.getFoundDecl());
5699 // Just pretend that we didn't see the previous declaration.
5703 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5704 // Forget that the previous declaration is the injected-class-name.
5707 // In C++, the previous declaration we find might be a tag type
5708 // (class or enum). In this case, the new declaration will hide the
5709 // tag type. Note that this applies to functions, function templates, and
5710 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5711 if (Previous.isSingleTagDecl() &&
5712 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5713 (TemplateParamLists.size() == 0 || R->isFunctionType()))
5716 // Check that there are no default arguments other than in the parameters
5717 // of a function declaration (C++ only).
5718 if (getLangOpts().CPlusPlus)
5719 CheckExtraCXXDefaultArguments(D);
5723 bool AddToScope = true;
5724 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5725 if (TemplateParamLists.size()) {
5726 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5730 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5731 } else if (R->isFunctionType()) {
5732 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5736 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5743 // If this has an identifier and is not a function template specialization,
5744 // add it to the scope stack.
5745 if (New->getDeclName() && AddToScope)
5746 PushOnScopeChains(New, S);
5748 if (isInOpenMPDeclareTargetContext())
5749 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5754 /// Helper method to turn variable array types into constant array
5755 /// types in certain situations which would otherwise be errors (for
5756 /// GCC compatibility).
5757 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5758 ASTContext &Context,
5759 bool &SizeIsNegative,
5760 llvm::APSInt &Oversized) {
5761 // This method tries to turn a variable array into a constant
5762 // array even when the size isn't an ICE. This is necessary
5763 // for compatibility with code that depends on gcc's buggy
5764 // constant expression folding, like struct {char x[(int)(char*)2];}
5765 SizeIsNegative = false;
5768 if (T->isDependentType())
5771 QualifierCollector Qs;
5772 const Type *Ty = Qs.strip(T);
5774 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5775 QualType Pointee = PTy->getPointeeType();
5776 QualType FixedType =
5777 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5779 if (FixedType.isNull()) return FixedType;
5780 FixedType = Context.getPointerType(FixedType);
5781 return Qs.apply(Context, FixedType);
5783 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5784 QualType Inner = PTy->getInnerType();
5785 QualType FixedType =
5786 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5788 if (FixedType.isNull()) return FixedType;
5789 FixedType = Context.getParenType(FixedType);
5790 return Qs.apply(Context, FixedType);
5793 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5796 // FIXME: We should probably handle this case
5797 if (VLATy->getElementType()->isVariablyModifiedType())
5800 Expr::EvalResult Result;
5801 if (!VLATy->getSizeExpr() ||
5802 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5805 llvm::APSInt Res = Result.Val.getInt();
5807 // Check whether the array size is negative.
5808 if (Res.isSigned() && Res.isNegative()) {
5809 SizeIsNegative = true;
5813 // Check whether the array is too large to be addressed.
5814 unsigned ActiveSizeBits
5815 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5817 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5822 return Context.getConstantArrayType(
5823 VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5827 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5828 SrcTL = SrcTL.getUnqualifiedLoc();
5829 DstTL = DstTL.getUnqualifiedLoc();
5830 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5831 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5832 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5833 DstPTL.getPointeeLoc());
5834 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5837 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5838 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5839 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5840 DstPTL.getInnerLoc());
5841 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5842 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5845 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5846 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5847 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5848 TypeLoc DstElemTL = DstATL.getElementLoc();
5849 DstElemTL.initializeFullCopy(SrcElemTL);
5850 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5851 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5852 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5855 /// Helper method to turn variable array types into constant array
5856 /// types in certain situations which would otherwise be errors (for
5857 /// GCC compatibility).
5858 static TypeSourceInfo*
5859 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5860 ASTContext &Context,
5861 bool &SizeIsNegative,
5862 llvm::APSInt &Oversized) {
5864 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5865 SizeIsNegative, Oversized);
5866 if (FixedTy.isNull())
5868 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5869 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5870 FixedTInfo->getTypeLoc());
5874 /// Register the given locally-scoped extern "C" declaration so
5875 /// that it can be found later for redeclarations. We include any extern "C"
5876 /// declaration that is not visible in the translation unit here, not just
5877 /// function-scope declarations.
5879 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5880 if (!getLangOpts().CPlusPlus &&
5881 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5882 // Don't need to track declarations in the TU in C.
5885 // Note that we have a locally-scoped external with this name.
5886 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5889 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5890 // FIXME: We can have multiple results via __attribute__((overloadable)).
5891 auto Result = Context.getExternCContextDecl()->lookup(Name);
5892 return Result.empty() ? nullptr : *Result.begin();
5895 /// Diagnose function specifiers on a declaration of an identifier that
5896 /// does not identify a function.
5897 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5898 // FIXME: We should probably indicate the identifier in question to avoid
5899 // confusion for constructs like "virtual int a(), b;"
5900 if (DS.isVirtualSpecified())
5901 Diag(DS.getVirtualSpecLoc(),
5902 diag::err_virtual_non_function);
5904 if (DS.hasExplicitSpecifier())
5905 Diag(DS.getExplicitSpecLoc(),
5906 diag::err_explicit_non_function);
5908 if (DS.isNoreturnSpecified())
5909 Diag(DS.getNoreturnSpecLoc(),
5910 diag::err_noreturn_non_function);
5914 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5915 TypeSourceInfo *TInfo, LookupResult &Previous) {
5916 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5917 if (D.getCXXScopeSpec().isSet()) {
5918 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5919 << D.getCXXScopeSpec().getRange();
5921 // Pretend we didn't see the scope specifier.
5926 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5928 if (D.getDeclSpec().isInlineSpecified())
5929 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5930 << getLangOpts().CPlusPlus17;
5931 if (D.getDeclSpec().hasConstexprSpecifier())
5932 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5933 << 1 << D.getDeclSpec().getConstexprSpecifier();
5935 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5936 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5937 Diag(D.getName().StartLocation,
5938 diag::err_deduction_guide_invalid_specifier)
5941 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5942 << D.getName().getSourceRange();
5946 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5947 if (!NewTD) return nullptr;
5949 // Handle attributes prior to checking for duplicates in MergeVarDecl
5950 ProcessDeclAttributes(S, NewTD, D);
5952 CheckTypedefForVariablyModifiedType(S, NewTD);
5954 bool Redeclaration = D.isRedeclaration();
5955 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5956 D.setRedeclaration(Redeclaration);
5961 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5962 // C99 6.7.7p2: If a typedef name specifies a variably modified type
5963 // then it shall have block scope.
5964 // Note that variably modified types must be fixed before merging the decl so
5965 // that redeclarations will match.
5966 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5967 QualType T = TInfo->getType();
5968 if (T->isVariablyModifiedType()) {
5969 setFunctionHasBranchProtectedScope();
5971 if (S->getFnParent() == nullptr) {
5972 bool SizeIsNegative;
5973 llvm::APSInt Oversized;
5974 TypeSourceInfo *FixedTInfo =
5975 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5979 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5980 NewTD->setTypeSourceInfo(FixedTInfo);
5983 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5984 else if (T->isVariableArrayType())
5985 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5986 else if (Oversized.getBoolValue())
5987 Diag(NewTD->getLocation(), diag::err_array_too_large)
5988 << Oversized.toString(10);
5990 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5991 NewTD->setInvalidDecl();
5997 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5998 /// declares a typedef-name, either using the 'typedef' type specifier or via
5999 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6001 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6002 LookupResult &Previous, bool &Redeclaration) {
6004 // Find the shadowed declaration before filtering for scope.
6005 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6007 // Merge the decl with the existing one if appropriate. If the decl is
6008 // in an outer scope, it isn't the same thing.
6009 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6010 /*AllowInlineNamespace*/false);
6011 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6012 if (!Previous.empty()) {
6013 Redeclaration = true;
6014 MergeTypedefNameDecl(S, NewTD, Previous);
6016 inferGslPointerAttribute(NewTD);
6019 if (ShadowedDecl && !Redeclaration)
6020 CheckShadow(NewTD, ShadowedDecl, Previous);
6022 // If this is the C FILE type, notify the AST context.
6023 if (IdentifierInfo *II = NewTD->getIdentifier())
6024 if (!NewTD->isInvalidDecl() &&
6025 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6026 if (II->isStr("FILE"))
6027 Context.setFILEDecl(NewTD);
6028 else if (II->isStr("jmp_buf"))
6029 Context.setjmp_bufDecl(NewTD);
6030 else if (II->isStr("sigjmp_buf"))
6031 Context.setsigjmp_bufDecl(NewTD);
6032 else if (II->isStr("ucontext_t"))
6033 Context.setucontext_tDecl(NewTD);
6039 /// Determines whether the given declaration is an out-of-scope
6040 /// previous declaration.
6042 /// This routine should be invoked when name lookup has found a
6043 /// previous declaration (PrevDecl) that is not in the scope where a
6044 /// new declaration by the same name is being introduced. If the new
6045 /// declaration occurs in a local scope, previous declarations with
6046 /// linkage may still be considered previous declarations (C99
6047 /// 6.2.2p4-5, C++ [basic.link]p6).
6049 /// \param PrevDecl the previous declaration found by name
6052 /// \param DC the context in which the new declaration is being
6055 /// \returns true if PrevDecl is an out-of-scope previous declaration
6056 /// for a new delcaration with the same name.
6058 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6059 ASTContext &Context) {
6063 if (!PrevDecl->hasLinkage())
6066 if (Context.getLangOpts().CPlusPlus) {
6067 // C++ [basic.link]p6:
6068 // If there is a visible declaration of an entity with linkage
6069 // having the same name and type, ignoring entities declared
6070 // outside the innermost enclosing namespace scope, the block
6071 // scope declaration declares that same entity and receives the
6072 // linkage of the previous declaration.
6073 DeclContext *OuterContext = DC->getRedeclContext();
6074 if (!OuterContext->isFunctionOrMethod())
6075 // This rule only applies to block-scope declarations.
6078 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6079 if (PrevOuterContext->isRecord())
6080 // We found a member function: ignore it.
6083 // Find the innermost enclosing namespace for the new and
6084 // previous declarations.
6085 OuterContext = OuterContext->getEnclosingNamespaceContext();
6086 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6088 // The previous declaration is in a different namespace, so it
6089 // isn't the same function.
6090 if (!OuterContext->Equals(PrevOuterContext))
6097 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6098 CXXScopeSpec &SS = D.getCXXScopeSpec();
6099 if (!SS.isSet()) return;
6100 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6103 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6104 QualType type = decl->getType();
6105 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6106 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6107 // Various kinds of declaration aren't allowed to be __autoreleasing.
6108 unsigned kind = -1U;
6109 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6110 if (var->hasAttr<BlocksAttr>())
6111 kind = 0; // __block
6112 else if (!var->hasLocalStorage())
6114 } else if (isa<ObjCIvarDecl>(decl)) {
6116 } else if (isa<FieldDecl>(decl)) {
6121 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6124 } else if (lifetime == Qualifiers::OCL_None) {
6125 // Try to infer lifetime.
6126 if (!type->isObjCLifetimeType())
6129 lifetime = type->getObjCARCImplicitLifetime();
6130 type = Context.getLifetimeQualifiedType(type, lifetime);
6131 decl->setType(type);
6134 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6135 // Thread-local variables cannot have lifetime.
6136 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6137 var->getTLSKind()) {
6138 Diag(var->getLocation(), diag::err_arc_thread_ownership)
6147 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6148 if (Decl->getType().hasAddressSpace())
6150 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6151 QualType Type = Var->getType();
6152 if (Type->isSamplerT() || Type->isVoidType())
6154 LangAS ImplAS = LangAS::opencl_private;
6155 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6156 Var->hasGlobalStorage())
6157 ImplAS = LangAS::opencl_global;
6158 // If the original type from a decayed type is an array type and that array
6159 // type has no address space yet, deduce it now.
6160 if (auto DT = dyn_cast<DecayedType>(Type)) {
6161 auto OrigTy = DT->getOriginalType();
6162 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6163 // Add the address space to the original array type and then propagate
6164 // that to the element type through `getAsArrayType`.
6165 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6166 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6167 // Re-generate the decayed type.
6168 Type = Context.getDecayedType(OrigTy);
6171 Type = Context.getAddrSpaceQualType(Type, ImplAS);
6172 // Apply any qualifiers (including address space) from the array type to
6173 // the element type. This implements C99 6.7.3p8: "If the specification of
6174 // an array type includes any type qualifiers, the element type is so
6175 // qualified, not the array type."
6176 if (Type->isArrayType())
6177 Type = QualType(Context.getAsArrayType(Type), 0);
6178 Decl->setType(Type);
6182 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6183 // Ensure that an auto decl is deduced otherwise the checks below might cache
6184 // the wrong linkage.
6185 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6187 // 'weak' only applies to declarations with external linkage.
6188 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6189 if (!ND.isExternallyVisible()) {
6190 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6191 ND.dropAttr<WeakAttr>();
6194 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6195 if (ND.isExternallyVisible()) {
6196 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6197 ND.dropAttr<WeakRefAttr>();
6198 ND.dropAttr<AliasAttr>();
6202 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6203 if (VD->hasInit()) {
6204 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6205 assert(VD->isThisDeclarationADefinition() &&
6206 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6207 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6208 VD->dropAttr<AliasAttr>();
6213 // 'selectany' only applies to externally visible variable declarations.
6214 // It does not apply to functions.
6215 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6216 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6217 S.Diag(Attr->getLocation(),
6218 diag::err_attribute_selectany_non_extern_data);
6219 ND.dropAttr<SelectAnyAttr>();
6223 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6224 auto *VD = dyn_cast<VarDecl>(&ND);
6225 bool IsAnonymousNS = false;
6226 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6228 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6229 while (NS && !IsAnonymousNS) {
6230 IsAnonymousNS = NS->isAnonymousNamespace();
6231 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6234 // dll attributes require external linkage. Static locals may have external
6235 // linkage but still cannot be explicitly imported or exported.
6236 // In Microsoft mode, a variable defined in anonymous namespace must have
6237 // external linkage in order to be exported.
6238 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6239 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6240 (!AnonNSInMicrosoftMode &&
6241 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6242 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6244 ND.setInvalidDecl();
6248 // Virtual functions cannot be marked as 'notail'.
6249 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6250 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6251 if (MD->isVirtual()) {
6252 S.Diag(ND.getLocation(),
6253 diag::err_invalid_attribute_on_virtual_function)
6255 ND.dropAttr<NotTailCalledAttr>();
6258 // Check the attributes on the function type, if any.
6259 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6260 // Don't declare this variable in the second operand of the for-statement;
6261 // GCC miscompiles that by ending its lifetime before evaluating the
6262 // third operand. See gcc.gnu.org/PR86769.
6263 AttributedTypeLoc ATL;
6264 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6265 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6266 TL = ATL.getModifiedLoc()) {
6267 // The [[lifetimebound]] attribute can be applied to the implicit object
6268 // parameter of a non-static member function (other than a ctor or dtor)
6269 // by applying it to the function type.
6270 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6271 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6272 if (!MD || MD->isStatic()) {
6273 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6274 << !MD << A->getRange();
6275 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6276 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6277 << isa<CXXDestructorDecl>(MD) << A->getRange();
6284 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6286 bool IsSpecialization,
6287 bool IsDefinition) {
6288 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6291 bool IsTemplate = false;
6292 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6293 OldDecl = OldTD->getTemplatedDecl();
6295 if (!IsSpecialization)
6296 IsDefinition = false;
6298 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6299 NewDecl = NewTD->getTemplatedDecl();
6303 if (!OldDecl || !NewDecl)
6306 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6307 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6308 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6309 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6311 // dllimport and dllexport are inheritable attributes so we have to exclude
6312 // inherited attribute instances.
6313 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6314 (NewExportAttr && !NewExportAttr->isInherited());
6316 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6317 // the only exception being explicit specializations.
6318 // Implicitly generated declarations are also excluded for now because there
6319 // is no other way to switch these to use dllimport or dllexport.
6320 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6322 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6323 // Allow with a warning for free functions and global variables.
6324 bool JustWarn = false;
6325 if (!OldDecl->isCXXClassMember()) {
6326 auto *VD = dyn_cast<VarDecl>(OldDecl);
6327 if (VD && !VD->getDescribedVarTemplate())
6329 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6330 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6334 // We cannot change a declaration that's been used because IR has already
6335 // been emitted. Dllimported functions will still work though (modulo
6336 // address equality) as they can use the thunk.
6337 if (OldDecl->isUsed())
6338 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6341 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6342 : diag::err_attribute_dll_redeclaration;
6343 S.Diag(NewDecl->getLocation(), DiagID)
6345 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6346 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6348 NewDecl->setInvalidDecl();
6353 // A redeclaration is not allowed to drop a dllimport attribute, the only
6354 // exceptions being inline function definitions (except for function
6355 // templates), local extern declarations, qualified friend declarations or
6356 // special MSVC extension: in the last case, the declaration is treated as if
6357 // it were marked dllexport.
6358 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6359 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6360 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6361 // Ignore static data because out-of-line definitions are diagnosed
6363 IsStaticDataMember = VD->isStaticDataMember();
6364 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6365 VarDecl::DeclarationOnly;
6366 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6367 IsInline = FD->isInlined();
6368 IsQualifiedFriend = FD->getQualifier() &&
6369 FD->getFriendObjectKind() == Decl::FOK_Declared;
6372 if (OldImportAttr && !HasNewAttr &&
6373 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6374 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6375 if (IsMicrosoft && IsDefinition) {
6376 S.Diag(NewDecl->getLocation(),
6377 diag::warn_redeclaration_without_import_attribute)
6379 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6380 NewDecl->dropAttr<DLLImportAttr>();
6382 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6384 S.Diag(NewDecl->getLocation(),
6385 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6386 << NewDecl << OldImportAttr;
6387 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6388 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6389 OldDecl->dropAttr<DLLImportAttr>();
6390 NewDecl->dropAttr<DLLImportAttr>();
6392 } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6393 // In MinGW, seeing a function declared inline drops the dllimport
6395 OldDecl->dropAttr<DLLImportAttr>();
6396 NewDecl->dropAttr<DLLImportAttr>();
6397 S.Diag(NewDecl->getLocation(),
6398 diag::warn_dllimport_dropped_from_inline_function)
6399 << NewDecl << OldImportAttr;
6402 // A specialization of a class template member function is processed here
6403 // since it's a redeclaration. If the parent class is dllexport, the
6404 // specialization inherits that attribute. This doesn't happen automatically
6405 // since the parent class isn't instantiated until later.
6406 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6407 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6408 !NewImportAttr && !NewExportAttr) {
6409 if (const DLLExportAttr *ParentExportAttr =
6410 MD->getParent()->getAttr<DLLExportAttr>()) {
6411 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6412 NewAttr->setInherited(true);
6413 NewDecl->addAttr(NewAttr);
6419 /// Given that we are within the definition of the given function,
6420 /// will that definition behave like C99's 'inline', where the
6421 /// definition is discarded except for optimization purposes?
6422 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6423 // Try to avoid calling GetGVALinkageForFunction.
6425 // All cases of this require the 'inline' keyword.
6426 if (!FD->isInlined()) return false;
6428 // This is only possible in C++ with the gnu_inline attribute.
6429 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6432 // Okay, go ahead and call the relatively-more-expensive function.
6433 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6436 /// Determine whether a variable is extern "C" prior to attaching
6437 /// an initializer. We can't just call isExternC() here, because that
6438 /// will also compute and cache whether the declaration is externally
6439 /// visible, which might change when we attach the initializer.
6441 /// This can only be used if the declaration is known to not be a
6442 /// redeclaration of an internal linkage declaration.
6448 /// Attaching the initializer here makes this declaration not externally
6449 /// visible, because its type has internal linkage.
6451 /// FIXME: This is a hack.
6452 template<typename T>
6453 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6454 if (S.getLangOpts().CPlusPlus) {
6455 // In C++, the overloadable attribute negates the effects of extern "C".
6456 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6459 // So do CUDA's host/device attributes.
6460 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6461 D->template hasAttr<CUDAHostAttr>()))
6464 return D->isExternC();
6467 static bool shouldConsiderLinkage(const VarDecl *VD) {
6468 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6469 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6470 isa<OMPDeclareMapperDecl>(DC))
6471 return VD->hasExternalStorage();
6472 if (DC->isFileContext())
6476 if (isa<RequiresExprBodyDecl>(DC))
6478 llvm_unreachable("Unexpected context");
6481 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6482 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6483 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6484 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6488 llvm_unreachable("Unexpected context");
6491 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6492 ParsedAttr::Kind Kind) {
6493 // Check decl attributes on the DeclSpec.
6494 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6497 // Walk the declarator structure, checking decl attributes that were in a type
6498 // position to the decl itself.
6499 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6500 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6504 // Finally, check attributes on the decl itself.
6505 return PD.getAttributes().hasAttribute(Kind);
6508 /// Adjust the \c DeclContext for a function or variable that might be a
6509 /// function-local external declaration.
6510 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6511 if (!DC->isFunctionOrMethod())
6514 // If this is a local extern function or variable declared within a function
6515 // template, don't add it into the enclosing namespace scope until it is
6516 // instantiated; it might have a dependent type right now.
6517 if (DC->isDependentContext())
6520 // C++11 [basic.link]p7:
6521 // When a block scope declaration of an entity with linkage is not found to
6522 // refer to some other declaration, then that entity is a member of the
6523 // innermost enclosing namespace.
6525 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6526 // semantically-enclosing namespace, not a lexically-enclosing one.
6527 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6528 DC = DC->getParent();
6532 /// Returns true if given declaration has external C language linkage.
6533 static bool isDeclExternC(const Decl *D) {
6534 if (const auto *FD = dyn_cast<FunctionDecl>(D))
6535 return FD->isExternC();
6536 if (const auto *VD = dyn_cast<VarDecl>(D))
6537 return VD->isExternC();
6539 llvm_unreachable("Unknown type of decl!");
6541 /// Returns true if there hasn't been any invalid type diagnosed.
6542 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6543 DeclContext *DC, QualType R) {
6544 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6545 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6547 if (R->isImageType() || R->isPipeType()) {
6548 Se.Diag(D.getIdentifierLoc(),
6549 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6555 // OpenCL v1.2 s6.9.r:
6556 // The event type cannot be used to declare a program scope variable.
6557 // OpenCL v2.0 s6.9.q:
6558 // The clk_event_t and reserve_id_t types cannot be declared in program
6560 if (NULL == S->getParent()) {
6561 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6562 Se.Diag(D.getIdentifierLoc(),
6563 diag::err_invalid_type_for_program_scope_var)
6570 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6572 while (NR->isPointerType()) {
6573 if (NR->isFunctionPointerType()) {
6574 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6578 NR = NR->getPointeeType();
6581 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6582 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6583 // half array type (unless the cl_khr_fp16 extension is enabled).
6584 if (Se.Context.getBaseElementType(R)->isHalfType()) {
6585 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6591 // OpenCL v1.2 s6.9.r:
6592 // The event type cannot be used with the __local, __constant and __global
6593 // address space qualifiers.
6594 if (R->isEventT()) {
6595 if (R.getAddressSpace() != LangAS::opencl_private) {
6596 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6602 // C++ for OpenCL does not allow the thread_local storage qualifier.
6603 // OpenCL C does not support thread_local either, and
6604 // also reject all other thread storage class specifiers.
6605 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6606 if (TSC != TSCS_unspecified) {
6607 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6608 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6609 diag::err_opencl_unknown_type_specifier)
6610 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6611 << DeclSpec::getSpecifierName(TSC) << 1;
6616 if (R->isSamplerT()) {
6617 // OpenCL v1.2 s6.9.b p4:
6618 // The sampler type cannot be used with the __local and __global address
6619 // space qualifiers.
6620 if (R.getAddressSpace() == LangAS::opencl_local ||
6621 R.getAddressSpace() == LangAS::opencl_global) {
6622 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6626 // OpenCL v1.2 s6.12.14.1:
6627 // A global sampler must be declared with either the constant address
6628 // space qualifier or with the const qualifier.
6629 if (DC->isTranslationUnit() &&
6630 !(R.getAddressSpace() == LangAS::opencl_constant ||
6631 R.isConstQualified())) {
6632 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6635 if (D.isInvalidType())
6641 NamedDecl *Sema::ActOnVariableDeclarator(
6642 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6643 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6644 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6645 QualType R = TInfo->getType();
6646 DeclarationName Name = GetNameForDeclarator(D).getName();
6648 IdentifierInfo *II = Name.getAsIdentifierInfo();
6650 if (D.isDecompositionDeclarator()) {
6651 // Take the name of the first declarator as our name for diagnostic
6653 auto &Decomp = D.getDecompositionDeclarator();
6654 if (!Decomp.bindings().empty()) {
6655 II = Decomp.bindings()[0].Name;
6659 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6664 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6665 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6667 // dllimport globals without explicit storage class are treated as extern. We
6668 // have to change the storage class this early to get the right DeclContext.
6669 if (SC == SC_None && !DC->isRecord() &&
6670 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6671 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6674 DeclContext *OriginalDC = DC;
6675 bool IsLocalExternDecl = SC == SC_Extern &&
6676 adjustContextForLocalExternDecl(DC);
6678 if (SCSpec == DeclSpec::SCS_mutable) {
6679 // mutable can only appear on non-static class members, so it's always
6681 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6686 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6687 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6688 D.getDeclSpec().getStorageClassSpecLoc())) {
6689 // In C++11, the 'register' storage class specifier is deprecated.
6690 // Suppress the warning in system macros, it's used in macros in some
6691 // popular C system headers, such as in glibc's htonl() macro.
6692 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6693 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6694 : diag::warn_deprecated_register)
6695 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6698 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6700 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6701 // C99 6.9p2: The storage-class specifiers auto and register shall not
6702 // appear in the declaration specifiers in an external declaration.
6703 // Global Register+Asm is a GNU extension we support.
6704 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6705 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6710 bool IsMemberSpecialization = false;
6711 bool IsVariableTemplateSpecialization = false;
6712 bool IsPartialSpecialization = false;
6713 bool IsVariableTemplate = false;
6714 VarDecl *NewVD = nullptr;
6715 VarTemplateDecl *NewTemplate = nullptr;
6716 TemplateParameterList *TemplateParams = nullptr;
6717 if (!getLangOpts().CPlusPlus) {
6718 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6721 if (R->getContainedDeducedType())
6722 ParsingInitForAutoVars.insert(NewVD);
6724 if (D.isInvalidType())
6725 NewVD->setInvalidDecl();
6727 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6728 NewVD->hasLocalStorage())
6729 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6730 NTCUC_AutoVar, NTCUK_Destruct);
6732 bool Invalid = false;
6734 if (DC->isRecord() && !CurContext->isRecord()) {
6735 // This is an out-of-line definition of a static data member.
6740 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6741 diag::err_static_out_of_line)
6742 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6747 // [dcl.stc] p2: The auto or register specifiers shall be applied only
6748 // to names of variables declared in a block or to function parameters.
6749 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6752 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6753 diag::err_storage_class_for_static_member)
6754 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6756 case SC_PrivateExtern:
6757 llvm_unreachable("C storage class in c++!");
6761 if (SC == SC_Static && CurContext->isRecord()) {
6762 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6763 if (RD->isLocalClass())
6764 Diag(D.getIdentifierLoc(),
6765 diag::err_static_data_member_not_allowed_in_local_class)
6766 << Name << RD->getDeclName();
6768 // C++98 [class.union]p1: If a union contains a static data member,
6769 // the program is ill-formed. C++11 drops this restriction.
6771 Diag(D.getIdentifierLoc(),
6772 getLangOpts().CPlusPlus11
6773 ? diag::warn_cxx98_compat_static_data_member_in_union
6774 : diag::ext_static_data_member_in_union) << Name;
6775 // We conservatively disallow static data members in anonymous structs.
6776 else if (!RD->getDeclName())
6777 Diag(D.getIdentifierLoc(),
6778 diag::err_static_data_member_not_allowed_in_anon_struct)
6779 << Name << RD->isUnion();
6783 // Match up the template parameter lists with the scope specifier, then
6784 // determine whether we have a template or a template specialization.
6785 TemplateParams = MatchTemplateParametersToScopeSpecifier(
6786 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6787 D.getCXXScopeSpec(),
6788 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6789 ? D.getName().TemplateId
6792 /*never a friend*/ false, IsMemberSpecialization, Invalid);
6794 if (TemplateParams) {
6795 if (!TemplateParams->size() &&
6796 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6797 // There is an extraneous 'template<>' for this variable. Complain
6798 // about it, but allow the declaration of the variable.
6799 Diag(TemplateParams->getTemplateLoc(),
6800 diag::err_template_variable_noparams)
6802 << SourceRange(TemplateParams->getTemplateLoc(),
6803 TemplateParams->getRAngleLoc());
6804 TemplateParams = nullptr;
6806 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6807 // This is an explicit specialization or a partial specialization.
6808 // FIXME: Check that we can declare a specialization here.
6809 IsVariableTemplateSpecialization = true;
6810 IsPartialSpecialization = TemplateParams->size() > 0;
6811 } else { // if (TemplateParams->size() > 0)
6812 // This is a template declaration.
6813 IsVariableTemplate = true;
6815 // Check that we can declare a template here.
6816 if (CheckTemplateDeclScope(S, TemplateParams))
6819 // Only C++1y supports variable templates (N3651).
6820 Diag(D.getIdentifierLoc(),
6821 getLangOpts().CPlusPlus14
6822 ? diag::warn_cxx11_compat_variable_template
6823 : diag::ext_variable_template);
6828 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6829 "should have a 'template<>' for this decl");
6832 if (IsVariableTemplateSpecialization) {
6833 SourceLocation TemplateKWLoc =
6834 TemplateParamLists.size() > 0
6835 ? TemplateParamLists[0]->getTemplateLoc()
6837 DeclResult Res = ActOnVarTemplateSpecialization(
6838 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6839 IsPartialSpecialization);
6840 if (Res.isInvalid())
6842 NewVD = cast<VarDecl>(Res.get());
6844 } else if (D.isDecompositionDeclarator()) {
6845 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6846 D.getIdentifierLoc(), R, TInfo, SC,
6849 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6850 D.getIdentifierLoc(), II, R, TInfo, SC);
6852 // If this is supposed to be a variable template, create it as such.
6853 if (IsVariableTemplate) {
6855 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6856 TemplateParams, NewVD);
6857 NewVD->setDescribedVarTemplate(NewTemplate);
6860 // If this decl has an auto type in need of deduction, make a note of the
6861 // Decl so we can diagnose uses of it in its own initializer.
6862 if (R->getContainedDeducedType())
6863 ParsingInitForAutoVars.insert(NewVD);
6865 if (D.isInvalidType() || Invalid) {
6866 NewVD->setInvalidDecl();
6868 NewTemplate->setInvalidDecl();
6871 SetNestedNameSpecifier(*this, NewVD, D);
6873 // If we have any template parameter lists that don't directly belong to
6874 // the variable (matching the scope specifier), store them.
6875 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6876 if (TemplateParamLists.size() > VDTemplateParamLists)
6877 NewVD->setTemplateParameterListsInfo(
6878 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6881 if (D.getDeclSpec().isInlineSpecified()) {
6882 if (!getLangOpts().CPlusPlus) {
6883 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6885 } else if (CurContext->isFunctionOrMethod()) {
6886 // 'inline' is not allowed on block scope variable declaration.
6887 Diag(D.getDeclSpec().getInlineSpecLoc(),
6888 diag::err_inline_declaration_block_scope) << Name
6889 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6891 Diag(D.getDeclSpec().getInlineSpecLoc(),
6892 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6893 : diag::ext_inline_variable);
6894 NewVD->setInlineSpecified();
6898 // Set the lexical context. If the declarator has a C++ scope specifier, the
6899 // lexical context will be different from the semantic context.
6900 NewVD->setLexicalDeclContext(CurContext);
6902 NewTemplate->setLexicalDeclContext(CurContext);
6904 if (IsLocalExternDecl) {
6905 if (D.isDecompositionDeclarator())
6906 for (auto *B : Bindings)
6907 B->setLocalExternDecl();
6909 NewVD->setLocalExternDecl();
6912 bool EmitTLSUnsupportedError = false;
6913 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6914 // C++11 [dcl.stc]p4:
6915 // When thread_local is applied to a variable of block scope the
6916 // storage-class-specifier static is implied if it does not appear
6918 // Core issue: 'static' is not implied if the variable is declared
6920 if (NewVD->hasLocalStorage() &&
6921 (SCSpec != DeclSpec::SCS_unspecified ||
6922 TSCS != DeclSpec::TSCS_thread_local ||
6923 !DC->isFunctionOrMethod()))
6924 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6925 diag::err_thread_non_global)
6926 << DeclSpec::getSpecifierName(TSCS);
6927 else if (!Context.getTargetInfo().isTLSSupported()) {
6928 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6929 // Postpone error emission until we've collected attributes required to
6930 // figure out whether it's a host or device variable and whether the
6931 // error should be ignored.
6932 EmitTLSUnsupportedError = true;
6933 // We still need to mark the variable as TLS so it shows up in AST with
6934 // proper storage class for other tools to use even if we're not going
6935 // to emit any code for it.
6936 NewVD->setTSCSpec(TSCS);
6938 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6939 diag::err_thread_unsupported);
6941 NewVD->setTSCSpec(TSCS);
6944 switch (D.getDeclSpec().getConstexprSpecifier()) {
6945 case CSK_unspecified:
6949 Diag(D.getDeclSpec().getConstexprSpecLoc(),
6950 diag::err_constexpr_wrong_decl_kind)
6951 << D.getDeclSpec().getConstexprSpecifier();
6955 NewVD->setConstexpr(true);
6956 // C++1z [dcl.spec.constexpr]p1:
6957 // A static data member declared with the constexpr specifier is
6958 // implicitly an inline variable.
6959 if (NewVD->isStaticDataMember() &&
6960 (getLangOpts().CPlusPlus17 ||
6961 Context.getTargetInfo().getCXXABI().isMicrosoft()))
6962 NewVD->setImplicitlyInline();
6966 if (!NewVD->hasGlobalStorage())
6967 Diag(D.getDeclSpec().getConstexprSpecLoc(),
6968 diag::err_constinit_local_variable);
6970 NewVD->addAttr(ConstInitAttr::Create(
6971 Context, D.getDeclSpec().getConstexprSpecLoc(),
6972 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
6977 // An inline definition of a function with external linkage shall
6978 // not contain a definition of a modifiable object with static or
6979 // thread storage duration...
6980 // We only apply this when the function is required to be defined
6981 // elsewhere, i.e. when the function is not 'extern inline'. Note
6982 // that a local variable with thread storage duration still has to
6983 // be marked 'static'. Also note that it's possible to get these
6984 // semantics in C++ using __attribute__((gnu_inline)).
6985 if (SC == SC_Static && S->getFnParent() != nullptr &&
6986 !NewVD->getType().isConstQualified()) {
6987 FunctionDecl *CurFD = getCurFunctionDecl();
6988 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6989 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6990 diag::warn_static_local_in_extern_inline);
6991 MaybeSuggestAddingStaticToDecl(CurFD);
6995 if (D.getDeclSpec().isModulePrivateSpecified()) {
6996 if (IsVariableTemplateSpecialization)
6997 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6998 << (IsPartialSpecialization ? 1 : 0)
6999 << FixItHint::CreateRemoval(
7000 D.getDeclSpec().getModulePrivateSpecLoc());
7001 else if (IsMemberSpecialization)
7002 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7004 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7005 else if (NewVD->hasLocalStorage())
7006 Diag(NewVD->getLocation(), diag::err_module_private_local)
7007 << 0 << NewVD->getDeclName()
7008 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7009 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7011 NewVD->setModulePrivate();
7013 NewTemplate->setModulePrivate();
7014 for (auto *B : Bindings)
7015 B->setModulePrivate();
7019 if (getLangOpts().OpenCL) {
7021 deduceOpenCLAddressSpace(NewVD);
7023 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7026 // Handle attributes prior to checking for duplicates in MergeVarDecl
7027 ProcessDeclAttributes(S, NewVD, D);
7029 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
7030 if (EmitTLSUnsupportedError &&
7031 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7032 (getLangOpts().OpenMPIsDevice &&
7033 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7034 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7035 diag::err_thread_unsupported);
7036 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7037 // storage [duration]."
7038 if (SC == SC_None && S->getFnParent() != nullptr &&
7039 (NewVD->hasAttr<CUDASharedAttr>() ||
7040 NewVD->hasAttr<CUDAConstantAttr>())) {
7041 NewVD->setStorageClass(SC_Static);
7045 // Ensure that dllimport globals without explicit storage class are treated as
7046 // extern. The storage class is set above using parsed attributes. Now we can
7047 // check the VarDecl itself.
7048 assert(!NewVD->hasAttr<DLLImportAttr>() ||
7049 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7050 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7052 // In auto-retain/release, infer strong retension for variables of
7054 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7055 NewVD->setInvalidDecl();
7057 // Handle GNU asm-label extension (encoded as an attribute).
7058 if (Expr *E = (Expr*)D.getAsmLabel()) {
7059 // The parser guarantees this is a string.
7060 StringLiteral *SE = cast<StringLiteral>(E);
7061 StringRef Label = SE->getString();
7062 if (S->getFnParent() != nullptr) {
7066 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7069 // Local Named register
7070 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7071 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7072 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7076 case SC_PrivateExtern:
7079 } else if (SC == SC_Register) {
7080 // Global Named register
7081 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7082 const auto &TI = Context.getTargetInfo();
7083 bool HasSizeMismatch;
7085 if (!TI.isValidGCCRegisterName(Label))
7086 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7087 else if (!TI.validateGlobalRegisterVariable(Label,
7088 Context.getTypeSize(R),
7090 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7091 else if (HasSizeMismatch)
7092 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7095 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7096 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7097 NewVD->setInvalidDecl(true);
7101 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7102 /*IsLiteralLabel=*/true,
7103 SE->getStrTokenLoc(0)));
7104 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7105 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7106 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7107 if (I != ExtnameUndeclaredIdentifiers.end()) {
7108 if (isDeclExternC(NewVD)) {
7109 NewVD->addAttr(I->second);
7110 ExtnameUndeclaredIdentifiers.erase(I);
7112 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7113 << /*Variable*/1 << NewVD;
7117 // Find the shadowed declaration before filtering for scope.
7118 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7119 ? getShadowedDeclaration(NewVD, Previous)
7122 // Don't consider existing declarations that are in a different
7123 // scope and are out-of-semantic-context declarations (if the new
7124 // declaration has linkage).
7125 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7126 D.getCXXScopeSpec().isNotEmpty() ||
7127 IsMemberSpecialization ||
7128 IsVariableTemplateSpecialization);
7130 // Check whether the previous declaration is in the same block scope. This
7131 // affects whether we merge types with it, per C++11 [dcl.array]p3.
7132 if (getLangOpts().CPlusPlus &&
7133 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7134 NewVD->setPreviousDeclInSameBlockScope(
7135 Previous.isSingleResult() && !Previous.isShadowed() &&
7136 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7138 if (!getLangOpts().CPlusPlus) {
7139 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7141 // If this is an explicit specialization of a static data member, check it.
7142 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7143 CheckMemberSpecialization(NewVD, Previous))
7144 NewVD->setInvalidDecl();
7146 // Merge the decl with the existing one if appropriate.
7147 if (!Previous.empty()) {
7148 if (Previous.isSingleResult() &&
7149 isa<FieldDecl>(Previous.getFoundDecl()) &&
7150 D.getCXXScopeSpec().isSet()) {
7151 // The user tried to define a non-static data member
7152 // out-of-line (C++ [dcl.meaning]p1).
7153 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7154 << D.getCXXScopeSpec().getRange();
7156 NewVD->setInvalidDecl();
7158 } else if (D.getCXXScopeSpec().isSet()) {
7159 // No previous declaration in the qualifying scope.
7160 Diag(D.getIdentifierLoc(), diag::err_no_member)
7161 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7162 << D.getCXXScopeSpec().getRange();
7163 NewVD->setInvalidDecl();
7166 if (!IsVariableTemplateSpecialization)
7167 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7170 VarTemplateDecl *PrevVarTemplate =
7171 NewVD->getPreviousDecl()
7172 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7175 // Check the template parameter list of this declaration, possibly
7176 // merging in the template parameter list from the previous variable
7177 // template declaration.
7178 if (CheckTemplateParameterList(
7180 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7182 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7183 DC->isDependentContext())
7184 ? TPC_ClassTemplateMember
7186 NewVD->setInvalidDecl();
7188 // If we are providing an explicit specialization of a static variable
7189 // template, make a note of that.
7190 if (PrevVarTemplate &&
7191 PrevVarTemplate->getInstantiatedFromMemberTemplate())
7192 PrevVarTemplate->setMemberSpecialization();
7196 // Diagnose shadowed variables iff this isn't a redeclaration.
7197 if (ShadowedDecl && !D.isRedeclaration())
7198 CheckShadow(NewVD, ShadowedDecl, Previous);
7200 ProcessPragmaWeak(S, NewVD);
7202 // If this is the first declaration of an extern C variable, update
7203 // the map of such variables.
7204 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7205 isIncompleteDeclExternC(*this, NewVD))
7206 RegisterLocallyScopedExternCDecl(NewVD, S);
7208 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7209 MangleNumberingContext *MCtx;
7210 Decl *ManglingContextDecl;
7211 std::tie(MCtx, ManglingContextDecl) =
7212 getCurrentMangleNumberContext(NewVD->getDeclContext());
7214 Context.setManglingNumber(
7215 NewVD, MCtx->getManglingNumber(
7216 NewVD, getMSManglingNumber(getLangOpts(), S)));
7217 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7221 // Special handling of variable named 'main'.
7222 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7223 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7224 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7226 // C++ [basic.start.main]p3
7227 // A program that declares a variable main at global scope is ill-formed.
7228 if (getLangOpts().CPlusPlus)
7229 Diag(D.getBeginLoc(), diag::err_main_global_variable);
7231 // In C, and external-linkage variable named main results in undefined
7233 else if (NewVD->hasExternalFormalLinkage())
7234 Diag(D.getBeginLoc(), diag::warn_main_redefined);
7237 if (D.isRedeclaration() && !Previous.empty()) {
7238 NamedDecl *Prev = Previous.getRepresentativeDecl();
7239 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7240 D.isFunctionDefinition());
7244 if (NewVD->isInvalidDecl())
7245 NewTemplate->setInvalidDecl();
7246 ActOnDocumentableDecl(NewTemplate);
7250 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7251 CompleteMemberSpecialization(NewVD, Previous);
7256 /// Enum describing the %select options in diag::warn_decl_shadow.
7257 enum ShadowedDeclKind {
7266 /// Determine what kind of declaration we're shadowing.
7267 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7268 const DeclContext *OldDC) {
7269 if (isa<TypeAliasDecl>(ShadowedDecl))
7271 else if (isa<TypedefDecl>(ShadowedDecl))
7273 else if (isa<RecordDecl>(OldDC))
7274 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7276 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7279 /// Return the location of the capture if the given lambda captures the given
7280 /// variable \p VD, or an invalid source location otherwise.
7281 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7282 const VarDecl *VD) {
7283 for (const Capture &Capture : LSI->Captures) {
7284 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7285 return Capture.getLocation();
7287 return SourceLocation();
7290 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7291 const LookupResult &R) {
7292 // Only diagnose if we're shadowing an unambiguous field or variable.
7293 if (R.getResultKind() != LookupResult::Found)
7296 // Return false if warning is ignored.
7297 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7300 /// Return the declaration shadowed by the given variable \p D, or null
7301 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7302 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7303 const LookupResult &R) {
7304 if (!shouldWarnIfShadowedDecl(Diags, R))
7307 // Don't diagnose declarations at file scope.
7308 if (D->hasGlobalStorage())
7311 NamedDecl *ShadowedDecl = R.getFoundDecl();
7312 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7317 /// Return the declaration shadowed by the given typedef \p D, or null
7318 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7319 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7320 const LookupResult &R) {
7321 // Don't warn if typedef declaration is part of a class
7322 if (D->getDeclContext()->isRecord())
7325 if (!shouldWarnIfShadowedDecl(Diags, R))
7328 NamedDecl *ShadowedDecl = R.getFoundDecl();
7329 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7332 /// Diagnose variable or built-in function shadowing. Implements
7335 /// This method is called whenever a VarDecl is added to a "useful"
7338 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7339 /// \param R the lookup of the name
7341 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7342 const LookupResult &R) {
7343 DeclContext *NewDC = D->getDeclContext();
7345 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7346 // Fields are not shadowed by variables in C++ static methods.
7347 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7351 // Fields shadowed by constructor parameters are a special case. Usually
7352 // the constructor initializes the field with the parameter.
7353 if (isa<CXXConstructorDecl>(NewDC))
7354 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7355 // Remember that this was shadowed so we can either warn about its
7356 // modification or its existence depending on warning settings.
7357 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7362 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7363 if (shadowedVar->isExternC()) {
7364 // For shadowing external vars, make sure that we point to the global
7365 // declaration, not a locally scoped extern declaration.
7366 for (auto I : shadowedVar->redecls())
7367 if (I->isFileVarDecl()) {
7373 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7375 unsigned WarningDiag = diag::warn_decl_shadow;
7376 SourceLocation CaptureLoc;
7377 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7378 isa<CXXMethodDecl>(NewDC)) {
7379 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7380 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7381 if (RD->getLambdaCaptureDefault() == LCD_None) {
7382 // Try to avoid warnings for lambdas with an explicit capture list.
7383 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7384 // Warn only when the lambda captures the shadowed decl explicitly.
7385 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7386 if (CaptureLoc.isInvalid())
7387 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7389 // Remember that this was shadowed so we can avoid the warning if the
7390 // shadowed decl isn't captured and the warning settings allow it.
7391 cast<LambdaScopeInfo>(getCurFunction())
7392 ->ShadowingDecls.push_back(
7393 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7398 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7399 // A variable can't shadow a local variable in an enclosing scope, if
7400 // they are separated by a non-capturing declaration context.
7401 for (DeclContext *ParentDC = NewDC;
7402 ParentDC && !ParentDC->Equals(OldDC);
7403 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7404 // Only block literals, captured statements, and lambda expressions
7405 // can capture; other scopes don't.
7406 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7407 !isLambdaCallOperator(ParentDC)) {
7415 // Only warn about certain kinds of shadowing for class members.
7416 if (NewDC && NewDC->isRecord()) {
7417 // In particular, don't warn about shadowing non-class members.
7418 if (!OldDC->isRecord())
7421 // TODO: should we warn about static data members shadowing
7422 // static data members from base classes?
7424 // TODO: don't diagnose for inaccessible shadowed members.
7425 // This is hard to do perfectly because we might friend the
7426 // shadowing context, but that's just a false negative.
7430 DeclarationName Name = R.getLookupName();
7432 // Emit warning and note.
7433 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7435 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7436 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7437 if (!CaptureLoc.isInvalid())
7438 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7439 << Name << /*explicitly*/ 1;
7440 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7443 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7444 /// when these variables are captured by the lambda.
7445 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7446 for (const auto &Shadow : LSI->ShadowingDecls) {
7447 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7448 // Try to avoid the warning when the shadowed decl isn't captured.
7449 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7450 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7451 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7452 ? diag::warn_decl_shadow_uncaptured_local
7453 : diag::warn_decl_shadow)
7454 << Shadow.VD->getDeclName()
7455 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7456 if (!CaptureLoc.isInvalid())
7457 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7458 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7459 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7463 /// Check -Wshadow without the advantage of a previous lookup.
7464 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7465 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7468 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7469 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7471 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7472 CheckShadow(D, ShadowedDecl, R);
7475 /// Check if 'E', which is an expression that is about to be modified, refers
7476 /// to a constructor parameter that shadows a field.
7477 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7478 // Quickly ignore expressions that can't be shadowing ctor parameters.
7479 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7481 E = E->IgnoreParenImpCasts();
7482 auto *DRE = dyn_cast<DeclRefExpr>(E);
7485 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7486 auto I = ShadowingDecls.find(D);
7487 if (I == ShadowingDecls.end())
7489 const NamedDecl *ShadowedDecl = I->second;
7490 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7491 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7492 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7493 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7495 // Avoid issuing multiple warnings about the same decl.
7496 ShadowingDecls.erase(I);
7499 /// Check for conflict between this global or extern "C" declaration and
7500 /// previous global or extern "C" declarations. This is only used in C++.
7501 template<typename T>
7502 static bool checkGlobalOrExternCConflict(
7503 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7504 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7505 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7507 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7508 // The common case: this global doesn't conflict with any extern "C"
7514 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7515 // Both the old and new declarations have C language linkage. This is a
7518 Previous.addDecl(Prev);
7522 // This is a global, non-extern "C" declaration, and there is a previous
7523 // non-global extern "C" declaration. Diagnose if this is a variable
7525 if (!isa<VarDecl>(ND))
7528 // The declaration is extern "C". Check for any declaration in the
7529 // translation unit which might conflict.
7531 // We have already performed the lookup into the translation unit.
7533 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7535 if (isa<VarDecl>(*I)) {
7541 DeclContext::lookup_result R =
7542 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7543 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7545 if (isa<VarDecl>(*I)) {
7549 // FIXME: If we have any other entity with this name in global scope,
7550 // the declaration is ill-formed, but that is a defect: it breaks the
7551 // 'stat' hack, for instance. Only variables can have mangled name
7552 // clashes with extern "C" declarations, so only they deserve a
7561 // Use the first declaration's location to ensure we point at something which
7562 // is lexically inside an extern "C" linkage-spec.
7563 assert(Prev && "should have found a previous declaration to diagnose");
7564 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7565 Prev = FD->getFirstDecl();
7567 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7569 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7571 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7576 /// Apply special rules for handling extern "C" declarations. Returns \c true
7577 /// if we have found that this is a redeclaration of some prior entity.
7579 /// Per C++ [dcl.link]p6:
7580 /// Two declarations [for a function or variable] with C language linkage
7581 /// with the same name that appear in different scopes refer to the same
7582 /// [entity]. An entity with C language linkage shall not be declared with
7583 /// the same name as an entity in global scope.
7584 template<typename T>
7585 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7586 LookupResult &Previous) {
7587 if (!S.getLangOpts().CPlusPlus) {
7588 // In C, when declaring a global variable, look for a corresponding 'extern'
7589 // variable declared in function scope. We don't need this in C++, because
7590 // we find local extern decls in the surrounding file-scope DeclContext.
7591 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7592 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7594 Previous.addDecl(Prev);
7601 // A declaration in the translation unit can conflict with an extern "C"
7603 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7604 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7606 // An extern "C" declaration can conflict with a declaration in the
7607 // translation unit or can be a redeclaration of an extern "C" declaration
7608 // in another scope.
7609 if (isIncompleteDeclExternC(S,ND))
7610 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7612 // Neither global nor extern "C": nothing to do.
7616 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7617 // If the decl is already known invalid, don't check it.
7618 if (NewVD->isInvalidDecl())
7621 QualType T = NewVD->getType();
7623 // Defer checking an 'auto' type until its initializer is attached.
7624 if (T->isUndeducedType())
7627 if (NewVD->hasAttrs())
7628 CheckAlignasUnderalignment(NewVD);
7630 if (T->isObjCObjectType()) {
7631 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7632 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7633 T = Context.getObjCObjectPointerType(T);
7637 // Emit an error if an address space was applied to decl with local storage.
7638 // This includes arrays of objects with address space qualifiers, but not
7639 // automatic variables that point to other address spaces.
7640 // ISO/IEC TR 18037 S5.1.2
7641 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7642 T.getAddressSpace() != LangAS::Default) {
7643 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7644 NewVD->setInvalidDecl();
7648 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7650 if (getLangOpts().OpenCLVersion == 120 &&
7651 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7652 NewVD->isStaticLocal()) {
7653 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7654 NewVD->setInvalidDecl();
7658 if (getLangOpts().OpenCL) {
7659 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7660 if (NewVD->hasAttr<BlocksAttr>()) {
7661 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7665 if (T->isBlockPointerType()) {
7666 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7667 // can't use 'extern' storage class.
7668 if (!T.isConstQualified()) {
7669 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7671 NewVD->setInvalidDecl();
7674 if (NewVD->hasExternalStorage()) {
7675 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7676 NewVD->setInvalidDecl();
7680 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7681 // __constant address space.
7682 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7683 // variables inside a function can also be declared in the global
7685 // C++ for OpenCL inherits rule from OpenCL C v2.0.
7686 // FIXME: Adding local AS in C++ for OpenCL might make sense.
7687 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7688 NewVD->hasExternalStorage()) {
7689 if (!T->isSamplerT() &&
7690 !(T.getAddressSpace() == LangAS::opencl_constant ||
7691 (T.getAddressSpace() == LangAS::opencl_global &&
7692 (getLangOpts().OpenCLVersion == 200 ||
7693 getLangOpts().OpenCLCPlusPlus)))) {
7694 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7695 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7696 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7697 << Scope << "global or constant";
7699 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7700 << Scope << "constant";
7701 NewVD->setInvalidDecl();
7705 if (T.getAddressSpace() == LangAS::opencl_global) {
7706 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7707 << 1 /*is any function*/ << "global";
7708 NewVD->setInvalidDecl();
7711 if (T.getAddressSpace() == LangAS::opencl_constant ||
7712 T.getAddressSpace() == LangAS::opencl_local) {
7713 FunctionDecl *FD = getCurFunctionDecl();
7714 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7716 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7717 if (T.getAddressSpace() == LangAS::opencl_constant)
7718 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7719 << 0 /*non-kernel only*/ << "constant";
7721 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7722 << 0 /*non-kernel only*/ << "local";
7723 NewVD->setInvalidDecl();
7726 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7727 // in the outermost scope of a kernel function.
7728 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7729 if (!getCurScope()->isFunctionScope()) {
7730 if (T.getAddressSpace() == LangAS::opencl_constant)
7731 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7734 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7736 NewVD->setInvalidDecl();
7740 } else if (T.getAddressSpace() != LangAS::opencl_private &&
7741 // If we are parsing a template we didn't deduce an addr
7743 T.getAddressSpace() != LangAS::Default) {
7744 // Do not allow other address spaces on automatic variable.
7745 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7746 NewVD->setInvalidDecl();
7752 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7753 && !NewVD->hasAttr<BlocksAttr>()) {
7754 if (getLangOpts().getGC() != LangOptions::NonGC)
7755 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7757 assert(!getLangOpts().ObjCAutoRefCount);
7758 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7762 bool isVM = T->isVariablyModifiedType();
7763 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7764 NewVD->hasAttr<BlocksAttr>())
7765 setFunctionHasBranchProtectedScope();
7767 if ((isVM && NewVD->hasLinkage()) ||
7768 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7769 bool SizeIsNegative;
7770 llvm::APSInt Oversized;
7771 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7772 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7774 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
7775 FixedT = FixedTInfo->getType();
7776 else if (FixedTInfo) {
7777 // Type and type-as-written are canonically different. We need to fix up
7778 // both types separately.
7779 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7782 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7783 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7784 // FIXME: This won't give the correct result for
7786 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7788 if (NewVD->isFileVarDecl())
7789 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7791 else if (NewVD->isStaticLocal())
7792 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7795 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7797 NewVD->setInvalidDecl();
7802 if (NewVD->isFileVarDecl())
7803 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7805 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7806 NewVD->setInvalidDecl();
7810 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7811 NewVD->setType(FixedT);
7812 NewVD->setTypeSourceInfo(FixedTInfo);
7815 if (T->isVoidType()) {
7816 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7817 // of objects and functions.
7818 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7819 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7821 NewVD->setInvalidDecl();
7826 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7827 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7828 NewVD->setInvalidDecl();
7832 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7833 Diag(NewVD->getLocation(), diag::err_block_on_vm);
7834 NewVD->setInvalidDecl();
7838 if (NewVD->isConstexpr() && !T->isDependentType() &&
7839 RequireLiteralType(NewVD->getLocation(), T,
7840 diag::err_constexpr_var_non_literal)) {
7841 NewVD->setInvalidDecl();
7846 /// Perform semantic checking on a newly-created variable
7849 /// This routine performs all of the type-checking required for a
7850 /// variable declaration once it has been built. It is used both to
7851 /// check variables after they have been parsed and their declarators
7852 /// have been translated into a declaration, and to check variables
7853 /// that have been instantiated from a template.
7855 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7857 /// Returns true if the variable declaration is a redeclaration.
7858 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7859 CheckVariableDeclarationType(NewVD);
7861 // If the decl is already known invalid, don't check it.
7862 if (NewVD->isInvalidDecl())
7865 // If we did not find anything by this name, look for a non-visible
7866 // extern "C" declaration with the same name.
7867 if (Previous.empty() &&
7868 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7869 Previous.setShadowed();
7871 if (!Previous.empty()) {
7872 MergeVarDecl(NewVD, Previous);
7879 struct FindOverriddenMethod {
7881 CXXMethodDecl *Method;
7883 /// Member lookup function that determines whether a given C++
7884 /// method overrides a method in a base class, to be used with
7885 /// CXXRecordDecl::lookupInBases().
7886 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7887 RecordDecl *BaseRecord =
7888 Specifier->getType()->castAs<RecordType>()->getDecl();
7890 DeclarationName Name = Method->getDeclName();
7892 // FIXME: Do we care about other names here too?
7893 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7894 // We really want to find the base class destructor here.
7895 QualType T = S->Context.getTypeDeclType(BaseRecord);
7896 CanQualType CT = S->Context.getCanonicalType(T);
7898 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7901 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7902 Path.Decls = Path.Decls.slice(1)) {
7903 NamedDecl *D = Path.Decls.front();
7904 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7905 if (MD->isVirtual() &&
7907 Method, MD, /*UseMemberUsingDeclRules=*/false,
7908 /*ConsiderCudaAttrs=*/true,
7909 // C++2a [class.virtual]p2 does not consider requires clauses
7911 /*ConsiderRequiresClauses=*/false))
7920 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7921 } // end anonymous namespace
7923 /// Report an error regarding overriding, along with any relevant
7924 /// overridden methods.
7926 /// \param DiagID the primary error to report.
7927 /// \param MD the overriding method.
7928 /// \param OEK which overrides to include as notes.
7929 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7930 OverrideErrorKind OEK = OEK_All) {
7931 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7932 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7933 // This check (& the OEK parameter) could be replaced by a predicate, but
7934 // without lambdas that would be overkill. This is still nicer than writing
7935 // out the diag loop 3 times.
7936 if ((OEK == OEK_All) ||
7937 (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7938 (OEK == OEK_Deleted && O->isDeleted()))
7939 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7943 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7944 /// and if so, check that it's a valid override and remember it.
7945 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7946 // Look for methods in base classes that this method might override.
7948 FindOverriddenMethod FOM;
7951 bool hasDeletedOverridenMethods = false;
7952 bool hasNonDeletedOverridenMethods = false;
7953 bool AddedAny = false;
7954 if (DC->lookupInBases(FOM, Paths)) {
7955 for (auto *I : Paths.found_decls()) {
7956 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7957 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7958 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7959 !CheckOverridingFunctionAttributes(MD, OldMD) &&
7960 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7961 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7962 hasDeletedOverridenMethods |= OldMD->isDeleted();
7963 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7970 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7971 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7973 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7974 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7981 // Struct for holding all of the extra arguments needed by
7982 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7983 struct ActOnFDArgs {
7986 MultiTemplateParamsArg TemplateParamLists;
7989 } // end anonymous namespace
7993 // Callback to only accept typo corrections that have a non-zero edit distance.
7994 // Also only accept corrections that have the same parent decl.
7995 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7997 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7998 CXXRecordDecl *Parent)
7999 : Context(Context), OriginalFD(TypoFD),
8000 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8002 bool ValidateCandidate(const TypoCorrection &candidate) override {
8003 if (candidate.getEditDistance() == 0)
8006 SmallVector<unsigned, 1> MismatchedParams;
8007 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8008 CDeclEnd = candidate.end();
8009 CDecl != CDeclEnd; ++CDecl) {
8010 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8012 if (FD && !FD->hasBody() &&
8013 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8014 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8015 CXXRecordDecl *Parent = MD->getParent();
8016 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8018 } else if (!ExpectedParent) {
8027 std::unique_ptr<CorrectionCandidateCallback> clone() override {
8028 return std::make_unique<DifferentNameValidatorCCC>(*this);
8032 ASTContext &Context;
8033 FunctionDecl *OriginalFD;
8034 CXXRecordDecl *ExpectedParent;
8037 } // end anonymous namespace
8039 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8040 TypoCorrectedFunctionDefinitions.insert(F);
8043 /// Generate diagnostics for an invalid function redeclaration.
8045 /// This routine handles generating the diagnostic messages for an invalid
8046 /// function redeclaration, including finding possible similar declarations
8047 /// or performing typo correction if there are no previous declarations with
8050 /// Returns a NamedDecl iff typo correction was performed and substituting in
8051 /// the new declaration name does not cause new errors.
8052 static NamedDecl *DiagnoseInvalidRedeclaration(
8053 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8054 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8055 DeclarationName Name = NewFD->getDeclName();
8056 DeclContext *NewDC = NewFD->getDeclContext();
8057 SmallVector<unsigned, 1> MismatchedParams;
8058 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8059 TypoCorrection Correction;
8060 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8062 IsLocalFriend ? diag::err_no_matching_local_friend :
8063 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8064 diag::err_member_decl_does_not_match;
8065 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8066 IsLocalFriend ? Sema::LookupLocalFriendName
8067 : Sema::LookupOrdinaryName,
8068 Sema::ForVisibleRedeclaration);
8070 NewFD->setInvalidDecl();
8072 SemaRef.LookupName(Prev, S);
8074 SemaRef.LookupQualifiedName(Prev, NewDC);
8075 assert(!Prev.isAmbiguous() &&
8076 "Cannot have an ambiguity in previous-declaration lookup");
8077 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8078 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8079 MD ? MD->getParent() : nullptr);
8080 if (!Prev.empty()) {
8081 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8082 Func != FuncEnd; ++Func) {
8083 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8085 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8086 // Add 1 to the index so that 0 can mean the mismatch didn't
8087 // involve a parameter
8089 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8090 NearMatches.push_back(std::make_pair(FD, ParamNum));
8093 // If the qualified name lookup yielded nothing, try typo correction
8094 } else if ((Correction = SemaRef.CorrectTypo(
8095 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8096 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8097 IsLocalFriend ? nullptr : NewDC))) {
8098 // Set up everything for the call to ActOnFunctionDeclarator
8099 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8100 ExtraArgs.D.getIdentifierLoc());
8102 Previous.setLookupName(Correction.getCorrection());
8103 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8104 CDeclEnd = Correction.end();
8105 CDecl != CDeclEnd; ++CDecl) {
8106 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8107 if (FD && !FD->hasBody() &&
8108 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8109 Previous.addDecl(FD);
8112 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8115 // Retry building the function declaration with the new previous
8116 // declarations, and with errors suppressed.
8119 Sema::SFINAETrap Trap(SemaRef);
8121 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8122 // pieces need to verify the typo-corrected C++ declaration and hopefully
8123 // eliminate the need for the parameter pack ExtraArgs.
8124 Result = SemaRef.ActOnFunctionDeclarator(
8125 ExtraArgs.S, ExtraArgs.D,
8126 Correction.getCorrectionDecl()->getDeclContext(),
8127 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8128 ExtraArgs.AddToScope);
8130 if (Trap.hasErrorOccurred())
8135 // Determine which correction we picked.
8136 Decl *Canonical = Result->getCanonicalDecl();
8137 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8139 if ((*I)->getCanonicalDecl() == Canonical)
8140 Correction.setCorrectionDecl(*I);
8142 // Let Sema know about the correction.
8143 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8144 SemaRef.diagnoseTypo(
8146 SemaRef.PDiag(IsLocalFriend
8147 ? diag::err_no_matching_local_friend_suggest
8148 : diag::err_member_decl_does_not_match_suggest)
8149 << Name << NewDC << IsDefinition);
8153 // Pretend the typo correction never occurred
8154 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8155 ExtraArgs.D.getIdentifierLoc());
8156 ExtraArgs.D.setRedeclaration(wasRedeclaration);
8158 Previous.setLookupName(Name);
8161 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8162 << Name << NewDC << IsDefinition << NewFD->getLocation();
8164 bool NewFDisConst = false;
8165 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8166 NewFDisConst = NewMD->isConst();
8168 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8169 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8170 NearMatch != NearMatchEnd; ++NearMatch) {
8171 FunctionDecl *FD = NearMatch->first;
8172 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8173 bool FDisConst = MD && MD->isConst();
8174 bool IsMember = MD || !IsLocalFriend;
8176 // FIXME: These notes are poorly worded for the local friend case.
8177 if (unsigned Idx = NearMatch->second) {
8178 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8179 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8180 if (Loc.isInvalid()) Loc = FD->getLocation();
8181 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8182 : diag::note_local_decl_close_param_match)
8183 << Idx << FDParam->getType()
8184 << NewFD->getParamDecl(Idx - 1)->getType();
8185 } else if (FDisConst != NewFDisConst) {
8186 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8187 << NewFDisConst << FD->getSourceRange().getEnd();
8189 SemaRef.Diag(FD->getLocation(),
8190 IsMember ? diag::note_member_def_close_match
8191 : diag::note_local_decl_close_match);
8196 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8197 switch (D.getDeclSpec().getStorageClassSpec()) {
8198 default: llvm_unreachable("Unknown storage class!");
8199 case DeclSpec::SCS_auto:
8200 case DeclSpec::SCS_register:
8201 case DeclSpec::SCS_mutable:
8202 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8203 diag::err_typecheck_sclass_func);
8204 D.getMutableDeclSpec().ClearStorageClassSpecs();
8207 case DeclSpec::SCS_unspecified: break;
8208 case DeclSpec::SCS_extern:
8209 if (D.getDeclSpec().isExternInLinkageSpec())
8212 case DeclSpec::SCS_static: {
8213 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8215 // The declaration of an identifier for a function that has
8216 // block scope shall have no explicit storage-class specifier
8217 // other than extern
8218 // See also (C++ [dcl.stc]p4).
8219 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8220 diag::err_static_block_func);
8225 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8228 // No explicit storage class has already been returned
8232 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8233 DeclContext *DC, QualType &R,
8234 TypeSourceInfo *TInfo,
8236 bool &IsVirtualOkay) {
8237 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8238 DeclarationName Name = NameInfo.getName();
8240 FunctionDecl *NewFD = nullptr;
8241 bool isInline = D.getDeclSpec().isInlineSpecified();
8243 if (!SemaRef.getLangOpts().CPlusPlus) {
8244 // Determine whether the function was written with a
8245 // prototype. This true when:
8246 // - there is a prototype in the declarator, or
8247 // - the type R of the function is some kind of typedef or other non-
8248 // attributed reference to a type name (which eventually refers to a
8251 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8252 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8254 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8255 R, TInfo, SC, isInline, HasPrototype,
8257 /*TrailingRequiresClause=*/nullptr);
8258 if (D.isInvalidType())
8259 NewFD->setInvalidDecl();
8264 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8266 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8267 if (ConstexprKind == CSK_constinit) {
8268 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8269 diag::err_constexpr_wrong_decl_kind)
8271 ConstexprKind = CSK_unspecified;
8272 D.getMutableDeclSpec().ClearConstexprSpec();
8274 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8276 // Check that the return type is not an abstract class type.
8277 // For record types, this is done by the AbstractClassUsageDiagnoser once
8278 // the class has been completely parsed.
8279 if (!DC->isRecord() &&
8280 SemaRef.RequireNonAbstractType(
8281 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8282 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8285 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8286 // This is a C++ constructor declaration.
8287 assert(DC->isRecord() &&
8288 "Constructors can only be declared in a member context");
8290 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8291 return CXXConstructorDecl::Create(
8292 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8293 TInfo, ExplicitSpecifier, isInline,
8294 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8295 TrailingRequiresClause);
8297 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8298 // This is a C++ destructor declaration.
8299 if (DC->isRecord()) {
8300 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8301 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8302 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8303 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8304 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8305 TrailingRequiresClause);
8307 // If the destructor needs an implicit exception specification, set it
8308 // now. FIXME: It'd be nice to be able to create the right type to start
8309 // with, but the type needs to reference the destructor declaration.
8310 if (SemaRef.getLangOpts().CPlusPlus11)
8311 SemaRef.AdjustDestructorExceptionSpec(NewDD);
8313 IsVirtualOkay = true;
8317 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8320 // Create a FunctionDecl to satisfy the function definition parsing
8322 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8323 D.getIdentifierLoc(), Name, R, TInfo, SC,
8325 /*hasPrototype=*/true, ConstexprKind,
8326 TrailingRequiresClause);
8329 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8330 if (!DC->isRecord()) {
8331 SemaRef.Diag(D.getIdentifierLoc(),
8332 diag::err_conv_function_not_member);
8336 SemaRef.CheckConversionDeclarator(D, R, SC);
8337 if (D.isInvalidType())
8340 IsVirtualOkay = true;
8341 return CXXConversionDecl::Create(
8342 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8343 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8344 TrailingRequiresClause);
8346 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8347 if (TrailingRequiresClause)
8348 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8349 diag::err_trailing_requires_clause_on_deduction_guide)
8350 << TrailingRequiresClause->getSourceRange();
8351 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8353 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8354 ExplicitSpecifier, NameInfo, R, TInfo,
8356 } else if (DC->isRecord()) {
8357 // If the name of the function is the same as the name of the record,
8358 // then this must be an invalid constructor that has a return type.
8359 // (The parser checks for a return type and makes the declarator a
8360 // constructor if it has no return type).
8361 if (Name.getAsIdentifierInfo() &&
8362 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8363 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8364 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8365 << SourceRange(D.getIdentifierLoc());
8369 // This is a C++ method declaration.
8370 CXXMethodDecl *Ret = CXXMethodDecl::Create(
8371 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8372 TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8373 TrailingRequiresClause);
8374 IsVirtualOkay = !Ret->isStatic();
8378 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8379 if (!isFriend && SemaRef.CurContext->isRecord())
8382 // Determine whether the function was written with a
8383 // prototype. This true when:
8384 // - we're in C++ (where every function has a prototype),
8385 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8386 R, TInfo, SC, isInline, true /*HasPrototype*/,
8387 ConstexprKind, TrailingRequiresClause);
8391 enum OpenCLParamType {
8395 InvalidAddrSpacePtrKernelParam,
8400 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8401 // Size dependent types are just typedefs to normal integer types
8402 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8403 // integers other than by their names.
8404 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8406 // Remove typedefs one by one until we reach a typedef
8407 // for a size dependent type.
8408 QualType DesugaredTy = Ty;
8410 ArrayRef<StringRef> Names(SizeTypeNames);
8411 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8412 if (Names.end() != Match)
8416 DesugaredTy = Ty.getSingleStepDesugaredType(C);
8417 } while (DesugaredTy != Ty);
8422 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8423 if (PT->isPointerType()) {
8424 QualType PointeeType = PT->getPointeeType();
8425 if (PointeeType->isPointerType())
8426 return PtrPtrKernelParam;
8427 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8428 PointeeType.getAddressSpace() == LangAS::opencl_private ||
8429 PointeeType.getAddressSpace() == LangAS::Default)
8430 return InvalidAddrSpacePtrKernelParam;
8431 return PtrKernelParam;
8434 // OpenCL v1.2 s6.9.k:
8435 // Arguments to kernel functions in a program cannot be declared with the
8436 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8437 // uintptr_t or a struct and/or union that contain fields declared to be one
8438 // of these built-in scalar types.
8439 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8440 return InvalidKernelParam;
8442 if (PT->isImageType())
8443 return PtrKernelParam;
8445 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8446 return InvalidKernelParam;
8448 // OpenCL extension spec v1.2 s9.5:
8449 // This extension adds support for half scalar and vector types as built-in
8450 // types that can be used for arithmetic operations, conversions etc.
8451 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8452 return InvalidKernelParam;
8454 if (PT->isRecordType())
8455 return RecordKernelParam;
8457 // Look into an array argument to check if it has a forbidden type.
8458 if (PT->isArrayType()) {
8459 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8460 // Call ourself to check an underlying type of an array. Since the
8461 // getPointeeOrArrayElementType returns an innermost type which is not an
8462 // array, this recursive call only happens once.
8463 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8466 return ValidKernelParam;
8469 static void checkIsValidOpenCLKernelParameter(
8473 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8474 QualType PT = Param->getType();
8476 // Cache the valid types we encounter to avoid rechecking structs that are
8478 if (ValidTypes.count(PT.getTypePtr()))
8481 switch (getOpenCLKernelParameterType(S, PT)) {
8482 case PtrPtrKernelParam:
8483 // OpenCL v1.2 s6.9.a:
8484 // A kernel function argument cannot be declared as a
8485 // pointer to a pointer type.
8486 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8490 case InvalidAddrSpacePtrKernelParam:
8491 // OpenCL v1.0 s6.5:
8492 // __kernel function arguments declared to be a pointer of a type can point
8493 // to one of the following address spaces only : __global, __local or
8495 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8499 // OpenCL v1.2 s6.9.k:
8500 // Arguments to kernel functions in a program cannot be declared with the
8501 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8502 // uintptr_t or a struct and/or union that contain fields declared to be
8503 // one of these built-in scalar types.
8505 case InvalidKernelParam:
8506 // OpenCL v1.2 s6.8 n:
8507 // A kernel function argument cannot be declared
8509 // Do not diagnose half type since it is diagnosed as invalid argument
8510 // type for any function elsewhere.
8511 if (!PT->isHalfType()) {
8512 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8514 // Explain what typedefs are involved.
8515 const TypedefType *Typedef = nullptr;
8516 while ((Typedef = PT->getAs<TypedefType>())) {
8517 SourceLocation Loc = Typedef->getDecl()->getLocation();
8518 // SourceLocation may be invalid for a built-in type.
8520 S.Diag(Loc, diag::note_entity_declared_at) << PT;
8521 PT = Typedef->desugar();
8528 case PtrKernelParam:
8529 case ValidKernelParam:
8530 ValidTypes.insert(PT.getTypePtr());
8533 case RecordKernelParam:
8537 // Track nested structs we will inspect
8538 SmallVector<const Decl *, 4> VisitStack;
8540 // Track where we are in the nested structs. Items will migrate from
8541 // VisitStack to HistoryStack as we do the DFS for bad field.
8542 SmallVector<const FieldDecl *, 4> HistoryStack;
8543 HistoryStack.push_back(nullptr);
8545 // At this point we already handled everything except of a RecordType or
8546 // an ArrayType of a RecordType.
8547 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8548 const RecordType *RecTy =
8549 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8550 const RecordDecl *OrigRecDecl = RecTy->getDecl();
8552 VisitStack.push_back(RecTy->getDecl());
8553 assert(VisitStack.back() && "First decl null?");
8556 const Decl *Next = VisitStack.pop_back_val();
8558 assert(!HistoryStack.empty());
8559 // Found a marker, we have gone up a level
8560 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8561 ValidTypes.insert(Hist->getType().getTypePtr());
8566 // Adds everything except the original parameter declaration (which is not a
8567 // field itself) to the history stack.
8568 const RecordDecl *RD;
8569 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8570 HistoryStack.push_back(Field);
8572 QualType FieldTy = Field->getType();
8573 // Other field types (known to be valid or invalid) are handled while we
8574 // walk around RecordDecl::fields().
8575 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8576 "Unexpected type.");
8577 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8579 RD = FieldRecTy->castAs<RecordType>()->getDecl();
8581 RD = cast<RecordDecl>(Next);
8584 // Add a null marker so we know when we've gone back up a level
8585 VisitStack.push_back(nullptr);
8587 for (const auto *FD : RD->fields()) {
8588 QualType QT = FD->getType();
8590 if (ValidTypes.count(QT.getTypePtr()))
8593 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8594 if (ParamType == ValidKernelParam)
8597 if (ParamType == RecordKernelParam) {
8598 VisitStack.push_back(FD);
8602 // OpenCL v1.2 s6.9.p:
8603 // Arguments to kernel functions that are declared to be a struct or union
8604 // do not allow OpenCL objects to be passed as elements of the struct or
8606 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8607 ParamType == InvalidAddrSpacePtrKernelParam) {
8608 S.Diag(Param->getLocation(),
8609 diag::err_record_with_pointers_kernel_param)
8610 << PT->isUnionType()
8613 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8616 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8617 << OrigRecDecl->getDeclName();
8619 // We have an error, now let's go back up through history and show where
8620 // the offending field came from
8621 for (ArrayRef<const FieldDecl *>::const_iterator
8622 I = HistoryStack.begin() + 1,
8623 E = HistoryStack.end();
8625 const FieldDecl *OuterField = *I;
8626 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8627 << OuterField->getType();
8630 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8631 << QT->isPointerType()
8636 } while (!VisitStack.empty());
8639 /// Find the DeclContext in which a tag is implicitly declared if we see an
8640 /// elaborated type specifier in the specified context, and lookup finds
8642 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8643 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8644 DC = DC->getParent();
8648 /// Find the Scope in which a tag is implicitly declared if we see an
8649 /// elaborated type specifier in the specified context, and lookup finds
8651 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8652 while (S->isClassScope() ||
8653 (LangOpts.CPlusPlus &&
8654 S->isFunctionPrototypeScope()) ||
8655 ((S->getFlags() & Scope::DeclScope) == 0) ||
8656 (S->getEntity() && S->getEntity()->isTransparentContext()))
8662 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8663 TypeSourceInfo *TInfo, LookupResult &Previous,
8664 MultiTemplateParamsArg TemplateParamListsRef,
8666 QualType R = TInfo->getType();
8668 assert(R->isFunctionType());
8669 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8670 for (TemplateParameterList *TPL : TemplateParamListsRef)
8671 TemplateParamLists.push_back(TPL);
8672 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8673 if (!TemplateParamLists.empty() &&
8674 Invented->getDepth() == TemplateParamLists.back()->getDepth())
8675 TemplateParamLists.back() = Invented;
8677 TemplateParamLists.push_back(Invented);
8680 // TODO: consider using NameInfo for diagnostic.
8681 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8682 DeclarationName Name = NameInfo.getName();
8683 StorageClass SC = getFunctionStorageClass(*this, D);
8685 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8686 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8687 diag::err_invalid_thread)
8688 << DeclSpec::getSpecifierName(TSCS);
8690 if (D.isFirstDeclarationOfMember())
8691 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8692 D.getIdentifierLoc());
8694 bool isFriend = false;
8695 FunctionTemplateDecl *FunctionTemplate = nullptr;
8696 bool isMemberSpecialization = false;
8697 bool isFunctionTemplateSpecialization = false;
8699 bool isDependentClassScopeExplicitSpecialization = false;
8700 bool HasExplicitTemplateArgs = false;
8701 TemplateArgumentListInfo TemplateArgs;
8703 bool isVirtualOkay = false;
8705 DeclContext *OriginalDC = DC;
8706 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8708 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8710 if (!NewFD) return nullptr;
8712 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8713 NewFD->setTopLevelDeclInObjCContainer();
8715 // Set the lexical context. If this is a function-scope declaration, or has a
8716 // C++ scope specifier, or is the object of a friend declaration, the lexical
8717 // context will be different from the semantic context.
8718 NewFD->setLexicalDeclContext(CurContext);
8720 if (IsLocalExternDecl)
8721 NewFD->setLocalExternDecl();
8723 if (getLangOpts().CPlusPlus) {
8724 bool isInline = D.getDeclSpec().isInlineSpecified();
8725 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8726 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8727 isFriend = D.getDeclSpec().isFriendSpecified();
8728 if (isFriend && !isInline && D.isFunctionDefinition()) {
8729 // C++ [class.friend]p5
8730 // A function can be defined in a friend declaration of a
8731 // class . . . . Such a function is implicitly inline.
8732 NewFD->setImplicitlyInline();
8735 // If this is a method defined in an __interface, and is not a constructor
8736 // or an overloaded operator, then set the pure flag (isVirtual will already
8738 if (const CXXRecordDecl *Parent =
8739 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8740 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8741 NewFD->setPure(true);
8743 // C++ [class.union]p2
8744 // A union can have member functions, but not virtual functions.
8745 if (isVirtual && Parent->isUnion())
8746 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8749 SetNestedNameSpecifier(*this, NewFD, D);
8750 isMemberSpecialization = false;
8751 isFunctionTemplateSpecialization = false;
8752 if (D.isInvalidType())
8753 NewFD->setInvalidDecl();
8755 // Match up the template parameter lists with the scope specifier, then
8756 // determine whether we have a template or a template specialization.
8757 bool Invalid = false;
8758 TemplateParameterList *TemplateParams =
8759 MatchTemplateParametersToScopeSpecifier(
8760 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8761 D.getCXXScopeSpec(),
8762 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8763 ? D.getName().TemplateId
8765 TemplateParamLists, isFriend, isMemberSpecialization,
8767 if (TemplateParams) {
8768 if (TemplateParams->size() > 0) {
8769 // This is a function template
8771 // Check that we can declare a template here.
8772 if (CheckTemplateDeclScope(S, TemplateParams))
8773 NewFD->setInvalidDecl();
8775 // A destructor cannot be a template.
8776 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8777 Diag(NewFD->getLocation(), diag::err_destructor_template);
8778 NewFD->setInvalidDecl();
8781 // If we're adding a template to a dependent context, we may need to
8782 // rebuilding some of the types used within the template parameter list,
8783 // now that we know what the current instantiation is.
8784 if (DC->isDependentContext()) {
8785 ContextRAII SavedContext(*this, DC);
8786 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8790 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8791 NewFD->getLocation(),
8792 Name, TemplateParams,
8794 FunctionTemplate->setLexicalDeclContext(CurContext);
8795 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8797 // For source fidelity, store the other template param lists.
8798 if (TemplateParamLists.size() > 1) {
8799 NewFD->setTemplateParameterListsInfo(Context,
8800 ArrayRef<TemplateParameterList *>(TemplateParamLists)
8804 // This is a function template specialization.
8805 isFunctionTemplateSpecialization = true;
8806 // For source fidelity, store all the template param lists.
8807 if (TemplateParamLists.size() > 0)
8808 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8810 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8812 // We want to remove the "template<>", found here.
8813 SourceRange RemoveRange = TemplateParams->getSourceRange();
8815 // If we remove the template<> and the name is not a
8816 // template-id, we're actually silently creating a problem:
8817 // the friend declaration will refer to an untemplated decl,
8818 // and clearly the user wants a template specialization. So
8819 // we need to insert '<>' after the name.
8820 SourceLocation InsertLoc;
8821 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8822 InsertLoc = D.getName().getSourceRange().getEnd();
8823 InsertLoc = getLocForEndOfToken(InsertLoc);
8826 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8827 << Name << RemoveRange
8828 << FixItHint::CreateRemoval(RemoveRange)
8829 << FixItHint::CreateInsertion(InsertLoc, "<>");
8833 // All template param lists were matched against the scope specifier:
8834 // this is NOT (an explicit specialization of) a template.
8835 if (TemplateParamLists.size() > 0)
8836 // For source fidelity, store all the template param lists.
8837 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8841 NewFD->setInvalidDecl();
8842 if (FunctionTemplate)
8843 FunctionTemplate->setInvalidDecl();
8846 // C++ [dcl.fct.spec]p5:
8847 // The virtual specifier shall only be used in declarations of
8848 // nonstatic class member functions that appear within a
8849 // member-specification of a class declaration; see 10.3.
8851 if (isVirtual && !NewFD->isInvalidDecl()) {
8852 if (!isVirtualOkay) {
8853 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8854 diag::err_virtual_non_function);
8855 } else if (!CurContext->isRecord()) {
8856 // 'virtual' was specified outside of the class.
8857 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8858 diag::err_virtual_out_of_class)
8859 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8860 } else if (NewFD->getDescribedFunctionTemplate()) {
8861 // C++ [temp.mem]p3:
8862 // A member function template shall not be virtual.
8863 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8864 diag::err_virtual_member_function_template)
8865 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8867 // Okay: Add virtual to the method.
8868 NewFD->setVirtualAsWritten(true);
8871 if (getLangOpts().CPlusPlus14 &&
8872 NewFD->getReturnType()->isUndeducedType())
8873 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8876 if (getLangOpts().CPlusPlus14 &&
8877 (NewFD->isDependentContext() ||
8878 (isFriend && CurContext->isDependentContext())) &&
8879 NewFD->getReturnType()->isUndeducedType()) {
8880 // If the function template is referenced directly (for instance, as a
8881 // member of the current instantiation), pretend it has a dependent type.
8882 // This is not really justified by the standard, but is the only sane
8884 // FIXME: For a friend function, we have not marked the function as being
8885 // a friend yet, so 'isDependentContext' on the FD doesn't work.
8886 const FunctionProtoType *FPT =
8887 NewFD->getType()->castAs<FunctionProtoType>();
8889 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8890 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8891 FPT->getExtProtoInfo()));
8894 // C++ [dcl.fct.spec]p3:
8895 // The inline specifier shall not appear on a block scope function
8897 if (isInline && !NewFD->isInvalidDecl()) {
8898 if (CurContext->isFunctionOrMethod()) {
8899 // 'inline' is not allowed on block scope function declaration.
8900 Diag(D.getDeclSpec().getInlineSpecLoc(),
8901 diag::err_inline_declaration_block_scope) << Name
8902 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8906 // C++ [dcl.fct.spec]p6:
8907 // The explicit specifier shall be used only in the declaration of a
8908 // constructor or conversion function within its class definition;
8909 // see 12.3.1 and 12.3.2.
8910 if (hasExplicit && !NewFD->isInvalidDecl() &&
8911 !isa<CXXDeductionGuideDecl>(NewFD)) {
8912 if (!CurContext->isRecord()) {
8913 // 'explicit' was specified outside of the class.
8914 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8915 diag::err_explicit_out_of_class)
8916 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8917 } else if (!isa<CXXConstructorDecl>(NewFD) &&
8918 !isa<CXXConversionDecl>(NewFD)) {
8919 // 'explicit' was specified on a function that wasn't a constructor
8920 // or conversion function.
8921 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8922 diag::err_explicit_non_ctor_or_conv_function)
8923 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8927 if (ConstexprSpecKind ConstexprKind =
8928 D.getDeclSpec().getConstexprSpecifier()) {
8929 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8930 // are implicitly inline.
8931 NewFD->setImplicitlyInline();
8933 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8934 // be either constructors or to return a literal type. Therefore,
8935 // destructors cannot be declared constexpr.
8936 if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) {
8937 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8942 // If __module_private__ was specified, mark the function accordingly.
8943 if (D.getDeclSpec().isModulePrivateSpecified()) {
8944 if (isFunctionTemplateSpecialization) {
8945 SourceLocation ModulePrivateLoc
8946 = D.getDeclSpec().getModulePrivateSpecLoc();
8947 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8949 << FixItHint::CreateRemoval(ModulePrivateLoc);
8951 NewFD->setModulePrivate();
8952 if (FunctionTemplate)
8953 FunctionTemplate->setModulePrivate();
8958 if (FunctionTemplate) {
8959 FunctionTemplate->setObjectOfFriendDecl();
8960 FunctionTemplate->setAccess(AS_public);
8962 NewFD->setObjectOfFriendDecl();
8963 NewFD->setAccess(AS_public);
8966 // If a function is defined as defaulted or deleted, mark it as such now.
8967 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8968 // definition kind to FDK_Definition.
8969 switch (D.getFunctionDefinitionKind()) {
8970 case FDK_Declaration:
8971 case FDK_Definition:
8975 NewFD->setDefaulted();
8979 NewFD->setDeletedAsWritten();
8983 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8984 D.isFunctionDefinition()) {
8985 // C++ [class.mfct]p2:
8986 // A member function may be defined (8.4) in its class definition, in
8987 // which case it is an inline member function (7.1.2)
8988 NewFD->setImplicitlyInline();
8991 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8992 !CurContext->isRecord()) {
8993 // C++ [class.static]p1:
8994 // A data or function member of a class may be declared static
8995 // in a class definition, in which case it is a static member of
8998 // Complain about the 'static' specifier if it's on an out-of-line
8999 // member function definition.
9001 // MSVC permits the use of a 'static' storage specifier on an out-of-line
9002 // member function template declaration and class member template
9003 // declaration (MSVC versions before 2015), warn about this.
9004 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9005 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9006 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9007 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9008 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9009 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9012 // C++11 [except.spec]p15:
9013 // A deallocation function with no exception-specification is treated
9014 // as if it were specified with noexcept(true).
9015 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9016 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9017 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9018 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9019 NewFD->setType(Context.getFunctionType(
9020 FPT->getReturnType(), FPT->getParamTypes(),
9021 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9024 // Filter out previous declarations that don't match the scope.
9025 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9026 D.getCXXScopeSpec().isNotEmpty() ||
9027 isMemberSpecialization ||
9028 isFunctionTemplateSpecialization);
9030 // Handle GNU asm-label extension (encoded as an attribute).
9031 if (Expr *E = (Expr*) D.getAsmLabel()) {
9032 // The parser guarantees this is a string.
9033 StringLiteral *SE = cast<StringLiteral>(E);
9034 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9035 /*IsLiteralLabel=*/true,
9036 SE->getStrTokenLoc(0)));
9037 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9038 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9039 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9040 if (I != ExtnameUndeclaredIdentifiers.end()) {
9041 if (isDeclExternC(NewFD)) {
9042 NewFD->addAttr(I->second);
9043 ExtnameUndeclaredIdentifiers.erase(I);
9045 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9046 << /*Variable*/0 << NewFD;
9050 // Copy the parameter declarations from the declarator D to the function
9051 // declaration NewFD, if they are available. First scavenge them into Params.
9052 SmallVector<ParmVarDecl*, 16> Params;
9054 if (D.isFunctionDeclarator(FTIIdx)) {
9055 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9057 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9058 // function that takes no arguments, not a function that takes a
9059 // single void argument.
9060 // We let through "const void" here because Sema::GetTypeForDeclarator
9061 // already checks for that case.
9062 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9063 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9064 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9065 assert(Param->getDeclContext() != NewFD && "Was set before ?");
9066 Param->setDeclContext(NewFD);
9067 Params.push_back(Param);
9069 if (Param->isInvalidDecl())
9070 NewFD->setInvalidDecl();
9074 if (!getLangOpts().CPlusPlus) {
9075 // In C, find all the tag declarations from the prototype and move them
9076 // into the function DeclContext. Remove them from the surrounding tag
9077 // injection context of the function, which is typically but not always
9079 DeclContext *PrototypeTagContext =
9080 getTagInjectionContext(NewFD->getLexicalDeclContext());
9081 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9082 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9084 // We don't want to reparent enumerators. Look at their parent enum
9087 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9088 TD = cast<EnumDecl>(ECD->getDeclContext());
9092 DeclContext *TagDC = TD->getLexicalDeclContext();
9093 if (!TagDC->containsDecl(TD))
9095 TagDC->removeDecl(TD);
9096 TD->setDeclContext(NewFD);
9099 // Preserve the lexical DeclContext if it is not the surrounding tag
9100 // injection context of the FD. In this example, the semantic context of
9101 // E will be f and the lexical context will be S, while both the
9102 // semantic and lexical contexts of S will be f:
9103 // void f(struct S { enum E { a } f; } s);
9104 if (TagDC != PrototypeTagContext)
9105 TD->setLexicalDeclContext(TagDC);
9108 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9109 // When we're declaring a function with a typedef, typeof, etc as in the
9110 // following example, we'll need to synthesize (unnamed)
9111 // parameters for use in the declaration.
9114 // typedef void fn(int);
9118 // Synthesize a parameter for each argument type.
9119 for (const auto &AI : FT->param_types()) {
9120 ParmVarDecl *Param =
9121 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9122 Param->setScopeInfo(0, Params.size());
9123 Params.push_back(Param);
9126 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9127 "Should not need args for typedef of non-prototype fn");
9130 // Finally, we know we have the right number of parameters, install them.
9131 NewFD->setParams(Params);
9133 if (D.getDeclSpec().isNoreturnSpecified())
9134 NewFD->addAttr(C11NoReturnAttr::Create(Context,
9135 D.getDeclSpec().getNoreturnSpecLoc(),
9136 AttributeCommonInfo::AS_Keyword));
9138 // Functions returning a variably modified type violate C99 6.7.5.2p2
9139 // because all functions have linkage.
9140 if (!NewFD->isInvalidDecl() &&
9141 NewFD->getReturnType()->isVariablyModifiedType()) {
9142 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9143 NewFD->setInvalidDecl();
9146 // Apply an implicit SectionAttr if '#pragma clang section text' is active
9147 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9148 !NewFD->hasAttr<SectionAttr>())
9149 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9150 Context, PragmaClangTextSection.SectionName,
9151 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9153 // Apply an implicit SectionAttr if #pragma code_seg is active.
9154 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9155 !NewFD->hasAttr<SectionAttr>()) {
9156 NewFD->addAttr(SectionAttr::CreateImplicit(
9157 Context, CodeSegStack.CurrentValue->getString(),
9158 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9159 SectionAttr::Declspec_allocate));
9160 if (UnifySection(CodeSegStack.CurrentValue->getString(),
9161 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9162 ASTContext::PSF_Read,
9164 NewFD->dropAttr<SectionAttr>();
9167 // Apply an implicit CodeSegAttr from class declspec or
9168 // apply an implicit SectionAttr from #pragma code_seg if active.
9169 if (!NewFD->hasAttr<CodeSegAttr>()) {
9170 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9171 D.isFunctionDefinition())) {
9172 NewFD->addAttr(SAttr);
9176 // Handle attributes.
9177 ProcessDeclAttributes(S, NewFD, D);
9179 if (getLangOpts().OpenCL) {
9180 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9181 // type declaration will generate a compilation error.
9182 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9183 if (AddressSpace != LangAS::Default) {
9184 Diag(NewFD->getLocation(),
9185 diag::err_opencl_return_value_with_address_space);
9186 NewFD->setInvalidDecl();
9190 if (!getLangOpts().CPlusPlus) {
9191 // Perform semantic checking on the function declaration.
9192 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9193 CheckMain(NewFD, D.getDeclSpec());
9195 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9196 CheckMSVCRTEntryPoint(NewFD);
9198 if (!NewFD->isInvalidDecl())
9199 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9200 isMemberSpecialization));
9201 else if (!Previous.empty())
9202 // Recover gracefully from an invalid redeclaration.
9203 D.setRedeclaration(true);
9204 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9205 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9206 "previous declaration set still overloaded");
9208 // Diagnose no-prototype function declarations with calling conventions that
9209 // don't support variadic calls. Only do this in C and do it after merging
9210 // possibly prototyped redeclarations.
9211 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9212 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9213 CallingConv CC = FT->getExtInfo().getCC();
9214 if (!supportsVariadicCall(CC)) {
9215 // Windows system headers sometimes accidentally use stdcall without
9216 // (void) parameters, so we relax this to a warning.
9218 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9219 Diag(NewFD->getLocation(), DiagID)
9220 << FunctionType::getNameForCallConv(CC);
9224 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9225 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9226 checkNonTrivialCUnion(NewFD->getReturnType(),
9227 NewFD->getReturnTypeSourceRange().getBegin(),
9228 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9230 // C++11 [replacement.functions]p3:
9231 // The program's definitions shall not be specified as inline.
9233 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9235 // Suppress the diagnostic if the function is __attribute__((used)), since
9236 // that forces an external definition to be emitted.
9237 if (D.getDeclSpec().isInlineSpecified() &&
9238 NewFD->isReplaceableGlobalAllocationFunction() &&
9239 !NewFD->hasAttr<UsedAttr>())
9240 Diag(D.getDeclSpec().getInlineSpecLoc(),
9241 diag::ext_operator_new_delete_declared_inline)
9242 << NewFD->getDeclName();
9244 // If the declarator is a template-id, translate the parser's template
9245 // argument list into our AST format.
9246 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9247 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9248 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9249 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9250 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9251 TemplateId->NumArgs);
9252 translateTemplateArguments(TemplateArgsPtr,
9255 HasExplicitTemplateArgs = true;
9257 if (NewFD->isInvalidDecl()) {
9258 HasExplicitTemplateArgs = false;
9259 } else if (FunctionTemplate) {
9260 // Function template with explicit template arguments.
9261 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9262 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9264 HasExplicitTemplateArgs = false;
9266 assert((isFunctionTemplateSpecialization ||
9267 D.getDeclSpec().isFriendSpecified()) &&
9268 "should have a 'template<>' for this decl");
9269 // "friend void foo<>(int);" is an implicit specialization decl.
9270 isFunctionTemplateSpecialization = true;
9272 } else if (isFriend && isFunctionTemplateSpecialization) {
9273 // This combination is only possible in a recovery case; the user
9274 // wrote something like:
9275 // template <> friend void foo(int);
9276 // which we're recovering from as if the user had written:
9277 // friend void foo<>(int);
9278 // Go ahead and fake up a template id.
9279 HasExplicitTemplateArgs = true;
9280 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9281 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9284 // We do not add HD attributes to specializations here because
9285 // they may have different constexpr-ness compared to their
9286 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9287 // may end up with different effective targets. Instead, a
9288 // specialization inherits its target attributes from its template
9289 // in the CheckFunctionTemplateSpecialization() call below.
9290 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9291 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9293 // If it's a friend (and only if it's a friend), it's possible
9294 // that either the specialized function type or the specialized
9295 // template is dependent, and therefore matching will fail. In
9296 // this case, don't check the specialization yet.
9297 bool InstantiationDependent = false;
9298 if (isFunctionTemplateSpecialization && isFriend &&
9299 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9300 TemplateSpecializationType::anyDependentTemplateArguments(
9302 InstantiationDependent))) {
9303 assert(HasExplicitTemplateArgs &&
9304 "friend function specialization without template args");
9305 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9307 NewFD->setInvalidDecl();
9308 } else if (isFunctionTemplateSpecialization) {
9309 if (CurContext->isDependentContext() && CurContext->isRecord()
9311 isDependentClassScopeExplicitSpecialization = true;
9312 } else if (!NewFD->isInvalidDecl() &&
9313 CheckFunctionTemplateSpecialization(
9314 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9316 NewFD->setInvalidDecl();
9319 // A storage-class-specifier shall not be specified in an explicit
9320 // specialization (14.7.3)
9321 FunctionTemplateSpecializationInfo *Info =
9322 NewFD->getTemplateSpecializationInfo();
9323 if (Info && SC != SC_None) {
9324 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9325 Diag(NewFD->getLocation(),
9326 diag::err_explicit_specialization_inconsistent_storage_class)
9328 << FixItHint::CreateRemoval(
9329 D.getDeclSpec().getStorageClassSpecLoc());
9332 Diag(NewFD->getLocation(),
9333 diag::ext_explicit_specialization_storage_class)
9334 << FixItHint::CreateRemoval(
9335 D.getDeclSpec().getStorageClassSpecLoc());
9337 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9338 if (CheckMemberSpecialization(NewFD, Previous))
9339 NewFD->setInvalidDecl();
9342 // Perform semantic checking on the function declaration.
9343 if (!isDependentClassScopeExplicitSpecialization) {
9344 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9345 CheckMain(NewFD, D.getDeclSpec());
9347 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9348 CheckMSVCRTEntryPoint(NewFD);
9350 if (!NewFD->isInvalidDecl())
9351 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9352 isMemberSpecialization));
9353 else if (!Previous.empty())
9354 // Recover gracefully from an invalid redeclaration.
9355 D.setRedeclaration(true);
9358 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9359 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9360 "previous declaration set still overloaded");
9362 NamedDecl *PrincipalDecl = (FunctionTemplate
9363 ? cast<NamedDecl>(FunctionTemplate)
9366 if (isFriend && NewFD->getPreviousDecl()) {
9367 AccessSpecifier Access = AS_public;
9368 if (!NewFD->isInvalidDecl())
9369 Access = NewFD->getPreviousDecl()->getAccess();
9371 NewFD->setAccess(Access);
9372 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9375 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9376 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9377 PrincipalDecl->setNonMemberOperator();
9379 // If we have a function template, check the template parameter
9380 // list. This will check and merge default template arguments.
9381 if (FunctionTemplate) {
9382 FunctionTemplateDecl *PrevTemplate =
9383 FunctionTemplate->getPreviousDecl();
9384 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9385 PrevTemplate ? PrevTemplate->getTemplateParameters()
9387 D.getDeclSpec().isFriendSpecified()
9388 ? (D.isFunctionDefinition()
9389 ? TPC_FriendFunctionTemplateDefinition
9390 : TPC_FriendFunctionTemplate)
9391 : (D.getCXXScopeSpec().isSet() &&
9392 DC && DC->isRecord() &&
9393 DC->isDependentContext())
9394 ? TPC_ClassTemplateMember
9395 : TPC_FunctionTemplate);
9398 if (NewFD->isInvalidDecl()) {
9399 // Ignore all the rest of this.
9400 } else if (!D.isRedeclaration()) {
9401 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9403 // Fake up an access specifier if it's supposed to be a class member.
9404 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9405 NewFD->setAccess(AS_public);
9407 // Qualified decls generally require a previous declaration.
9408 if (D.getCXXScopeSpec().isSet()) {
9409 // ...with the major exception of templated-scope or
9410 // dependent-scope friend declarations.
9412 // TODO: we currently also suppress this check in dependent
9413 // contexts because (1) the parameter depth will be off when
9414 // matching friend templates and (2) we might actually be
9415 // selecting a friend based on a dependent factor. But there
9416 // are situations where these conditions don't apply and we
9417 // can actually do this check immediately.
9419 // Unless the scope is dependent, it's always an error if qualified
9420 // redeclaration lookup found nothing at all. Diagnose that now;
9421 // nothing will diagnose that error later.
9423 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9424 (!Previous.empty() && CurContext->isDependentContext()))) {
9427 // The user tried to provide an out-of-line definition for a
9428 // function that is a member of a class or namespace, but there
9429 // was no such member function declared (C++ [class.mfct]p2,
9430 // C++ [namespace.memdef]p2). For example:
9436 // void X::f() { } // ill-formed
9438 // Complain about this problem, and attempt to suggest close
9439 // matches (e.g., those that differ only in cv-qualifiers and
9440 // whether the parameter types are references).
9442 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9443 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9444 AddToScope = ExtraArgs.AddToScope;
9449 // Unqualified local friend declarations are required to resolve
9451 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9452 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9453 *this, Previous, NewFD, ExtraArgs, true, S)) {
9454 AddToScope = ExtraArgs.AddToScope;
9458 } else if (!D.isFunctionDefinition() &&
9459 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9460 !isFriend && !isFunctionTemplateSpecialization &&
9461 !isMemberSpecialization) {
9462 // An out-of-line member function declaration must also be a
9463 // definition (C++ [class.mfct]p2).
9464 // Note that this is not the case for explicit specializations of
9465 // function templates or member functions of class templates, per
9466 // C++ [temp.expl.spec]p2. We also allow these declarations as an
9467 // extension for compatibility with old SWIG code which likes to
9469 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9470 << D.getCXXScopeSpec().getRange();
9474 ProcessPragmaWeak(S, NewFD);
9475 checkAttributesAfterMerging(*this, *NewFD);
9477 AddKnownFunctionAttributes(NewFD);
9479 if (NewFD->hasAttr<OverloadableAttr>() &&
9480 !NewFD->getType()->getAs<FunctionProtoType>()) {
9481 Diag(NewFD->getLocation(),
9482 diag::err_attribute_overloadable_no_prototype)
9485 // Turn this into a variadic function with no parameters.
9486 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9487 FunctionProtoType::ExtProtoInfo EPI(
9488 Context.getDefaultCallingConvention(true, false));
9489 EPI.Variadic = true;
9490 EPI.ExtInfo = FT->getExtInfo();
9492 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9496 // If there's a #pragma GCC visibility in scope, and this isn't a class
9497 // member, set the visibility of this function.
9498 if (!DC->isRecord() && NewFD->isExternallyVisible())
9499 AddPushedVisibilityAttribute(NewFD);
9501 // If there's a #pragma clang arc_cf_code_audited in scope, consider
9502 // marking the function.
9503 AddCFAuditedAttribute(NewFD);
9505 // If this is a function definition, check if we have to apply optnone due to
9507 if(D.isFunctionDefinition())
9508 AddRangeBasedOptnone(NewFD);
9510 // If this is the first declaration of an extern C variable, update
9511 // the map of such variables.
9512 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9513 isIncompleteDeclExternC(*this, NewFD))
9514 RegisterLocallyScopedExternCDecl(NewFD, S);
9516 // Set this FunctionDecl's range up to the right paren.
9517 NewFD->setRangeEnd(D.getSourceRange().getEnd());
9519 if (D.isRedeclaration() && !Previous.empty()) {
9520 NamedDecl *Prev = Previous.getRepresentativeDecl();
9521 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9522 isMemberSpecialization ||
9523 isFunctionTemplateSpecialization,
9524 D.isFunctionDefinition());
9527 if (getLangOpts().CUDA) {
9528 IdentifierInfo *II = NewFD->getIdentifier();
9529 if (II && II->isStr(getCudaConfigureFuncName()) &&
9530 !NewFD->isInvalidDecl() &&
9531 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9532 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9533 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9534 << getCudaConfigureFuncName();
9535 Context.setcudaConfigureCallDecl(NewFD);
9538 // Variadic functions, other than a *declaration* of printf, are not allowed
9539 // in device-side CUDA code, unless someone passed
9540 // -fcuda-allow-variadic-functions.
9541 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9542 (NewFD->hasAttr<CUDADeviceAttr>() ||
9543 NewFD->hasAttr<CUDAGlobalAttr>()) &&
9544 !(II && II->isStr("printf") && NewFD->isExternC() &&
9545 !D.isFunctionDefinition())) {
9546 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9550 MarkUnusedFileScopedDecl(NewFD);
9554 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9555 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9556 if ((getLangOpts().OpenCLVersion >= 120)
9557 && (SC == SC_Static)) {
9558 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9562 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9563 if (!NewFD->getReturnType()->isVoidType()) {
9564 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9565 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9566 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9571 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9572 for (auto Param : NewFD->parameters())
9573 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9575 if (getLangOpts().OpenCLCPlusPlus) {
9576 if (DC->isRecord()) {
9577 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9580 if (FunctionTemplate) {
9581 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9587 if (getLangOpts().CPlusPlus) {
9588 if (FunctionTemplate) {
9589 if (NewFD->isInvalidDecl())
9590 FunctionTemplate->setInvalidDecl();
9591 return FunctionTemplate;
9594 if (isMemberSpecialization && !NewFD->isInvalidDecl())
9595 CompleteMemberSpecialization(NewFD, Previous);
9598 for (const ParmVarDecl *Param : NewFD->parameters()) {
9599 QualType PT = Param->getType();
9601 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9603 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9604 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9605 QualType ElemTy = PipeTy->getElementType();
9606 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9607 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9614 // Here we have an function template explicit specialization at class scope.
9615 // The actual specialization will be postponed to template instatiation
9616 // time via the ClassScopeFunctionSpecializationDecl node.
9617 if (isDependentClassScopeExplicitSpecialization) {
9618 ClassScopeFunctionSpecializationDecl *NewSpec =
9619 ClassScopeFunctionSpecializationDecl::Create(
9620 Context, CurContext, NewFD->getLocation(),
9621 cast<CXXMethodDecl>(NewFD),
9622 HasExplicitTemplateArgs, TemplateArgs);
9623 CurContext->addDecl(NewSpec);
9627 // Diagnose availability attributes. Availability cannot be used on functions
9628 // that are run during load/unload.
9629 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9630 if (NewFD->hasAttr<ConstructorAttr>()) {
9631 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9633 NewFD->dropAttr<AvailabilityAttr>();
9635 if (NewFD->hasAttr<DestructorAttr>()) {
9636 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9638 NewFD->dropAttr<AvailabilityAttr>();
9642 // Diagnose no_builtin attribute on function declaration that are not a
9644 // FIXME: We should really be doing this in
9645 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9646 // the FunctionDecl and at this point of the code
9647 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9648 // because Sema::ActOnStartOfFunctionDef has not been called yet.
9649 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9650 switch (D.getFunctionDefinitionKind()) {
9653 Diag(NBA->getLocation(),
9654 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9655 << NBA->getSpelling();
9657 case FDK_Declaration:
9658 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9659 << NBA->getSpelling();
9661 case FDK_Definition:
9668 /// Return a CodeSegAttr from a containing class. The Microsoft docs say
9669 /// when __declspec(code_seg) "is applied to a class, all member functions of
9670 /// the class and nested classes -- this includes compiler-generated special
9671 /// member functions -- are put in the specified segment."
9672 /// The actual behavior is a little more complicated. The Microsoft compiler
9673 /// won't check outer classes if there is an active value from #pragma code_seg.
9674 /// The CodeSeg is always applied from the direct parent but only from outer
9675 /// classes when the #pragma code_seg stack is empty. See:
9676 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9677 /// available since MS has removed the page.
9678 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9679 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9682 const CXXRecordDecl *Parent = Method->getParent();
9683 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9684 Attr *NewAttr = SAttr->clone(S.getASTContext());
9685 NewAttr->setImplicit(true);
9689 // The Microsoft compiler won't check outer classes for the CodeSeg
9690 // when the #pragma code_seg stack is active.
9691 if (S.CodeSegStack.CurrentValue)
9694 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9695 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9696 Attr *NewAttr = SAttr->clone(S.getASTContext());
9697 NewAttr->setImplicit(true);
9704 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9705 /// containing class. Otherwise it will return implicit SectionAttr if the
9706 /// function is a definition and there is an active value on CodeSegStack
9707 /// (from the current #pragma code-seg value).
9709 /// \param FD Function being declared.
9710 /// \param IsDefinition Whether it is a definition or just a declarartion.
9711 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9712 /// nullptr if no attribute should be added.
9713 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9714 bool IsDefinition) {
9715 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9717 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9718 CodeSegStack.CurrentValue)
9719 return SectionAttr::CreateImplicit(
9720 getASTContext(), CodeSegStack.CurrentValue->getString(),
9721 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9722 SectionAttr::Declspec_allocate);
9726 /// Determines if we can perform a correct type check for \p D as a
9727 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9728 /// best-effort check.
9730 /// \param NewD The new declaration.
9731 /// \param OldD The old declaration.
9732 /// \param NewT The portion of the type of the new declaration to check.
9733 /// \param OldT The portion of the type of the old declaration to check.
9734 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9735 QualType NewT, QualType OldT) {
9736 if (!NewD->getLexicalDeclContext()->isDependentContext())
9739 // For dependently-typed local extern declarations and friends, we can't
9740 // perform a correct type check in general until instantiation:
9743 // template<typename T> void g() { T f(); }
9745 // (valid if g() is only instantiated with T = int).
9746 if (NewT->isDependentType() &&
9747 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9750 // Similarly, if the previous declaration was a dependent local extern
9751 // declaration, we don't really know its type yet.
9752 if (OldT->isDependentType() && OldD->isLocalExternDecl())
9758 /// Checks if the new declaration declared in dependent context must be
9759 /// put in the same redeclaration chain as the specified declaration.
9761 /// \param D Declaration that is checked.
9762 /// \param PrevDecl Previous declaration found with proper lookup method for the
9763 /// same declaration name.
9764 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9767 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9768 if (!D->getLexicalDeclContext()->isDependentContext())
9771 // Don't chain dependent friend function definitions until instantiation, to
9772 // permit cases like
9775 // template<typename T> class C1 { friend void func() {} };
9776 // template<typename T> class C2 { friend void func() {} };
9778 // ... which is valid if only one of C1 and C2 is ever instantiated.
9780 // FIXME: This need only apply to function definitions. For now, we proxy
9781 // this by checking for a file-scope function. We do not want this to apply
9782 // to friend declarations nominating member functions, because that gets in
9783 // the way of access checks.
9784 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9787 auto *VD = dyn_cast<ValueDecl>(D);
9788 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9789 return !VD || !PrevVD ||
9790 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9794 /// Check the target attribute of the function for MultiVersion
9797 /// Returns true if there was an error, false otherwise.
9798 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9799 const auto *TA = FD->getAttr<TargetAttr>();
9800 assert(TA && "MultiVersion Candidate requires a target attribute");
9801 ParsedTargetAttr ParseInfo = TA->parse();
9802 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9803 enum ErrType { Feature = 0, Architecture = 1 };
9805 if (!ParseInfo.Architecture.empty() &&
9806 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9807 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9808 << Architecture << ParseInfo.Architecture;
9812 for (const auto &Feat : ParseInfo.Features) {
9813 auto BareFeat = StringRef{Feat}.substr(1);
9814 if (Feat[0] == '-') {
9815 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9816 << Feature << ("no-" + BareFeat).str();
9820 if (!TargetInfo.validateCpuSupports(BareFeat) ||
9821 !TargetInfo.isValidFeatureName(BareFeat)) {
9822 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9823 << Feature << BareFeat;
9830 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9831 MultiVersionKind MVType) {
9832 for (const Attr *A : FD->attrs()) {
9833 switch (A->getKind()) {
9834 case attr::CPUDispatch:
9835 case attr::CPUSpecific:
9836 if (MVType != MultiVersionKind::CPUDispatch &&
9837 MVType != MultiVersionKind::CPUSpecific)
9841 if (MVType != MultiVersionKind::Target)
9851 bool Sema::areMultiversionVariantFunctionsCompatible(
9852 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9853 const PartialDiagnostic &NoProtoDiagID,
9854 const PartialDiagnosticAt &NoteCausedDiagIDAt,
9855 const PartialDiagnosticAt &NoSupportDiagIDAt,
9856 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9857 bool ConstexprSupported, bool CLinkageMayDiffer) {
9858 enum DoesntSupport {
9878 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
9879 !OldFD->getType()->getAs<FunctionProtoType>()) {
9880 Diag(OldFD->getLocation(), NoProtoDiagID);
9881 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
9885 if (NoProtoDiagID.getDiagID() != 0 &&
9886 !NewFD->getType()->getAs<FunctionProtoType>())
9887 return Diag(NewFD->getLocation(), NoProtoDiagID);
9889 if (!TemplatesSupported &&
9890 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9891 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9894 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9895 if (NewCXXFD->isVirtual())
9896 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9899 if (isa<CXXConstructorDecl>(NewCXXFD))
9900 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9903 if (isa<CXXDestructorDecl>(NewCXXFD))
9904 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9908 if (NewFD->isDeleted())
9909 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9912 if (NewFD->isDefaulted())
9913 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9916 if (!ConstexprSupported && NewFD->isConstexpr())
9917 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9918 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9920 QualType NewQType = Context.getCanonicalType(NewFD->getType());
9921 const auto *NewType = cast<FunctionType>(NewQType);
9922 QualType NewReturnType = NewType->getReturnType();
9924 if (NewReturnType->isUndeducedType())
9925 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9928 // Ensure the return type is identical.
9930 QualType OldQType = Context.getCanonicalType(OldFD->getType());
9931 const auto *OldType = cast<FunctionType>(OldQType);
9932 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9933 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9935 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9936 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
9938 QualType OldReturnType = OldType->getReturnType();
9940 if (OldReturnType != NewReturnType)
9941 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
9943 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9944 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
9946 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9947 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
9949 if (OldFD->getStorageClass() != NewFD->getStorageClass())
9950 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
9952 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
9953 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
9955 if (CheckEquivalentExceptionSpec(
9956 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9957 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9963 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9964 const FunctionDecl *NewFD,
9966 MultiVersionKind MVType) {
9967 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9968 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9970 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9974 bool IsCPUSpecificCPUDispatchMVType =
9975 MVType == MultiVersionKind::CPUDispatch ||
9976 MVType == MultiVersionKind::CPUSpecific;
9978 // For now, disallow all other attributes. These should be opt-in, but
9979 // an analysis of all of them is a future FIXME.
9980 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9981 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9982 << IsCPUSpecificCPUDispatchMVType;
9983 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9987 if (HasNonMultiVersionAttributes(NewFD, MVType))
9988 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9989 << IsCPUSpecificCPUDispatchMVType;
9991 // Only allow transition to MultiVersion if it hasn't been used.
9992 if (OldFD && CausesMV && OldFD->isUsed(false))
9993 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9995 return S.areMultiversionVariantFunctionsCompatible(
9996 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
9997 PartialDiagnosticAt(NewFD->getLocation(),
9998 S.PDiag(diag::note_multiversioning_caused_here)),
9999 PartialDiagnosticAt(NewFD->getLocation(),
10000 S.PDiag(diag::err_multiversion_doesnt_support)
10001 << IsCPUSpecificCPUDispatchMVType),
10002 PartialDiagnosticAt(NewFD->getLocation(),
10003 S.PDiag(diag::err_multiversion_diff)),
10004 /*TemplatesSupported=*/false,
10005 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10006 /*CLinkageMayDiffer=*/false);
10009 /// Check the validity of a multiversion function declaration that is the
10010 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10012 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10014 /// Returns true if there was an error, false otherwise.
10015 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10016 MultiVersionKind MVType,
10017 const TargetAttr *TA) {
10018 assert(MVType != MultiVersionKind::None &&
10019 "Function lacks multiversion attribute");
10021 // Target only causes MV if it is default, otherwise this is a normal
10023 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10026 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10027 FD->setInvalidDecl();
10031 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10032 FD->setInvalidDecl();
10036 FD->setIsMultiVersion();
10040 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10041 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10042 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10049 static bool CheckTargetCausesMultiVersioning(
10050 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10051 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10052 LookupResult &Previous) {
10053 const auto *OldTA = OldFD->getAttr<TargetAttr>();
10054 ParsedTargetAttr NewParsed = NewTA->parse();
10055 // Sort order doesn't matter, it just needs to be consistent.
10056 llvm::sort(NewParsed.Features);
10058 // If the old decl is NOT MultiVersioned yet, and we don't cause that
10059 // to change, this is a simple redeclaration.
10060 if (!NewTA->isDefaultVersion() &&
10061 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10064 // Otherwise, this decl causes MultiVersioning.
10065 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10066 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10067 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10068 NewFD->setInvalidDecl();
10072 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10073 MultiVersionKind::Target)) {
10074 NewFD->setInvalidDecl();
10078 if (CheckMultiVersionValue(S, NewFD)) {
10079 NewFD->setInvalidDecl();
10083 // If this is 'default', permit the forward declaration.
10084 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10085 Redeclaration = true;
10087 OldFD->setIsMultiVersion();
10088 NewFD->setIsMultiVersion();
10092 if (CheckMultiVersionValue(S, OldFD)) {
10093 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10094 NewFD->setInvalidDecl();
10098 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10100 if (OldParsed == NewParsed) {
10101 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10102 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10103 NewFD->setInvalidDecl();
10107 for (const auto *FD : OldFD->redecls()) {
10108 const auto *CurTA = FD->getAttr<TargetAttr>();
10109 // We allow forward declarations before ANY multiversioning attributes, but
10110 // nothing after the fact.
10111 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10112 (!CurTA || CurTA->isInherited())) {
10113 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10115 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10116 NewFD->setInvalidDecl();
10121 OldFD->setIsMultiVersion();
10122 NewFD->setIsMultiVersion();
10123 Redeclaration = false;
10124 MergeTypeWithPrevious = false;
10130 /// Check the validity of a new function declaration being added to an existing
10131 /// multiversioned declaration collection.
10132 static bool CheckMultiVersionAdditionalDecl(
10133 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10134 MultiVersionKind NewMVType, const TargetAttr *NewTA,
10135 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10136 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10137 LookupResult &Previous) {
10139 MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10140 // Disallow mixing of multiversioning types.
10141 if ((OldMVType == MultiVersionKind::Target &&
10142 NewMVType != MultiVersionKind::Target) ||
10143 (NewMVType == MultiVersionKind::Target &&
10144 OldMVType != MultiVersionKind::Target)) {
10145 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10146 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10147 NewFD->setInvalidDecl();
10151 ParsedTargetAttr NewParsed;
10153 NewParsed = NewTA->parse();
10154 llvm::sort(NewParsed.Features);
10157 bool UseMemberUsingDeclRules =
10158 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10160 // Next, check ALL non-overloads to see if this is a redeclaration of a
10161 // previous member of the MultiVersion set.
10162 for (NamedDecl *ND : Previous) {
10163 FunctionDecl *CurFD = ND->getAsFunction();
10166 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10169 if (NewMVType == MultiVersionKind::Target) {
10170 const auto *CurTA = CurFD->getAttr<TargetAttr>();
10171 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10172 NewFD->setIsMultiVersion();
10173 Redeclaration = true;
10178 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10179 if (CurParsed == NewParsed) {
10180 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10181 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10182 NewFD->setInvalidDecl();
10186 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10187 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10188 // Handle CPUDispatch/CPUSpecific versions.
10189 // Only 1 CPUDispatch function is allowed, this will make it go through
10190 // the redeclaration errors.
10191 if (NewMVType == MultiVersionKind::CPUDispatch &&
10192 CurFD->hasAttr<CPUDispatchAttr>()) {
10193 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10195 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10196 NewCPUDisp->cpus_begin(),
10197 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10198 return Cur->getName() == New->getName();
10200 NewFD->setIsMultiVersion();
10201 Redeclaration = true;
10206 // If the declarations don't match, this is an error condition.
10207 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10208 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10209 NewFD->setInvalidDecl();
10212 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10214 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10216 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10217 NewCPUSpec->cpus_begin(),
10218 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10219 return Cur->getName() == New->getName();
10221 NewFD->setIsMultiVersion();
10222 Redeclaration = true;
10227 // Only 1 version of CPUSpecific is allowed for each CPU.
10228 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10229 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10230 if (CurII == NewII) {
10231 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10233 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10234 NewFD->setInvalidDecl();
10240 // If the two decls aren't the same MVType, there is no possible error
10245 // Else, this is simply a non-redecl case. Checking the 'value' is only
10246 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10247 // handled in the attribute adding step.
10248 if (NewMVType == MultiVersionKind::Target &&
10249 CheckMultiVersionValue(S, NewFD)) {
10250 NewFD->setInvalidDecl();
10254 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10255 !OldFD->isMultiVersion(), NewMVType)) {
10256 NewFD->setInvalidDecl();
10260 // Permit forward declarations in the case where these two are compatible.
10261 if (!OldFD->isMultiVersion()) {
10262 OldFD->setIsMultiVersion();
10263 NewFD->setIsMultiVersion();
10264 Redeclaration = true;
10269 NewFD->setIsMultiVersion();
10270 Redeclaration = false;
10271 MergeTypeWithPrevious = false;
10278 /// Check the validity of a mulitversion function declaration.
10279 /// Also sets the multiversion'ness' of the function itself.
10281 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10283 /// Returns true if there was an error, false otherwise.
10284 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10285 bool &Redeclaration, NamedDecl *&OldDecl,
10286 bool &MergeTypeWithPrevious,
10287 LookupResult &Previous) {
10288 const auto *NewTA = NewFD->getAttr<TargetAttr>();
10289 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10290 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10292 // Mixing Multiversioning types is prohibited.
10293 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10294 (NewCPUDisp && NewCPUSpec)) {
10295 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10296 NewFD->setInvalidDecl();
10300 MultiVersionKind MVType = NewFD->getMultiVersionKind();
10302 // Main isn't allowed to become a multiversion function, however it IS
10303 // permitted to have 'main' be marked with the 'target' optimization hint.
10304 if (NewFD->isMain()) {
10305 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10306 MVType == MultiVersionKind::CPUDispatch ||
10307 MVType == MultiVersionKind::CPUSpecific) {
10308 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10309 NewFD->setInvalidDecl();
10315 if (!OldDecl || !OldDecl->getAsFunction() ||
10316 OldDecl->getDeclContext()->getRedeclContext() !=
10317 NewFD->getDeclContext()->getRedeclContext()) {
10318 // If there's no previous declaration, AND this isn't attempting to cause
10319 // multiversioning, this isn't an error condition.
10320 if (MVType == MultiVersionKind::None)
10322 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10325 FunctionDecl *OldFD = OldDecl->getAsFunction();
10327 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10330 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10331 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10332 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10333 NewFD->setInvalidDecl();
10337 // Handle the target potentially causes multiversioning case.
10338 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10339 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10340 Redeclaration, OldDecl,
10341 MergeTypeWithPrevious, Previous);
10343 // At this point, we have a multiversion function decl (in OldFD) AND an
10344 // appropriate attribute in the current function decl. Resolve that these are
10345 // still compatible with previous declarations.
10346 return CheckMultiVersionAdditionalDecl(
10347 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10348 OldDecl, MergeTypeWithPrevious, Previous);
10351 /// Perform semantic checking of a new function declaration.
10353 /// Performs semantic analysis of the new function declaration
10354 /// NewFD. This routine performs all semantic checking that does not
10355 /// require the actual declarator involved in the declaration, and is
10356 /// used both for the declaration of functions as they are parsed
10357 /// (called via ActOnDeclarator) and for the declaration of functions
10358 /// that have been instantiated via C++ template instantiation (called
10359 /// via InstantiateDecl).
10361 /// \param IsMemberSpecialization whether this new function declaration is
10362 /// a member specialization (that replaces any definition provided by the
10363 /// previous declaration).
10365 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10367 /// \returns true if the function declaration is a redeclaration.
10368 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10369 LookupResult &Previous,
10370 bool IsMemberSpecialization) {
10371 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10372 "Variably modified return types are not handled here");
10374 // Determine whether the type of this function should be merged with
10375 // a previous visible declaration. This never happens for functions in C++,
10376 // and always happens in C if the previous declaration was visible.
10377 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10378 !Previous.isShadowed();
10380 bool Redeclaration = false;
10381 NamedDecl *OldDecl = nullptr;
10382 bool MayNeedOverloadableChecks = false;
10384 // Merge or overload the declaration with an existing declaration of
10385 // the same name, if appropriate.
10386 if (!Previous.empty()) {
10387 // Determine whether NewFD is an overload of PrevDecl or
10388 // a declaration that requires merging. If it's an overload,
10389 // there's no more work to do here; we'll just add the new
10390 // function to the scope.
10391 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10392 NamedDecl *Candidate = Previous.getRepresentativeDecl();
10393 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10394 Redeclaration = true;
10395 OldDecl = Candidate;
10398 MayNeedOverloadableChecks = true;
10399 switch (CheckOverload(S, NewFD, Previous, OldDecl,
10400 /*NewIsUsingDecl*/ false)) {
10402 Redeclaration = true;
10405 case Ovl_NonFunction:
10406 Redeclaration = true;
10410 Redeclaration = false;
10416 // Check for a previous extern "C" declaration with this name.
10417 if (!Redeclaration &&
10418 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10419 if (!Previous.empty()) {
10420 // This is an extern "C" declaration with the same name as a previous
10421 // declaration, and thus redeclares that entity...
10422 Redeclaration = true;
10423 OldDecl = Previous.getFoundDecl();
10424 MergeTypeWithPrevious = false;
10426 // ... except in the presence of __attribute__((overloadable)).
10427 if (OldDecl->hasAttr<OverloadableAttr>() ||
10428 NewFD->hasAttr<OverloadableAttr>()) {
10429 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10430 MayNeedOverloadableChecks = true;
10431 Redeclaration = false;
10438 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10439 MergeTypeWithPrevious, Previous))
10440 return Redeclaration;
10442 // C++11 [dcl.constexpr]p8:
10443 // A constexpr specifier for a non-static member function that is not
10444 // a constructor declares that member function to be const.
10446 // This needs to be delayed until we know whether this is an out-of-line
10447 // definition of a static member function.
10449 // This rule is not present in C++1y, so we produce a backwards
10450 // compatibility warning whenever it happens in C++11.
10451 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10452 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10453 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10454 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10455 CXXMethodDecl *OldMD = nullptr;
10457 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10458 if (!OldMD || !OldMD->isStatic()) {
10459 const FunctionProtoType *FPT =
10460 MD->getType()->castAs<FunctionProtoType>();
10461 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10462 EPI.TypeQuals.addConst();
10463 MD->setType(Context.getFunctionType(FPT->getReturnType(),
10464 FPT->getParamTypes(), EPI));
10466 // Warn that we did this, if we're not performing template instantiation.
10467 // In that case, we'll have warned already when the template was defined.
10468 if (!inTemplateInstantiation()) {
10469 SourceLocation AddConstLoc;
10470 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10471 .IgnoreParens().getAs<FunctionTypeLoc>())
10472 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10474 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10475 << FixItHint::CreateInsertion(AddConstLoc, " const");
10480 if (Redeclaration) {
10481 // NewFD and OldDecl represent declarations that need to be
10483 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10484 NewFD->setInvalidDecl();
10485 return Redeclaration;
10489 Previous.addDecl(OldDecl);
10491 if (FunctionTemplateDecl *OldTemplateDecl =
10492 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10493 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10494 FunctionTemplateDecl *NewTemplateDecl
10495 = NewFD->getDescribedFunctionTemplate();
10496 assert(NewTemplateDecl && "Template/non-template mismatch");
10498 // The call to MergeFunctionDecl above may have created some state in
10499 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10500 // can add it as a redeclaration.
10501 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10503 NewFD->setPreviousDeclaration(OldFD);
10504 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10505 if (NewFD->isCXXClassMember()) {
10506 NewFD->setAccess(OldTemplateDecl->getAccess());
10507 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10510 // If this is an explicit specialization of a member that is a function
10511 // template, mark it as a member specialization.
10512 if (IsMemberSpecialization &&
10513 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10514 NewTemplateDecl->setMemberSpecialization();
10515 assert(OldTemplateDecl->isMemberSpecialization());
10516 // Explicit specializations of a member template do not inherit deleted
10517 // status from the parent member template that they are specializing.
10518 if (OldFD->isDeleted()) {
10519 // FIXME: This assert will not hold in the presence of modules.
10520 assert(OldFD->getCanonicalDecl() == OldFD);
10521 // FIXME: We need an update record for this AST mutation.
10522 OldFD->setDeletedAsWritten(false);
10527 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10528 auto *OldFD = cast<FunctionDecl>(OldDecl);
10529 // This needs to happen first so that 'inline' propagates.
10530 NewFD->setPreviousDeclaration(OldFD);
10531 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10532 if (NewFD->isCXXClassMember())
10533 NewFD->setAccess(OldFD->getAccess());
10536 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10537 !NewFD->getAttr<OverloadableAttr>()) {
10538 assert((Previous.empty() ||
10539 llvm::any_of(Previous,
10540 [](const NamedDecl *ND) {
10541 return ND->hasAttr<OverloadableAttr>();
10543 "Non-redecls shouldn't happen without overloadable present");
10545 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10546 const auto *FD = dyn_cast<FunctionDecl>(ND);
10547 return FD && !FD->hasAttr<OverloadableAttr>();
10550 if (OtherUnmarkedIter != Previous.end()) {
10551 Diag(NewFD->getLocation(),
10552 diag::err_attribute_overloadable_multiple_unmarked_overloads);
10553 Diag((*OtherUnmarkedIter)->getLocation(),
10554 diag::note_attribute_overloadable_prev_overload)
10557 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10561 // Semantic checking for this function declaration (in isolation).
10563 if (getLangOpts().CPlusPlus) {
10564 // C++-specific checks.
10565 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10566 CheckConstructor(Constructor);
10567 } else if (CXXDestructorDecl *Destructor =
10568 dyn_cast<CXXDestructorDecl>(NewFD)) {
10569 CXXRecordDecl *Record = Destructor->getParent();
10570 QualType ClassType = Context.getTypeDeclType(Record);
10572 // FIXME: Shouldn't we be able to perform this check even when the class
10573 // type is dependent? Both gcc and edg can handle that.
10574 if (!ClassType->isDependentType()) {
10575 DeclarationName Name
10576 = Context.DeclarationNames.getCXXDestructorName(
10577 Context.getCanonicalType(ClassType));
10578 if (NewFD->getDeclName() != Name) {
10579 Diag(NewFD->getLocation(), diag::err_destructor_name);
10580 NewFD->setInvalidDecl();
10581 return Redeclaration;
10584 } else if (CXXConversionDecl *Conversion
10585 = dyn_cast<CXXConversionDecl>(NewFD)) {
10586 ActOnConversionDeclarator(Conversion);
10587 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10588 if (auto *TD = Guide->getDescribedFunctionTemplate())
10589 CheckDeductionGuideTemplate(TD);
10591 // A deduction guide is not on the list of entities that can be
10592 // explicitly specialized.
10593 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10594 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10595 << /*explicit specialization*/ 1;
10598 // Find any virtual functions that this function overrides.
10599 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10600 if (!Method->isFunctionTemplateSpecialization() &&
10601 !Method->getDescribedFunctionTemplate() &&
10602 Method->isCanonicalDecl()) {
10603 if (AddOverriddenMethods(Method->getParent(), Method)) {
10604 // If the function was marked as "static", we have a problem.
10605 if (NewFD->getStorageClass() == SC_Static) {
10606 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10610 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10611 // C++2a [class.virtual]p6
10612 // A virtual method shall not have a requires-clause.
10613 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10614 diag::err_constrained_virtual_method);
10616 if (Method->isStatic())
10617 checkThisInStaticMemberFunctionType(Method);
10620 // Extra checking for C++ overloaded operators (C++ [over.oper]).
10621 if (NewFD->isOverloadedOperator() &&
10622 CheckOverloadedOperatorDeclaration(NewFD)) {
10623 NewFD->setInvalidDecl();
10624 return Redeclaration;
10627 // Extra checking for C++0x literal operators (C++0x [over.literal]).
10628 if (NewFD->getLiteralIdentifier() &&
10629 CheckLiteralOperatorDeclaration(NewFD)) {
10630 NewFD->setInvalidDecl();
10631 return Redeclaration;
10634 // In C++, check default arguments now that we have merged decls. Unless
10635 // the lexical context is the class, because in this case this is done
10636 // during delayed parsing anyway.
10637 if (!CurContext->isRecord())
10638 CheckCXXDefaultArguments(NewFD);
10640 // If this function declares a builtin function, check the type of this
10641 // declaration against the expected type for the builtin.
10642 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10643 ASTContext::GetBuiltinTypeError Error;
10644 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10645 QualType T = Context.GetBuiltinType(BuiltinID, Error);
10646 // If the type of the builtin differs only in its exception
10647 // specification, that's OK.
10648 // FIXME: If the types do differ in this way, it would be better to
10649 // retain the 'noexcept' form of the type.
10651 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10653 // The type of this function differs from the type of the builtin,
10654 // so forget about the builtin entirely.
10655 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10658 // If this function is declared as being extern "C", then check to see if
10659 // the function returns a UDT (class, struct, or union type) that is not C
10660 // compatible, and if it does, warn the user.
10661 // But, issue any diagnostic on the first declaration only.
10662 if (Previous.empty() && NewFD->isExternC()) {
10663 QualType R = NewFD->getReturnType();
10664 if (R->isIncompleteType() && !R->isVoidType())
10665 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10667 else if (!R.isPODType(Context) && !R->isVoidType() &&
10668 !R->isObjCObjectPointerType())
10669 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10672 // C++1z [dcl.fct]p6:
10673 // [...] whether the function has a non-throwing exception-specification
10674 // [is] part of the function type
10676 // This results in an ABI break between C++14 and C++17 for functions whose
10677 // declared type includes an exception-specification in a parameter or
10678 // return type. (Exception specifications on the function itself are OK in
10679 // most cases, and exception specifications are not permitted in most other
10680 // contexts where they could make it into a mangling.)
10681 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10682 auto HasNoexcept = [&](QualType T) -> bool {
10683 // Strip off declarator chunks that could be between us and a function
10684 // type. We don't need to look far, exception specifications are very
10685 // restricted prior to C++17.
10686 if (auto *RT = T->getAs<ReferenceType>())
10687 T = RT->getPointeeType();
10688 else if (T->isAnyPointerType())
10689 T = T->getPointeeType();
10690 else if (auto *MPT = T->getAs<MemberPointerType>())
10691 T = MPT->getPointeeType();
10692 if (auto *FPT = T->getAs<FunctionProtoType>())
10693 if (FPT->isNothrow())
10698 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10699 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10700 for (QualType T : FPT->param_types())
10701 AnyNoexcept |= HasNoexcept(T);
10703 Diag(NewFD->getLocation(),
10704 diag::warn_cxx17_compat_exception_spec_in_signature)
10708 if (!Redeclaration && LangOpts.CUDA)
10709 checkCUDATargetOverload(NewFD, Previous);
10711 return Redeclaration;
10714 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10715 // C++11 [basic.start.main]p3:
10716 // A program that [...] declares main to be inline, static or
10717 // constexpr is ill-formed.
10718 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
10719 // appear in a declaration of main.
10720 // static main is not an error under C99, but we should warn about it.
10721 // We accept _Noreturn main as an extension.
10722 if (FD->getStorageClass() == SC_Static)
10723 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10724 ? diag::err_static_main : diag::warn_static_main)
10725 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10726 if (FD->isInlineSpecified())
10727 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10728 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10729 if (DS.isNoreturnSpecified()) {
10730 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10731 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10732 Diag(NoreturnLoc, diag::ext_noreturn_main);
10733 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10734 << FixItHint::CreateRemoval(NoreturnRange);
10736 if (FD->isConstexpr()) {
10737 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10738 << FD->isConsteval()
10739 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10740 FD->setConstexprKind(CSK_unspecified);
10743 if (getLangOpts().OpenCL) {
10744 Diag(FD->getLocation(), diag::err_opencl_no_main)
10745 << FD->hasAttr<OpenCLKernelAttr>();
10746 FD->setInvalidDecl();
10750 QualType T = FD->getType();
10751 assert(T->isFunctionType() && "function decl is not of function type");
10752 const FunctionType* FT = T->castAs<FunctionType>();
10754 // Set default calling convention for main()
10755 if (FT->getCallConv() != CC_C) {
10756 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10757 FD->setType(QualType(FT, 0));
10758 T = Context.getCanonicalType(FD->getType());
10761 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10762 // In C with GNU extensions we allow main() to have non-integer return
10763 // type, but we should warn about the extension, and we disable the
10764 // implicit-return-zero rule.
10766 // GCC in C mode accepts qualified 'int'.
10767 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10768 FD->setHasImplicitReturnZero(true);
10770 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10771 SourceRange RTRange = FD->getReturnTypeSourceRange();
10772 if (RTRange.isValid())
10773 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10774 << FixItHint::CreateReplacement(RTRange, "int");
10777 // In C and C++, main magically returns 0 if you fall off the end;
10778 // set the flag which tells us that.
10779 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10781 // All the standards say that main() should return 'int'.
10782 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10783 FD->setHasImplicitReturnZero(true);
10785 // Otherwise, this is just a flat-out error.
10786 SourceRange RTRange = FD->getReturnTypeSourceRange();
10787 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10788 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10790 FD->setInvalidDecl(true);
10794 // Treat protoless main() as nullary.
10795 if (isa<FunctionNoProtoType>(FT)) return;
10797 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10798 unsigned nparams = FTP->getNumParams();
10799 assert(FD->getNumParams() == nparams);
10801 bool HasExtraParameters = (nparams > 3);
10803 if (FTP->isVariadic()) {
10804 Diag(FD->getLocation(), diag::ext_variadic_main);
10805 // FIXME: if we had information about the location of the ellipsis, we
10806 // could add a FixIt hint to remove it as a parameter.
10809 // Darwin passes an undocumented fourth argument of type char**. If
10810 // other platforms start sprouting these, the logic below will start
10812 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10813 HasExtraParameters = false;
10815 if (HasExtraParameters) {
10816 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10817 FD->setInvalidDecl(true);
10821 // FIXME: a lot of the following diagnostics would be improved
10822 // if we had some location information about types.
10825 Context.getPointerType(Context.getPointerType(Context.CharTy));
10826 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10828 for (unsigned i = 0; i < nparams; ++i) {
10829 QualType AT = FTP->getParamType(i);
10831 bool mismatch = true;
10833 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10835 else if (Expected[i] == CharPP) {
10836 // As an extension, the following forms are okay:
10838 // char const * const *
10841 QualifierCollector qs;
10842 const PointerType* PT;
10843 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10844 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10845 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10848 mismatch = !qs.empty();
10853 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10854 // TODO: suggest replacing given type with expected type
10855 FD->setInvalidDecl(true);
10859 if (nparams == 1 && !FD->isInvalidDecl()) {
10860 Diag(FD->getLocation(), diag::warn_main_one_arg);
10863 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10864 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10865 FD->setInvalidDecl();
10869 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10870 QualType T = FD->getType();
10871 assert(T->isFunctionType() && "function decl is not of function type");
10872 const FunctionType *FT = T->castAs<FunctionType>();
10874 // Set an implicit return of 'zero' if the function can return some integral,
10875 // enumeration, pointer or nullptr type.
10876 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10877 FT->getReturnType()->isAnyPointerType() ||
10878 FT->getReturnType()->isNullPtrType())
10879 // DllMain is exempt because a return value of zero means it failed.
10880 if (FD->getName() != "DllMain")
10881 FD->setHasImplicitReturnZero(true);
10883 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10884 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10885 FD->setInvalidDecl();
10889 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10890 // FIXME: Need strict checking. In C89, we need to check for
10891 // any assignment, increment, decrement, function-calls, or
10892 // commas outside of a sizeof. In C99, it's the same list,
10893 // except that the aforementioned are allowed in unevaluated
10894 // expressions. Everything else falls under the
10895 // "may accept other forms of constant expressions" exception.
10896 // (We never end up here for C++, so the constant expression
10897 // rules there don't matter.)
10898 const Expr *Culprit;
10899 if (Init->isConstantInitializer(Context, false, &Culprit))
10901 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10902 << Culprit->getSourceRange();
10907 // Visits an initialization expression to see if OrigDecl is evaluated in
10908 // its own initialization and throws a warning if it does.
10909 class SelfReferenceChecker
10910 : public EvaluatedExprVisitor<SelfReferenceChecker> {
10915 bool isReferenceType;
10918 llvm::SmallVector<unsigned, 4> InitFieldIndex;
10921 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10923 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10924 S(S), OrigDecl(OrigDecl) {
10926 isRecordType = false;
10927 isReferenceType = false;
10928 isInitList = false;
10929 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10930 isPODType = VD->getType().isPODType(S.Context);
10931 isRecordType = VD->getType()->isRecordType();
10932 isReferenceType = VD->getType()->isReferenceType();
10936 // For most expressions, just call the visitor. For initializer lists,
10937 // track the index of the field being initialized since fields are
10938 // initialized in order allowing use of previously initialized fields.
10939 void CheckExpr(Expr *E) {
10940 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10946 // Track and increment the index here.
10948 InitFieldIndex.push_back(0);
10949 for (auto Child : InitList->children()) {
10950 CheckExpr(cast<Expr>(Child));
10951 ++InitFieldIndex.back();
10953 InitFieldIndex.pop_back();
10956 // Returns true if MemberExpr is checked and no further checking is needed.
10957 // Returns false if additional checking is required.
10958 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10959 llvm::SmallVector<FieldDecl*, 4> Fields;
10961 bool ReferenceField = false;
10963 // Get the field members used.
10964 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10965 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10968 Fields.push_back(FD);
10969 if (FD->getType()->isReferenceType())
10970 ReferenceField = true;
10971 Base = ME->getBase()->IgnoreParenImpCasts();
10974 // Keep checking only if the base Decl is the same.
10975 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10976 if (!DRE || DRE->getDecl() != OrigDecl)
10979 // A reference field can be bound to an unininitialized field.
10980 if (CheckReference && !ReferenceField)
10983 // Convert FieldDecls to their index number.
10984 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10985 for (const FieldDecl *I : llvm::reverse(Fields))
10986 UsedFieldIndex.push_back(I->getFieldIndex());
10988 // See if a warning is needed by checking the first difference in index
10989 // numbers. If field being used has index less than the field being
10990 // initialized, then the use is safe.
10991 for (auto UsedIter = UsedFieldIndex.begin(),
10992 UsedEnd = UsedFieldIndex.end(),
10993 OrigIter = InitFieldIndex.begin(),
10994 OrigEnd = InitFieldIndex.end();
10995 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10996 if (*UsedIter < *OrigIter)
10998 if (*UsedIter > *OrigIter)
11002 // TODO: Add a different warning which will print the field names.
11003 HandleDeclRefExpr(DRE);
11007 // For most expressions, the cast is directly above the DeclRefExpr.
11008 // For conditional operators, the cast can be outside the conditional
11009 // operator if both expressions are DeclRefExpr's.
11010 void HandleValue(Expr *E) {
11011 E = E->IgnoreParens();
11012 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11013 HandleDeclRefExpr(DRE);
11017 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11018 Visit(CO->getCond());
11019 HandleValue(CO->getTrueExpr());
11020 HandleValue(CO->getFalseExpr());
11024 if (BinaryConditionalOperator *BCO =
11025 dyn_cast<BinaryConditionalOperator>(E)) {
11026 Visit(BCO->getCond());
11027 HandleValue(BCO->getFalseExpr());
11031 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11032 HandleValue(OVE->getSourceExpr());
11036 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11037 if (BO->getOpcode() == BO_Comma) {
11038 Visit(BO->getLHS());
11039 HandleValue(BO->getRHS());
11044 if (isa<MemberExpr>(E)) {
11046 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11047 false /*CheckReference*/))
11051 Expr *Base = E->IgnoreParenImpCasts();
11052 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11053 // Check for static member variables and don't warn on them.
11054 if (!isa<FieldDecl>(ME->getMemberDecl()))
11056 Base = ME->getBase()->IgnoreParenImpCasts();
11058 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11059 HandleDeclRefExpr(DRE);
11066 // Reference types not handled in HandleValue are handled here since all
11067 // uses of references are bad, not just r-value uses.
11068 void VisitDeclRefExpr(DeclRefExpr *E) {
11069 if (isReferenceType)
11070 HandleDeclRefExpr(E);
11073 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11074 if (E->getCastKind() == CK_LValueToRValue) {
11075 HandleValue(E->getSubExpr());
11079 Inherited::VisitImplicitCastExpr(E);
11082 void VisitMemberExpr(MemberExpr *E) {
11084 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11088 // Don't warn on arrays since they can be treated as pointers.
11089 if (E->getType()->canDecayToPointerType()) return;
11091 // Warn when a non-static method call is followed by non-static member
11092 // field accesses, which is followed by a DeclRefExpr.
11093 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11094 bool Warn = (MD && !MD->isStatic());
11095 Expr *Base = E->getBase()->IgnoreParenImpCasts();
11096 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11097 if (!isa<FieldDecl>(ME->getMemberDecl()))
11099 Base = ME->getBase()->IgnoreParenImpCasts();
11102 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11104 HandleDeclRefExpr(DRE);
11108 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11109 // Visit that expression.
11113 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11114 Expr *Callee = E->getCallee();
11116 if (isa<UnresolvedLookupExpr>(Callee))
11117 return Inherited::VisitCXXOperatorCallExpr(E);
11120 for (auto Arg: E->arguments())
11121 HandleValue(Arg->IgnoreParenImpCasts());
11124 void VisitUnaryOperator(UnaryOperator *E) {
11125 // For POD record types, addresses of its own members are well-defined.
11126 if (E->getOpcode() == UO_AddrOf && isRecordType &&
11127 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11129 HandleValue(E->getSubExpr());
11133 if (E->isIncrementDecrementOp()) {
11134 HandleValue(E->getSubExpr());
11138 Inherited::VisitUnaryOperator(E);
11141 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11143 void VisitCXXConstructExpr(CXXConstructExpr *E) {
11144 if (E->getConstructor()->isCopyConstructor()) {
11145 Expr *ArgExpr = E->getArg(0);
11146 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11147 if (ILE->getNumInits() == 1)
11148 ArgExpr = ILE->getInit(0);
11149 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11150 if (ICE->getCastKind() == CK_NoOp)
11151 ArgExpr = ICE->getSubExpr();
11152 HandleValue(ArgExpr);
11155 Inherited::VisitCXXConstructExpr(E);
11158 void VisitCallExpr(CallExpr *E) {
11159 // Treat std::move as a use.
11160 if (E->isCallToStdMove()) {
11161 HandleValue(E->getArg(0));
11165 Inherited::VisitCallExpr(E);
11168 void VisitBinaryOperator(BinaryOperator *E) {
11169 if (E->isCompoundAssignmentOp()) {
11170 HandleValue(E->getLHS());
11171 Visit(E->getRHS());
11175 Inherited::VisitBinaryOperator(E);
11178 // A custom visitor for BinaryConditionalOperator is needed because the
11179 // regular visitor would check the condition and true expression separately
11180 // but both point to the same place giving duplicate diagnostics.
11181 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11182 Visit(E->getCond());
11183 Visit(E->getFalseExpr());
11186 void HandleDeclRefExpr(DeclRefExpr *DRE) {
11187 Decl* ReferenceDecl = DRE->getDecl();
11188 if (OrigDecl != ReferenceDecl) return;
11190 if (isReferenceType) {
11191 diag = diag::warn_uninit_self_reference_in_reference_init;
11192 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11193 diag = diag::warn_static_self_reference_in_init;
11194 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11195 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11196 DRE->getDecl()->getType()->isRecordType()) {
11197 diag = diag::warn_uninit_self_reference_in_init;
11199 // Local variables will be handled by the CFG analysis.
11203 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11205 << DRE->getDecl() << OrigDecl->getLocation()
11206 << DRE->getSourceRange());
11210 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11211 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11213 // Parameters arguments are occassionially constructed with itself,
11214 // for instance, in recursive functions. Skip them.
11215 if (isa<ParmVarDecl>(OrigDecl))
11218 E = E->IgnoreParens();
11220 // Skip checking T a = a where T is not a record or reference type.
11221 // Doing so is a way to silence uninitialized warnings.
11222 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11223 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11224 if (ICE->getCastKind() == CK_LValueToRValue)
11225 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11226 if (DRE->getDecl() == OrigDecl)
11229 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11231 } // end anonymous namespace
11234 // Simple wrapper to add the name of a variable or (if no variable is
11235 // available) a DeclarationName into a diagnostic.
11236 struct VarDeclOrName {
11238 DeclarationName Name;
11240 friend const Sema::SemaDiagnosticBuilder &
11241 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11242 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11245 } // end anonymous namespace
11247 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11248 DeclarationName Name, QualType Type,
11249 TypeSourceInfo *TSI,
11250 SourceRange Range, bool DirectInit,
11252 bool IsInitCapture = !VDecl;
11253 assert((!VDecl || !VDecl->isInitCapture()) &&
11254 "init captures are expected to be deduced prior to initialization");
11256 VarDeclOrName VN{VDecl, Name};
11258 DeducedType *Deduced = Type->getContainedDeducedType();
11259 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11261 // C++11 [dcl.spec.auto]p3
11263 assert(VDecl && "no init for init capture deduction?");
11265 // Except for class argument deduction, and then for an initializing
11266 // declaration only, i.e. no static at class scope or extern.
11267 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11268 VDecl->hasExternalStorage() ||
11269 VDecl->isStaticDataMember()) {
11270 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11271 << VDecl->getDeclName() << Type;
11276 ArrayRef<Expr*> DeduceInits;
11278 DeduceInits = Init;
11281 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11282 DeduceInits = PL->exprs();
11285 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11286 assert(VDecl && "non-auto type for init capture deduction?");
11287 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11288 InitializationKind Kind = InitializationKind::CreateForInit(
11289 VDecl->getLocation(), DirectInit, Init);
11290 // FIXME: Initialization should not be taking a mutable list of inits.
11291 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11292 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11297 if (auto *IL = dyn_cast<InitListExpr>(Init))
11298 DeduceInits = IL->inits();
11301 // Deduction only works if we have exactly one source expression.
11302 if (DeduceInits.empty()) {
11303 // It isn't possible to write this directly, but it is possible to
11304 // end up in this situation with "auto x(some_pack...);"
11305 Diag(Init->getBeginLoc(), IsInitCapture
11306 ? diag::err_init_capture_no_expression
11307 : diag::err_auto_var_init_no_expression)
11308 << VN << Type << Range;
11312 if (DeduceInits.size() > 1) {
11313 Diag(DeduceInits[1]->getBeginLoc(),
11314 IsInitCapture ? diag::err_init_capture_multiple_expressions
11315 : diag::err_auto_var_init_multiple_expressions)
11316 << VN << Type << Range;
11320 Expr *DeduceInit = DeduceInits[0];
11321 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11322 Diag(Init->getBeginLoc(), IsInitCapture
11323 ? diag::err_init_capture_paren_braces
11324 : diag::err_auto_var_init_paren_braces)
11325 << isa<InitListExpr>(Init) << VN << Type << Range;
11329 // Expressions default to 'id' when we're in a debugger.
11330 bool DefaultedAnyToId = false;
11331 if (getLangOpts().DebuggerCastResultToId &&
11332 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11333 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11334 if (Result.isInvalid()) {
11337 Init = Result.get();
11338 DefaultedAnyToId = true;
11341 // C++ [dcl.decomp]p1:
11342 // If the assignment-expression [...] has array type A and no ref-qualifier
11343 // is present, e has type cv A
11344 if (VDecl && isa<DecompositionDecl>(VDecl) &&
11345 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11346 DeduceInit->getType()->isConstantArrayType())
11347 return Context.getQualifiedType(DeduceInit->getType(),
11348 Type.getQualifiers());
11350 QualType DeducedType;
11351 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11352 if (!IsInitCapture)
11353 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11354 else if (isa<InitListExpr>(Init))
11355 Diag(Range.getBegin(),
11356 diag::err_init_capture_deduction_failure_from_init_list)
11358 << (DeduceInit->getType().isNull() ? TSI->getType()
11359 : DeduceInit->getType())
11360 << DeduceInit->getSourceRange();
11362 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11363 << VN << TSI->getType()
11364 << (DeduceInit->getType().isNull() ? TSI->getType()
11365 : DeduceInit->getType())
11366 << DeduceInit->getSourceRange();
11369 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11370 // 'id' instead of a specific object type prevents most of our usual
11372 // We only want to warn outside of template instantiations, though:
11373 // inside a template, the 'id' could have come from a parameter.
11374 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11375 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11376 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11377 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11380 return DeducedType;
11383 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11385 QualType DeducedType = deduceVarTypeFromInitializer(
11386 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11387 VDecl->getSourceRange(), DirectInit, Init);
11388 if (DeducedType.isNull()) {
11389 VDecl->setInvalidDecl();
11393 VDecl->setType(DeducedType);
11394 assert(VDecl->isLinkageValid());
11396 // In ARC, infer lifetime.
11397 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11398 VDecl->setInvalidDecl();
11400 if (getLangOpts().OpenCL)
11401 deduceOpenCLAddressSpace(VDecl);
11403 // If this is a redeclaration, check that the type we just deduced matches
11404 // the previously declared type.
11405 if (VarDecl *Old = VDecl->getPreviousDecl()) {
11406 // We never need to merge the type, because we cannot form an incomplete
11407 // array of auto, nor deduce such a type.
11408 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11411 // Check the deduced type is valid for a variable declaration.
11412 CheckVariableDeclarationType(VDecl);
11413 return VDecl->isInvalidDecl();
11416 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11417 SourceLocation Loc) {
11418 if (auto *CE = dyn_cast<ConstantExpr>(Init))
11419 Init = CE->getSubExpr();
11421 QualType InitType = Init->getType();
11422 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11423 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11424 "shouldn't be called if type doesn't have a non-trivial C struct");
11425 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11426 for (auto I : ILE->inits()) {
11427 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11428 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11430 SourceLocation SL = I->getExprLoc();
11431 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11436 if (isa<ImplicitValueInitExpr>(Init)) {
11437 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11438 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11441 // Assume all other explicit initializers involving copying some existing
11443 // TODO: ignore any explicit initializers where we can guarantee
11445 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11446 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11452 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11453 // Ignore unavailable fields. A field can be marked as unavailable explicitly
11454 // in the source code or implicitly by the compiler if it is in a union
11455 // defined in a system header and has non-trivial ObjC ownership
11456 // qualifications. We don't want those fields to participate in determining
11457 // whether the containing union is non-trivial.
11458 return FD->hasAttr<UnavailableAttr>();
11461 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11462 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11465 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11468 DiagNonTrivalCUnionDefaultInitializeVisitor(
11469 QualType OrigTy, SourceLocation OrigLoc,
11470 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11471 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11473 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11474 const FieldDecl *FD, bool InNonTrivialUnion) {
11475 if (const auto *AT = S.Context.getAsArrayType(QT))
11476 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11477 InNonTrivialUnion);
11478 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11481 void visitARCStrong(QualType QT, const FieldDecl *FD,
11482 bool InNonTrivialUnion) {
11483 if (InNonTrivialUnion)
11484 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11485 << 1 << 0 << QT << FD->getName();
11488 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11489 if (InNonTrivialUnion)
11490 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11491 << 1 << 0 << QT << FD->getName();
11494 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11495 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11496 if (RD->isUnion()) {
11497 if (OrigLoc.isValid()) {
11498 bool IsUnion = false;
11499 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11500 IsUnion = OrigRD->isUnion();
11501 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11502 << 0 << OrigTy << IsUnion << UseContext;
11503 // Reset OrigLoc so that this diagnostic is emitted only once.
11504 OrigLoc = SourceLocation();
11506 InNonTrivialUnion = true;
11509 if (InNonTrivialUnion)
11510 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11511 << 0 << 0 << QT.getUnqualifiedType() << "";
11513 for (const FieldDecl *FD : RD->fields())
11514 if (!shouldIgnoreForRecordTriviality(FD))
11515 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11518 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11520 // The non-trivial C union type or the struct/union type that contains a
11521 // non-trivial C union.
11523 SourceLocation OrigLoc;
11524 Sema::NonTrivialCUnionContext UseContext;
11528 struct DiagNonTrivalCUnionDestructedTypeVisitor
11529 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11531 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11533 DiagNonTrivalCUnionDestructedTypeVisitor(
11534 QualType OrigTy, SourceLocation OrigLoc,
11535 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11536 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11538 void visitWithKind(QualType::DestructionKind DK, QualType QT,
11539 const FieldDecl *FD, bool InNonTrivialUnion) {
11540 if (const auto *AT = S.Context.getAsArrayType(QT))
11541 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11542 InNonTrivialUnion);
11543 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11546 void visitARCStrong(QualType QT, const FieldDecl *FD,
11547 bool InNonTrivialUnion) {
11548 if (InNonTrivialUnion)
11549 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11550 << 1 << 1 << QT << FD->getName();
11553 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11554 if (InNonTrivialUnion)
11555 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11556 << 1 << 1 << QT << FD->getName();
11559 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11560 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11561 if (RD->isUnion()) {
11562 if (OrigLoc.isValid()) {
11563 bool IsUnion = false;
11564 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11565 IsUnion = OrigRD->isUnion();
11566 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11567 << 1 << OrigTy << IsUnion << UseContext;
11568 // Reset OrigLoc so that this diagnostic is emitted only once.
11569 OrigLoc = SourceLocation();
11571 InNonTrivialUnion = true;
11574 if (InNonTrivialUnion)
11575 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11576 << 0 << 1 << QT.getUnqualifiedType() << "";
11578 for (const FieldDecl *FD : RD->fields())
11579 if (!shouldIgnoreForRecordTriviality(FD))
11580 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11583 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11584 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11585 bool InNonTrivialUnion) {}
11587 // The non-trivial C union type or the struct/union type that contains a
11588 // non-trivial C union.
11590 SourceLocation OrigLoc;
11591 Sema::NonTrivialCUnionContext UseContext;
11595 struct DiagNonTrivalCUnionCopyVisitor
11596 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11597 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11599 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11600 Sema::NonTrivialCUnionContext UseContext,
11602 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11604 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11605 const FieldDecl *FD, bool InNonTrivialUnion) {
11606 if (const auto *AT = S.Context.getAsArrayType(QT))
11607 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11608 InNonTrivialUnion);
11609 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11612 void visitARCStrong(QualType QT, const FieldDecl *FD,
11613 bool InNonTrivialUnion) {
11614 if (InNonTrivialUnion)
11615 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11616 << 1 << 2 << QT << FD->getName();
11619 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11620 if (InNonTrivialUnion)
11621 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11622 << 1 << 2 << QT << FD->getName();
11625 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11626 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11627 if (RD->isUnion()) {
11628 if (OrigLoc.isValid()) {
11629 bool IsUnion = false;
11630 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11631 IsUnion = OrigRD->isUnion();
11632 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11633 << 2 << OrigTy << IsUnion << UseContext;
11634 // Reset OrigLoc so that this diagnostic is emitted only once.
11635 OrigLoc = SourceLocation();
11637 InNonTrivialUnion = true;
11640 if (InNonTrivialUnion)
11641 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11642 << 0 << 2 << QT.getUnqualifiedType() << "";
11644 for (const FieldDecl *FD : RD->fields())
11645 if (!shouldIgnoreForRecordTriviality(FD))
11646 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11649 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11650 const FieldDecl *FD, bool InNonTrivialUnion) {}
11651 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11652 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11653 bool InNonTrivialUnion) {}
11655 // The non-trivial C union type or the struct/union type that contains a
11656 // non-trivial C union.
11658 SourceLocation OrigLoc;
11659 Sema::NonTrivialCUnionContext UseContext;
11665 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11666 NonTrivialCUnionContext UseContext,
11667 unsigned NonTrivialKind) {
11668 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11669 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11670 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11671 "shouldn't be called if type doesn't have a non-trivial C union");
11673 if ((NonTrivialKind & NTCUK_Init) &&
11674 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11675 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11676 .visit(QT, nullptr, false);
11677 if ((NonTrivialKind & NTCUK_Destruct) &&
11678 QT.hasNonTrivialToPrimitiveDestructCUnion())
11679 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11680 .visit(QT, nullptr, false);
11681 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11682 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11683 .visit(QT, nullptr, false);
11686 /// AddInitializerToDecl - Adds the initializer Init to the
11687 /// declaration dcl. If DirectInit is true, this is C++ direct
11688 /// initialization rather than copy initialization.
11689 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11690 // If there is no declaration, there was an error parsing it. Just ignore
11691 // the initializer.
11692 if (!RealDecl || RealDecl->isInvalidDecl()) {
11693 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11697 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11698 // Pure-specifiers are handled in ActOnPureSpecifier.
11699 Diag(Method->getLocation(), diag::err_member_function_initialization)
11700 << Method->getDeclName() << Init->getSourceRange();
11701 Method->setInvalidDecl();
11705 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11707 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11708 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11709 RealDecl->setInvalidDecl();
11713 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11714 if (VDecl->getType()->isUndeducedType()) {
11715 // Attempt typo correction early so that the type of the init expression can
11716 // be deduced based on the chosen correction if the original init contains a
11718 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11719 if (!Res.isUsable()) {
11720 RealDecl->setInvalidDecl();
11725 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11729 // dllimport cannot be used on variable definitions.
11730 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11731 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11732 VDecl->setInvalidDecl();
11736 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11737 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11738 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11739 VDecl->setInvalidDecl();
11743 if (!VDecl->getType()->isDependentType()) {
11744 // A definition must end up with a complete type, which means it must be
11745 // complete with the restriction that an array type might be completed by
11746 // the initializer; note that later code assumes this restriction.
11747 QualType BaseDeclType = VDecl->getType();
11748 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11749 BaseDeclType = Array->getElementType();
11750 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11751 diag::err_typecheck_decl_incomplete_type)) {
11752 RealDecl->setInvalidDecl();
11756 // The variable can not have an abstract class type.
11757 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11758 diag::err_abstract_type_in_decl,
11759 AbstractVariableType))
11760 VDecl->setInvalidDecl();
11763 // If adding the initializer will turn this declaration into a definition,
11764 // and we already have a definition for this variable, diagnose or otherwise
11765 // handle the situation.
11767 if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11768 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11769 !VDecl->isThisDeclarationADemotedDefinition() &&
11770 checkVarDeclRedefinition(Def, VDecl))
11773 if (getLangOpts().CPlusPlus) {
11774 // C++ [class.static.data]p4
11775 // If a static data member is of const integral or const
11776 // enumeration type, its declaration in the class definition can
11777 // specify a constant-initializer which shall be an integral
11778 // constant expression (5.19). In that case, the member can appear
11779 // in integral constant expressions. The member shall still be
11780 // defined in a namespace scope if it is used in the program and the
11781 // namespace scope definition shall not contain an initializer.
11783 // We already performed a redefinition check above, but for static
11784 // data members we also need to check whether there was an in-class
11785 // declaration with an initializer.
11786 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11787 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11788 << VDecl->getDeclName();
11789 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11790 diag::note_previous_initializer)
11795 if (VDecl->hasLocalStorage())
11796 setFunctionHasBranchProtectedScope();
11798 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11799 VDecl->setInvalidDecl();
11804 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11805 // a kernel function cannot be initialized."
11806 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11807 Diag(VDecl->getLocation(), diag::err_local_cant_init);
11808 VDecl->setInvalidDecl();
11812 // Get the decls type and save a reference for later, since
11813 // CheckInitializerTypes may change it.
11814 QualType DclT = VDecl->getType(), SavT = DclT;
11816 // Expressions default to 'id' when we're in a debugger
11817 // and we are assigning it to a variable of Objective-C pointer type.
11818 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11819 Init->getType() == Context.UnknownAnyTy) {
11820 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11821 if (Result.isInvalid()) {
11822 VDecl->setInvalidDecl();
11825 Init = Result.get();
11828 // Perform the initialization.
11829 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11830 if (!VDecl->isInvalidDecl()) {
11831 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11832 InitializationKind Kind = InitializationKind::CreateForInit(
11833 VDecl->getLocation(), DirectInit, Init);
11835 MultiExprArg Args = Init;
11837 Args = MultiExprArg(CXXDirectInit->getExprs(),
11838 CXXDirectInit->getNumExprs());
11840 // Try to correct any TypoExprs in the initialization arguments.
11841 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11842 ExprResult Res = CorrectDelayedTyposInExpr(
11843 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11844 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11845 return Init.Failed() ? ExprError() : E;
11847 if (Res.isInvalid()) {
11848 VDecl->setInvalidDecl();
11849 } else if (Res.get() != Args[Idx]) {
11850 Args[Idx] = Res.get();
11853 if (VDecl->isInvalidDecl())
11856 InitializationSequence InitSeq(*this, Entity, Kind, Args,
11857 /*TopLevelOfInitList=*/false,
11858 /*TreatUnavailableAsInvalid=*/false);
11859 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11860 if (Result.isInvalid()) {
11861 VDecl->setInvalidDecl();
11865 Init = Result.getAs<Expr>();
11868 // Check for self-references within variable initializers.
11869 // Variables declared within a function/method body (except for references)
11870 // are handled by a dataflow analysis.
11871 // This is undefined behavior in C++, but valid in C.
11872 if (getLangOpts().CPlusPlus) {
11873 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11874 VDecl->getType()->isReferenceType()) {
11875 CheckSelfReference(*this, RealDecl, Init, DirectInit);
11879 // If the type changed, it means we had an incomplete type that was
11880 // completed by the initializer. For example:
11881 // int ary[] = { 1, 3, 5 };
11882 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11883 if (!VDecl->isInvalidDecl() && (DclT != SavT))
11884 VDecl->setType(DclT);
11886 if (!VDecl->isInvalidDecl()) {
11887 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11889 if (VDecl->hasAttr<BlocksAttr>())
11890 checkRetainCycles(VDecl, Init);
11892 // It is safe to assign a weak reference into a strong variable.
11893 // Although this code can still have problems:
11894 // id x = self.weakProp;
11895 // id y = self.weakProp;
11896 // we do not warn to warn spuriously when 'x' and 'y' are on separate
11897 // paths through the function. This should be revisited if
11898 // -Wrepeated-use-of-weak is made flow-sensitive.
11899 if (FunctionScopeInfo *FSI = getCurFunction())
11900 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11901 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11902 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11903 Init->getBeginLoc()))
11904 FSI->markSafeWeakUse(Init);
11907 // The initialization is usually a full-expression.
11909 // FIXME: If this is a braced initialization of an aggregate, it is not
11910 // an expression, and each individual field initializer is a separate
11911 // full-expression. For instance, in:
11913 // struct Temp { ~Temp(); };
11914 // struct S { S(Temp); };
11915 // struct T { S a, b; } t = { Temp(), Temp() }
11917 // we should destroy the first Temp before constructing the second.
11918 ExprResult Result =
11919 ActOnFinishFullExpr(Init, VDecl->getLocation(),
11920 /*DiscardedValue*/ false, VDecl->isConstexpr());
11921 if (Result.isInvalid()) {
11922 VDecl->setInvalidDecl();
11925 Init = Result.get();
11927 // Attach the initializer to the decl.
11928 VDecl->setInit(Init);
11930 if (VDecl->isLocalVarDecl()) {
11931 // Don't check the initializer if the declaration is malformed.
11932 if (VDecl->isInvalidDecl()) {
11935 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11936 // This is true even in C++ for OpenCL.
11937 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11938 CheckForConstantInitializer(Init, DclT);
11940 // Otherwise, C++ does not restrict the initializer.
11941 } else if (getLangOpts().CPlusPlus) {
11944 // C99 6.7.8p4: All the expressions in an initializer for an object that has
11945 // static storage duration shall be constant expressions or string literals.
11946 } else if (VDecl->getStorageClass() == SC_Static) {
11947 CheckForConstantInitializer(Init, DclT);
11949 // C89 is stricter than C99 for aggregate initializers.
11950 // C89 6.5.7p3: All the expressions [...] in an initializer list
11951 // for an object that has aggregate or union type shall be
11952 // constant expressions.
11953 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11954 isa<InitListExpr>(Init)) {
11955 const Expr *Culprit;
11956 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11957 Diag(Culprit->getExprLoc(),
11958 diag::ext_aggregate_init_not_constant)
11959 << Culprit->getSourceRange();
11963 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11964 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11965 if (VDecl->hasLocalStorage())
11966 BE->getBlockDecl()->setCanAvoidCopyToHeap();
11967 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11968 VDecl->getLexicalDeclContext()->isRecord()) {
11969 // This is an in-class initialization for a static data member, e.g.,
11972 // static const int value = 17;
11975 // C++ [class.mem]p4:
11976 // A member-declarator can contain a constant-initializer only
11977 // if it declares a static member (9.4) of const integral or
11978 // const enumeration type, see 9.4.2.
11980 // C++11 [class.static.data]p3:
11981 // If a non-volatile non-inline const static data member is of integral
11982 // or enumeration type, its declaration in the class definition can
11983 // specify a brace-or-equal-initializer in which every initializer-clause
11984 // that is an assignment-expression is a constant expression. A static
11985 // data member of literal type can be declared in the class definition
11986 // with the constexpr specifier; if so, its declaration shall specify a
11987 // brace-or-equal-initializer in which every initializer-clause that is
11988 // an assignment-expression is a constant expression.
11990 // Do nothing on dependent types.
11991 if (DclT->isDependentType()) {
11993 // Allow any 'static constexpr' members, whether or not they are of literal
11994 // type. We separately check that every constexpr variable is of literal
11996 } else if (VDecl->isConstexpr()) {
11998 // Require constness.
11999 } else if (!DclT.isConstQualified()) {
12000 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12001 << Init->getSourceRange();
12002 VDecl->setInvalidDecl();
12004 // We allow integer constant expressions in all cases.
12005 } else if (DclT->isIntegralOrEnumerationType()) {
12006 // Check whether the expression is a constant expression.
12007 SourceLocation Loc;
12008 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12009 // In C++11, a non-constexpr const static data member with an
12010 // in-class initializer cannot be volatile.
12011 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12012 else if (Init->isValueDependent())
12013 ; // Nothing to check.
12014 else if (Init->isIntegerConstantExpr(Context, &Loc))
12015 ; // Ok, it's an ICE!
12016 else if (Init->getType()->isScopedEnumeralType() &&
12017 Init->isCXX11ConstantExpr(Context))
12018 ; // Ok, it is a scoped-enum constant expression.
12019 else if (Init->isEvaluatable(Context)) {
12020 // If we can constant fold the initializer through heroics, accept it,
12021 // but report this as a use of an extension for -pedantic.
12022 Diag(Loc, diag::ext_in_class_initializer_non_constant)
12023 << Init->getSourceRange();
12025 // Otherwise, this is some crazy unknown case. Report the issue at the
12026 // location provided by the isIntegerConstantExpr failed check.
12027 Diag(Loc, diag::err_in_class_initializer_non_constant)
12028 << Init->getSourceRange();
12029 VDecl->setInvalidDecl();
12032 // We allow foldable floating-point constants as an extension.
12033 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12034 // In C++98, this is a GNU extension. In C++11, it is not, but we support
12035 // it anyway and provide a fixit to add the 'constexpr'.
12036 if (getLangOpts().CPlusPlus11) {
12037 Diag(VDecl->getLocation(),
12038 diag::ext_in_class_initializer_float_type_cxx11)
12039 << DclT << Init->getSourceRange();
12040 Diag(VDecl->getBeginLoc(),
12041 diag::note_in_class_initializer_float_type_cxx11)
12042 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12044 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12045 << DclT << Init->getSourceRange();
12047 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12048 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12049 << Init->getSourceRange();
12050 VDecl->setInvalidDecl();
12054 // Suggest adding 'constexpr' in C++11 for literal types.
12055 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12056 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12057 << DclT << Init->getSourceRange()
12058 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12059 VDecl->setConstexpr(true);
12062 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12063 << DclT << Init->getSourceRange();
12064 VDecl->setInvalidDecl();
12066 } else if (VDecl->isFileVarDecl()) {
12067 // In C, extern is typically used to avoid tentative definitions when
12068 // declaring variables in headers, but adding an intializer makes it a
12069 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12070 // In C++, extern is often used to give implictly static const variables
12071 // external linkage, so don't warn in that case. If selectany is present,
12072 // this might be header code intended for C and C++ inclusion, so apply the
12074 if (VDecl->getStorageClass() == SC_Extern &&
12075 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12076 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12077 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12078 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12079 Diag(VDecl->getLocation(), diag::warn_extern_init);
12081 // In Microsoft C++ mode, a const variable defined in namespace scope has
12082 // external linkage by default if the variable is declared with
12083 // __declspec(dllexport).
12084 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12085 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12086 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12087 VDecl->setStorageClass(SC_Extern);
12089 // C99 6.7.8p4. All file scoped initializers need to be constant.
12090 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12091 CheckForConstantInitializer(Init, DclT);
12094 QualType InitType = Init->getType();
12095 if (!InitType.isNull() &&
12096 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12097 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12098 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12100 // We will represent direct-initialization similarly to copy-initialization:
12101 // int x(1); -as-> int x = 1;
12102 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12104 // Clients that want to distinguish between the two forms, can check for
12105 // direct initializer using VarDecl::getInitStyle().
12106 // A major benefit is that clients that don't particularly care about which
12107 // exactly form was it (like the CodeGen) can handle both cases without
12108 // special case code.
12111 // The form of initialization (using parentheses or '=') is generally
12112 // insignificant, but does matter when the entity being initialized has a
12114 if (CXXDirectInit) {
12115 assert(DirectInit && "Call-style initializer must be direct init.");
12116 VDecl->setInitStyle(VarDecl::CallInit);
12117 } else if (DirectInit) {
12118 // This must be list-initialization. No other way is direct-initialization.
12119 VDecl->setInitStyle(VarDecl::ListInit);
12122 CheckCompleteVariableDeclaration(VDecl);
12125 /// ActOnInitializerError - Given that there was an error parsing an
12126 /// initializer for the given declaration, try to return to some form
12128 void Sema::ActOnInitializerError(Decl *D) {
12129 // Our main concern here is re-establishing invariants like "a
12130 // variable's type is either dependent or complete".
12131 if (!D || D->isInvalidDecl()) return;
12133 VarDecl *VD = dyn_cast<VarDecl>(D);
12136 // Bindings are not usable if we can't make sense of the initializer.
12137 if (auto *DD = dyn_cast<DecompositionDecl>(D))
12138 for (auto *BD : DD->bindings())
12139 BD->setInvalidDecl();
12141 // Auto types are meaningless if we can't make sense of the initializer.
12142 if (ParsingInitForAutoVars.count(D)) {
12143 D->setInvalidDecl();
12147 QualType Ty = VD->getType();
12148 if (Ty->isDependentType()) return;
12150 // Require a complete type.
12151 if (RequireCompleteType(VD->getLocation(),
12152 Context.getBaseElementType(Ty),
12153 diag::err_typecheck_decl_incomplete_type)) {
12154 VD->setInvalidDecl();
12158 // Require a non-abstract type.
12159 if (RequireNonAbstractType(VD->getLocation(), Ty,
12160 diag::err_abstract_type_in_decl,
12161 AbstractVariableType)) {
12162 VD->setInvalidDecl();
12166 // Don't bother complaining about constructors or destructors,
12170 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12171 // If there is no declaration, there was an error parsing it. Just ignore it.
12175 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12176 QualType Type = Var->getType();
12178 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12179 if (isa<DecompositionDecl>(RealDecl)) {
12180 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12181 Var->setInvalidDecl();
12185 if (Type->isUndeducedType() &&
12186 DeduceVariableDeclarationType(Var, false, nullptr))
12189 // C++11 [class.static.data]p3: A static data member can be declared with
12190 // the constexpr specifier; if so, its declaration shall specify
12191 // a brace-or-equal-initializer.
12192 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12193 // the definition of a variable [...] or the declaration of a static data
12195 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12196 !Var->isThisDeclarationADemotedDefinition()) {
12197 if (Var->isStaticDataMember()) {
12198 // C++1z removes the relevant rule; the in-class declaration is always
12199 // a definition there.
12200 if (!getLangOpts().CPlusPlus17 &&
12201 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12202 Diag(Var->getLocation(),
12203 diag::err_constexpr_static_mem_var_requires_init)
12204 << Var->getDeclName();
12205 Var->setInvalidDecl();
12209 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12210 Var->setInvalidDecl();
12215 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12217 if (!Var->isInvalidDecl() &&
12218 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12219 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12220 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12221 Var->setInvalidDecl();
12225 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12226 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12227 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12228 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12229 NTCUC_DefaultInitializedObject, NTCUK_Init);
12233 case VarDecl::Definition:
12234 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12237 // We have an out-of-line definition of a static data member
12238 // that has an in-class initializer, so we type-check this like
12243 case VarDecl::DeclarationOnly:
12244 // It's only a declaration.
12246 // Block scope. C99 6.7p7: If an identifier for an object is
12247 // declared with no linkage (C99 6.2.2p6), the type for the
12248 // object shall be complete.
12249 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12250 !Var->hasLinkage() && !Var->isInvalidDecl() &&
12251 RequireCompleteType(Var->getLocation(), Type,
12252 diag::err_typecheck_decl_incomplete_type))
12253 Var->setInvalidDecl();
12255 // Make sure that the type is not abstract.
12256 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12257 RequireNonAbstractType(Var->getLocation(), Type,
12258 diag::err_abstract_type_in_decl,
12259 AbstractVariableType))
12260 Var->setInvalidDecl();
12261 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12262 Var->getStorageClass() == SC_PrivateExtern) {
12263 Diag(Var->getLocation(), diag::warn_private_extern);
12264 Diag(Var->getLocation(), diag::note_private_extern);
12267 if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12268 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12269 ExternalDeclarations.push_back(Var);
12273 case VarDecl::TentativeDefinition:
12274 // File scope. C99 6.9.2p2: A declaration of an identifier for an
12275 // object that has file scope without an initializer, and without a
12276 // storage-class specifier or with the storage-class specifier "static",
12277 // constitutes a tentative definition. Note: A tentative definition with
12278 // external linkage is valid (C99 6.2.2p5).
12279 if (!Var->isInvalidDecl()) {
12280 if (const IncompleteArrayType *ArrayT
12281 = Context.getAsIncompleteArrayType(Type)) {
12282 if (RequireCompleteType(Var->getLocation(),
12283 ArrayT->getElementType(),
12284 diag::err_illegal_decl_array_incomplete_type))
12285 Var->setInvalidDecl();
12286 } else if (Var->getStorageClass() == SC_Static) {
12287 // C99 6.9.2p3: If the declaration of an identifier for an object is
12288 // a tentative definition and has internal linkage (C99 6.2.2p3), the
12289 // declared type shall not be an incomplete type.
12290 // NOTE: code such as the following
12291 // static struct s;
12292 // struct s { int a; };
12293 // is accepted by gcc. Hence here we issue a warning instead of
12294 // an error and we do not invalidate the static declaration.
12295 // NOTE: to avoid multiple warnings, only check the first declaration.
12296 if (Var->isFirstDecl())
12297 RequireCompleteType(Var->getLocation(), Type,
12298 diag::ext_typecheck_decl_incomplete_type);
12302 // Record the tentative definition; we're done.
12303 if (!Var->isInvalidDecl())
12304 TentativeDefinitions.push_back(Var);
12308 // Provide a specific diagnostic for uninitialized variable
12309 // definitions with incomplete array type.
12310 if (Type->isIncompleteArrayType()) {
12311 Diag(Var->getLocation(),
12312 diag::err_typecheck_incomplete_array_needs_initializer);
12313 Var->setInvalidDecl();
12317 // Provide a specific diagnostic for uninitialized variable
12318 // definitions with reference type.
12319 if (Type->isReferenceType()) {
12320 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12321 << Var->getDeclName()
12322 << SourceRange(Var->getLocation(), Var->getLocation());
12323 Var->setInvalidDecl();
12327 // Do not attempt to type-check the default initializer for a
12328 // variable with dependent type.
12329 if (Type->isDependentType())
12332 if (Var->isInvalidDecl())
12335 if (!Var->hasAttr<AliasAttr>()) {
12336 if (RequireCompleteType(Var->getLocation(),
12337 Context.getBaseElementType(Type),
12338 diag::err_typecheck_decl_incomplete_type)) {
12339 Var->setInvalidDecl();
12346 // The variable can not have an abstract class type.
12347 if (RequireNonAbstractType(Var->getLocation(), Type,
12348 diag::err_abstract_type_in_decl,
12349 AbstractVariableType)) {
12350 Var->setInvalidDecl();
12354 // Check for jumps past the implicit initializer. C++0x
12355 // clarifies that this applies to a "variable with automatic
12356 // storage duration", not a "local variable".
12357 // C++11 [stmt.dcl]p3
12358 // A program that jumps from a point where a variable with automatic
12359 // storage duration is not in scope to a point where it is in scope is
12360 // ill-formed unless the variable has scalar type, class type with a
12361 // trivial default constructor and a trivial destructor, a cv-qualified
12362 // version of one of these types, or an array of one of the preceding
12363 // types and is declared without an initializer.
12364 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12365 if (const RecordType *Record
12366 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12367 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12368 // Mark the function (if we're in one) for further checking even if the
12369 // looser rules of C++11 do not require such checks, so that we can
12370 // diagnose incompatibilities with C++98.
12371 if (!CXXRecord->isPOD())
12372 setFunctionHasBranchProtectedScope();
12375 // In OpenCL, we can't initialize objects in the __local address space,
12376 // even implicitly, so don't synthesize an implicit initializer.
12377 if (getLangOpts().OpenCL &&
12378 Var->getType().getAddressSpace() == LangAS::opencl_local)
12380 // C++03 [dcl.init]p9:
12381 // If no initializer is specified for an object, and the
12382 // object is of (possibly cv-qualified) non-POD class type (or
12383 // array thereof), the object shall be default-initialized; if
12384 // the object is of const-qualified type, the underlying class
12385 // type shall have a user-declared default
12386 // constructor. Otherwise, if no initializer is specified for
12387 // a non- static object, the object and its subobjects, if
12388 // any, have an indeterminate initial value); if the object
12389 // or any of its subobjects are of const-qualified type, the
12390 // program is ill-formed.
12391 // C++0x [dcl.init]p11:
12392 // If no initializer is specified for an object, the object is
12393 // default-initialized; [...].
12394 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12395 InitializationKind Kind
12396 = InitializationKind::CreateDefault(Var->getLocation());
12398 InitializationSequence InitSeq(*this, Entity, Kind, None);
12399 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12400 if (Init.isInvalid())
12401 Var->setInvalidDecl();
12402 else if (Init.get()) {
12403 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12404 // This is important for template substitution.
12405 Var->setInitStyle(VarDecl::CallInit);
12408 CheckCompleteVariableDeclaration(Var);
12412 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12413 // If there is no declaration, there was an error parsing it. Ignore it.
12417 VarDecl *VD = dyn_cast<VarDecl>(D);
12419 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12420 D->setInvalidDecl();
12424 VD->setCXXForRangeDecl(true);
12426 // for-range-declaration cannot be given a storage class specifier.
12428 switch (VD->getStorageClass()) {
12437 case SC_PrivateExtern:
12448 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12449 << VD->getDeclName() << Error;
12450 D->setInvalidDecl();
12455 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12456 IdentifierInfo *Ident,
12457 ParsedAttributes &Attrs,
12458 SourceLocation AttrEnd) {
12459 // C++1y [stmt.iter]p1:
12460 // A range-based for statement of the form
12461 // for ( for-range-identifier : for-range-initializer ) statement
12462 // is equivalent to
12463 // for ( auto&& for-range-identifier : for-range-initializer ) statement
12464 DeclSpec DS(Attrs.getPool().getFactory());
12466 const char *PrevSpec;
12468 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12469 getPrintingPolicy());
12471 Declarator D(DS, DeclaratorContext::ForContext);
12472 D.SetIdentifier(Ident, IdentLoc);
12473 D.takeAttributes(Attrs, AttrEnd);
12475 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12477 Decl *Var = ActOnDeclarator(S, D);
12478 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12479 FinalizeDeclaration(Var);
12480 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12481 AttrEnd.isValid() ? AttrEnd : IdentLoc);
12484 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12485 if (var->isInvalidDecl()) return;
12487 if (getLangOpts().OpenCL) {
12488 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12490 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12492 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12494 var->setInvalidDecl();
12499 // In Objective-C, don't allow jumps past the implicit initialization of a
12500 // local retaining variable.
12501 if (getLangOpts().ObjC &&
12502 var->hasLocalStorage()) {
12503 switch (var->getType().getObjCLifetime()) {
12504 case Qualifiers::OCL_None:
12505 case Qualifiers::OCL_ExplicitNone:
12506 case Qualifiers::OCL_Autoreleasing:
12509 case Qualifiers::OCL_Weak:
12510 case Qualifiers::OCL_Strong:
12511 setFunctionHasBranchProtectedScope();
12516 if (var->hasLocalStorage() &&
12517 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12518 setFunctionHasBranchProtectedScope();
12520 // Warn about externally-visible variables being defined without a
12521 // prior declaration. We only want to do this for global
12522 // declarations, but we also specifically need to avoid doing it for
12523 // class members because the linkage of an anonymous class can
12524 // change if it's later given a typedef name.
12525 if (var->isThisDeclarationADefinition() &&
12526 var->getDeclContext()->getRedeclContext()->isFileContext() &&
12527 var->isExternallyVisible() && var->hasLinkage() &&
12528 !var->isInline() && !var->getDescribedVarTemplate() &&
12529 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12530 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12531 var->getLocation())) {
12532 // Find a previous declaration that's not a definition.
12533 VarDecl *prev = var->getPreviousDecl();
12534 while (prev && prev->isThisDeclarationADefinition())
12535 prev = prev->getPreviousDecl();
12538 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12539 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12540 << /* variable */ 0;
12544 // Cache the result of checking for constant initialization.
12545 Optional<bool> CacheHasConstInit;
12546 const Expr *CacheCulprit = nullptr;
12547 auto checkConstInit = [&]() mutable {
12548 if (!CacheHasConstInit)
12549 CacheHasConstInit = var->getInit()->isConstantInitializer(
12550 Context, var->getType()->isReferenceType(), &CacheCulprit);
12551 return *CacheHasConstInit;
12554 if (var->getTLSKind() == VarDecl::TLS_Static) {
12555 if (var->getType().isDestructedType()) {
12556 // GNU C++98 edits for __thread, [basic.start.term]p3:
12557 // The type of an object with thread storage duration shall not
12558 // have a non-trivial destructor.
12559 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12560 if (getLangOpts().CPlusPlus11)
12561 Diag(var->getLocation(), diag::note_use_thread_local);
12562 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12563 if (!checkConstInit()) {
12564 // GNU C++98 edits for __thread, [basic.start.init]p4:
12565 // An object of thread storage duration shall not require dynamic
12567 // FIXME: Need strict checking here.
12568 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12569 << CacheCulprit->getSourceRange();
12570 if (getLangOpts().CPlusPlus11)
12571 Diag(var->getLocation(), diag::note_use_thread_local);
12576 // Apply section attributes and pragmas to global variables.
12577 bool GlobalStorage = var->hasGlobalStorage();
12578 if (GlobalStorage && var->isThisDeclarationADefinition() &&
12579 !inTemplateInstantiation()) {
12580 PragmaStack<StringLiteral *> *Stack = nullptr;
12581 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12582 if (var->getType().isConstQualified())
12583 Stack = &ConstSegStack;
12584 else if (!var->getInit()) {
12585 Stack = &BSSSegStack;
12586 SectionFlags |= ASTContext::PSF_Write;
12588 Stack = &DataSegStack;
12589 SectionFlags |= ASTContext::PSF_Write;
12591 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
12592 var->addAttr(SectionAttr::CreateImplicit(
12593 Context, Stack->CurrentValue->getString(),
12594 Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
12595 SectionAttr::Declspec_allocate));
12596 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12597 if (UnifySection(SA->getName(), SectionFlags, var))
12598 var->dropAttr<SectionAttr>();
12600 // Apply the init_seg attribute if this has an initializer. If the
12601 // initializer turns out to not be dynamic, we'll end up ignoring this
12603 if (CurInitSeg && var->getInit())
12604 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12606 AttributeCommonInfo::AS_Pragma));
12609 // All the following checks are C++ only.
12610 if (!getLangOpts().CPlusPlus) {
12611 // If this variable must be emitted, add it as an initializer for the
12613 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12614 Context.addModuleInitializer(ModuleScopes.back().Module, var);
12618 if (auto *DD = dyn_cast<DecompositionDecl>(var))
12619 CheckCompleteDecompositionDeclaration(DD);
12621 QualType type = var->getType();
12622 if (type->isDependentType()) return;
12624 if (var->hasAttr<BlocksAttr>())
12625 getCurFunction()->addByrefBlockVar(var);
12627 Expr *Init = var->getInit();
12628 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12629 QualType baseType = Context.getBaseElementType(type);
12631 if (Init && !Init->isValueDependent()) {
12632 if (var->isConstexpr()) {
12633 SmallVector<PartialDiagnosticAt, 8> Notes;
12634 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12635 SourceLocation DiagLoc = var->getLocation();
12636 // If the note doesn't add any useful information other than a source
12637 // location, fold it into the primary diagnostic.
12638 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12639 diag::note_invalid_subexpr_in_const_expr) {
12640 DiagLoc = Notes[0].first;
12643 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12644 << var << Init->getSourceRange();
12645 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12646 Diag(Notes[I].first, Notes[I].second);
12648 } else if (var->mightBeUsableInConstantExpressions(Context)) {
12649 // Check whether the initializer of a const variable of integral or
12650 // enumeration type is an ICE now, since we can't tell whether it was
12651 // initialized by a constant expression if we check later.
12652 var->checkInitIsICE();
12655 // Don't emit further diagnostics about constexpr globals since they
12656 // were just diagnosed.
12657 if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12658 // FIXME: Need strict checking in C++03 here.
12659 bool DiagErr = getLangOpts().CPlusPlus11
12660 ? !var->checkInitIsICE() : !checkConstInit();
12662 auto *Attr = var->getAttr<ConstInitAttr>();
12663 Diag(var->getLocation(), diag::err_require_constant_init_failed)
12664 << Init->getSourceRange();
12665 Diag(Attr->getLocation(),
12666 diag::note_declared_required_constant_init_here)
12667 << Attr->getRange() << Attr->isConstinit();
12668 if (getLangOpts().CPlusPlus11) {
12670 SmallVector<PartialDiagnosticAt, 8> Notes;
12671 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12672 for (auto &it : Notes)
12673 Diag(it.first, it.second);
12675 Diag(CacheCulprit->getExprLoc(),
12676 diag::note_invalid_subexpr_in_const_expr)
12677 << CacheCulprit->getSourceRange();
12681 else if (!var->isConstexpr() && IsGlobal &&
12682 !getDiagnostics().isIgnored(diag::warn_global_constructor,
12683 var->getLocation())) {
12684 // Warn about globals which don't have a constant initializer. Don't
12685 // warn about globals with a non-trivial destructor because we already
12686 // warned about them.
12687 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12688 if (!(RD && !RD->hasTrivialDestructor())) {
12689 if (!checkConstInit())
12690 Diag(var->getLocation(), diag::warn_global_constructor)
12691 << Init->getSourceRange();
12696 // Require the destructor.
12697 if (const RecordType *recordType = baseType->getAs<RecordType>())
12698 FinalizeVarWithDestructor(var, recordType);
12700 // If this variable must be emitted, add it as an initializer for the current
12702 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12703 Context.addModuleInitializer(ModuleScopes.back().Module, var);
12706 /// Determines if a variable's alignment is dependent.
12707 static bool hasDependentAlignment(VarDecl *VD) {
12708 if (VD->getType()->isDependentType())
12710 for (auto *I : VD->specific_attrs<AlignedAttr>())
12711 if (I->isAlignmentDependent())
12716 /// Check if VD needs to be dllexport/dllimport due to being in a
12717 /// dllexport/import function.
12718 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12719 assert(VD->isStaticLocal());
12721 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12723 // Find outermost function when VD is in lambda function.
12724 while (FD && !getDLLAttr(FD) &&
12725 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12726 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12727 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12733 // Static locals inherit dll attributes from their function.
12734 if (Attr *A = getDLLAttr(FD)) {
12735 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12736 NewAttr->setInherited(true);
12737 VD->addAttr(NewAttr);
12738 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12739 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
12740 NewAttr->setInherited(true);
12741 VD->addAttr(NewAttr);
12743 // Export this function to enforce exporting this static variable even
12744 // if it is not used in this compilation unit.
12745 if (!FD->hasAttr<DLLExportAttr>())
12746 FD->addAttr(NewAttr);
12748 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12749 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
12750 NewAttr->setInherited(true);
12751 VD->addAttr(NewAttr);
12755 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12756 /// any semantic actions necessary after any initializer has been attached.
12757 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12758 // Note that we are no longer parsing the initializer for this declaration.
12759 ParsingInitForAutoVars.erase(ThisDecl);
12761 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12765 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12766 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12767 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12768 if (PragmaClangBSSSection.Valid)
12769 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
12770 Context, PragmaClangBSSSection.SectionName,
12771 PragmaClangBSSSection.PragmaLocation,
12772 AttributeCommonInfo::AS_Pragma));
12773 if (PragmaClangDataSection.Valid)
12774 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
12775 Context, PragmaClangDataSection.SectionName,
12776 PragmaClangDataSection.PragmaLocation,
12777 AttributeCommonInfo::AS_Pragma));
12778 if (PragmaClangRodataSection.Valid)
12779 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
12780 Context, PragmaClangRodataSection.SectionName,
12781 PragmaClangRodataSection.PragmaLocation,
12782 AttributeCommonInfo::AS_Pragma));
12783 if (PragmaClangRelroSection.Valid)
12784 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
12785 Context, PragmaClangRelroSection.SectionName,
12786 PragmaClangRelroSection.PragmaLocation,
12787 AttributeCommonInfo::AS_Pragma));
12790 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12791 for (auto *BD : DD->bindings()) {
12792 FinalizeDeclaration(BD);
12796 checkAttributesAfterMerging(*this, *VD);
12798 // Perform TLS alignment check here after attributes attached to the variable
12799 // which may affect the alignment have been processed. Only perform the check
12800 // if the target has a maximum TLS alignment (zero means no constraints).
12801 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12802 // Protect the check so that it's not performed on dependent types and
12803 // dependent alignments (we can't determine the alignment in that case).
12804 if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12805 !VD->isInvalidDecl()) {
12806 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12807 if (Context.getDeclAlign(VD) > MaxAlignChars) {
12808 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12809 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12810 << (unsigned)MaxAlignChars.getQuantity();
12815 if (VD->isStaticLocal()) {
12816 CheckStaticLocalForDllExport(VD);
12818 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12819 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12820 // function, only __shared__ variables or variables without any device
12821 // memory qualifiers may be declared with static storage class.
12822 // Note: It is unclear how a function-scope non-const static variable
12823 // without device memory qualifier is implemented, therefore only static
12824 // const variable without device memory qualifier is allowed.
12826 if (!getLangOpts().CUDA)
12828 if (VD->hasAttr<CUDASharedAttr>())
12830 if (VD->getType().isConstQualified() &&
12831 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12833 if (CUDADiagIfDeviceCode(VD->getLocation(),
12834 diag::err_device_static_local_var)
12835 << CurrentCUDATarget())
12836 VD->setInvalidDecl();
12841 // Perform check for initializers of device-side global variables.
12842 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12843 // 7.5). We must also apply the same checks to all __shared__
12844 // variables whether they are local or not. CUDA also allows
12845 // constant initializers for __constant__ and __device__ variables.
12846 if (getLangOpts().CUDA)
12847 checkAllowedCUDAInitializer(VD);
12849 // Grab the dllimport or dllexport attribute off of the VarDecl.
12850 const InheritableAttr *DLLAttr = getDLLAttr(VD);
12852 // Imported static data members cannot be defined out-of-line.
12853 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12854 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12855 VD->isThisDeclarationADefinition()) {
12856 // We allow definitions of dllimport class template static data members
12858 CXXRecordDecl *Context =
12859 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12860 bool IsClassTemplateMember =
12861 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12862 Context->getDescribedClassTemplate();
12864 Diag(VD->getLocation(),
12865 IsClassTemplateMember
12866 ? diag::warn_attribute_dllimport_static_field_definition
12867 : diag::err_attribute_dllimport_static_field_definition);
12868 Diag(IA->getLocation(), diag::note_attribute);
12869 if (!IsClassTemplateMember)
12870 VD->setInvalidDecl();
12874 // dllimport/dllexport variables cannot be thread local, their TLS index
12875 // isn't exported with the variable.
12876 if (DLLAttr && VD->getTLSKind()) {
12877 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12878 if (F && getDLLAttr(F)) {
12879 assert(VD->isStaticLocal());
12880 // But if this is a static local in a dlimport/dllexport function, the
12881 // function will never be inlined, which means the var would never be
12882 // imported, so having it marked import/export is safe.
12884 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12886 VD->setInvalidDecl();
12890 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12891 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12892 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12893 VD->dropAttr<UsedAttr>();
12897 const DeclContext *DC = VD->getDeclContext();
12898 // If there's a #pragma GCC visibility in scope, and this isn't a class
12899 // member, set the visibility of this variable.
12900 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12901 AddPushedVisibilityAttribute(VD);
12903 // FIXME: Warn on unused var template partial specializations.
12904 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12905 MarkUnusedFileScopedDecl(VD);
12907 // Now we have parsed the initializer and can update the table of magic
12909 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12910 !VD->getType()->isIntegralOrEnumerationType())
12913 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12914 const Expr *MagicValueExpr = VD->getInit();
12915 if (!MagicValueExpr) {
12918 llvm::APSInt MagicValueInt;
12919 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12920 Diag(I->getRange().getBegin(),
12921 diag::err_type_tag_for_datatype_not_ice)
12922 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12925 if (MagicValueInt.getActiveBits() > 64) {
12926 Diag(I->getRange().getBegin(),
12927 diag::err_type_tag_for_datatype_too_large)
12928 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12931 uint64_t MagicValue = MagicValueInt.getZExtValue();
12932 RegisterTypeTagForDatatype(I->getArgumentKind(),
12934 I->getMatchingCType(),
12935 I->getLayoutCompatible(),
12936 I->getMustBeNull());
12940 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12941 auto *VD = dyn_cast<VarDecl>(DD);
12942 return VD && !VD->getType()->hasAutoForTrailingReturnType();
12945 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12946 ArrayRef<Decl *> Group) {
12947 SmallVector<Decl*, 8> Decls;
12949 if (DS.isTypeSpecOwned())
12950 Decls.push_back(DS.getRepAsDecl());
12952 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12953 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12954 bool DiagnosedMultipleDecomps = false;
12955 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12956 bool DiagnosedNonDeducedAuto = false;
12958 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12959 if (Decl *D = Group[i]) {
12960 // For declarators, there are some additional syntactic-ish checks we need
12962 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12963 if (!FirstDeclaratorInGroup)
12964 FirstDeclaratorInGroup = DD;
12965 if (!FirstDecompDeclaratorInGroup)
12966 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12967 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12968 !hasDeducedAuto(DD))
12969 FirstNonDeducedAutoInGroup = DD;
12971 if (FirstDeclaratorInGroup != DD) {
12972 // A decomposition declaration cannot be combined with any other
12973 // declaration in the same group.
12974 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12975 Diag(FirstDecompDeclaratorInGroup->getLocation(),
12976 diag::err_decomp_decl_not_alone)
12977 << FirstDeclaratorInGroup->getSourceRange()
12978 << DD->getSourceRange();
12979 DiagnosedMultipleDecomps = true;
12982 // A declarator that uses 'auto' in any way other than to declare a
12983 // variable with a deduced type cannot be combined with any other
12984 // declarator in the same group.
12985 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12986 Diag(FirstNonDeducedAutoInGroup->getLocation(),
12987 diag::err_auto_non_deduced_not_alone)
12988 << FirstNonDeducedAutoInGroup->getType()
12989 ->hasAutoForTrailingReturnType()
12990 << FirstDeclaratorInGroup->getSourceRange()
12991 << DD->getSourceRange();
12992 DiagnosedNonDeducedAuto = true;
12997 Decls.push_back(D);
13001 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13002 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13003 handleTagNumbering(Tag, S);
13004 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13005 getLangOpts().CPlusPlus)
13006 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13010 return BuildDeclaratorGroup(Decls);
13013 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13014 /// group, performing any necessary semantic checking.
13015 Sema::DeclGroupPtrTy
13016 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13017 // C++14 [dcl.spec.auto]p7: (DR1347)
13018 // If the type that replaces the placeholder type is not the same in each
13019 // deduction, the program is ill-formed.
13020 if (Group.size() > 1) {
13022 VarDecl *DeducedDecl = nullptr;
13023 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13024 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13025 if (!D || D->isInvalidDecl())
13027 DeducedType *DT = D->getType()->getContainedDeducedType();
13028 if (!DT || DT->getDeducedType().isNull())
13030 if (Deduced.isNull()) {
13031 Deduced = DT->getDeducedType();
13033 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13034 auto *AT = dyn_cast<AutoType>(DT);
13035 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13036 diag::err_auto_different_deductions)
13037 << (AT ? (unsigned)AT->getKeyword() : 3)
13038 << Deduced << DeducedDecl->getDeclName()
13039 << DT->getDeducedType() << D->getDeclName()
13040 << DeducedDecl->getInit()->getSourceRange()
13041 << D->getInit()->getSourceRange();
13042 D->setInvalidDecl();
13048 ActOnDocumentableDecls(Group);
13050 return DeclGroupPtrTy::make(
13051 DeclGroupRef::Create(Context, Group.data(), Group.size()));
13054 void Sema::ActOnDocumentableDecl(Decl *D) {
13055 ActOnDocumentableDecls(D);
13058 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13059 // Don't parse the comment if Doxygen diagnostics are ignored.
13060 if (Group.empty() || !Group[0])
13063 if (Diags.isIgnored(diag::warn_doc_param_not_found,
13064 Group[0]->getLocation()) &&
13065 Diags.isIgnored(diag::warn_unknown_comment_command_name,
13066 Group[0]->getLocation()))
13069 if (Group.size() >= 2) {
13070 // This is a decl group. Normally it will contain only declarations
13071 // produced from declarator list. But in case we have any definitions or
13072 // additional declaration references:
13073 // 'typedef struct S {} S;'
13074 // 'typedef struct S *S;'
13076 // FinalizeDeclaratorGroup adds these as separate declarations.
13077 Decl *MaybeTagDecl = Group[0];
13078 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13079 Group = Group.slice(1);
13083 // FIMXE: We assume every Decl in the group is in the same file.
13084 // This is false when preprocessor constructs the group from decls in
13085 // different files (e. g. macros or #include).
13086 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13089 /// Common checks for a parameter-declaration that should apply to both function
13090 /// parameters and non-type template parameters.
13091 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13092 // Check that there are no default arguments inside the type of this
13094 if (getLangOpts().CPlusPlus)
13095 CheckExtraCXXDefaultArguments(D);
13097 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13098 if (D.getCXXScopeSpec().isSet()) {
13099 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13100 << D.getCXXScopeSpec().getRange();
13103 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13104 // simple identifier except [...irrelevant cases...].
13105 switch (D.getName().getKind()) {
13106 case UnqualifiedIdKind::IK_Identifier:
13109 case UnqualifiedIdKind::IK_OperatorFunctionId:
13110 case UnqualifiedIdKind::IK_ConversionFunctionId:
13111 case UnqualifiedIdKind::IK_LiteralOperatorId:
13112 case UnqualifiedIdKind::IK_ConstructorName:
13113 case UnqualifiedIdKind::IK_DestructorName:
13114 case UnqualifiedIdKind::IK_ImplicitSelfParam:
13115 case UnqualifiedIdKind::IK_DeductionGuideName:
13116 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13117 << GetNameForDeclarator(D).getName();
13120 case UnqualifiedIdKind::IK_TemplateId:
13121 case UnqualifiedIdKind::IK_ConstructorTemplateId:
13122 // GetNameForDeclarator would not produce a useful name in this case.
13123 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13128 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13129 /// to introduce parameters into function prototype scope.
13130 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13131 const DeclSpec &DS = D.getDeclSpec();
13133 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13135 // C++03 [dcl.stc]p2 also permits 'auto'.
13136 StorageClass SC = SC_None;
13137 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13139 // In C++11, the 'register' storage class specifier is deprecated.
13140 // In C++17, it is not allowed, but we tolerate it as an extension.
13141 if (getLangOpts().CPlusPlus11) {
13142 Diag(DS.getStorageClassSpecLoc(),
13143 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13144 : diag::warn_deprecated_register)
13145 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13147 } else if (getLangOpts().CPlusPlus &&
13148 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13150 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13151 Diag(DS.getStorageClassSpecLoc(),
13152 diag::err_invalid_storage_class_in_func_decl);
13153 D.getMutableDeclSpec().ClearStorageClassSpecs();
13156 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13157 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13158 << DeclSpec::getSpecifierName(TSCS);
13159 if (DS.isInlineSpecified())
13160 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13161 << getLangOpts().CPlusPlus17;
13162 if (DS.hasConstexprSpecifier())
13163 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13164 << 0 << D.getDeclSpec().getConstexprSpecifier();
13166 DiagnoseFunctionSpecifiers(DS);
13168 CheckFunctionOrTemplateParamDeclarator(S, D);
13170 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13171 QualType parmDeclType = TInfo->getType();
13173 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13174 IdentifierInfo *II = D.getIdentifier();
13176 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13177 ForVisibleRedeclaration);
13179 if (R.isSingleResult()) {
13180 NamedDecl *PrevDecl = R.getFoundDecl();
13181 if (PrevDecl->isTemplateParameter()) {
13182 // Maybe we will complain about the shadowed template parameter.
13183 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13184 // Just pretend that we didn't see the previous declaration.
13185 PrevDecl = nullptr;
13186 } else if (S->isDeclScope(PrevDecl)) {
13187 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13188 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13190 // Recover by removing the name
13192 D.SetIdentifier(nullptr, D.getIdentifierLoc());
13193 D.setInvalidType(true);
13198 // Temporarily put parameter variables in the translation unit, not
13199 // the enclosing context. This prevents them from accidentally
13200 // looking like class members in C++.
13202 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13203 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13205 if (D.isInvalidType())
13206 New->setInvalidDecl();
13208 assert(S->isFunctionPrototypeScope());
13209 assert(S->getFunctionPrototypeDepth() >= 1);
13210 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13211 S->getNextFunctionPrototypeIndex());
13213 // Add the parameter declaration into this scope.
13216 IdResolver.AddDecl(New);
13218 ProcessDeclAttributes(S, New, D);
13220 if (D.getDeclSpec().isModulePrivateSpecified())
13221 Diag(New->getLocation(), diag::err_module_private_local)
13222 << 1 << New->getDeclName()
13223 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13224 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13226 if (New->hasAttr<BlocksAttr>()) {
13227 Diag(New->getLocation(), diag::err_block_on_nonlocal);
13230 if (getLangOpts().OpenCL)
13231 deduceOpenCLAddressSpace(New);
13236 /// Synthesizes a variable for a parameter arising from a
13238 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13239 SourceLocation Loc,
13241 /* FIXME: setting StartLoc == Loc.
13242 Would it be worth to modify callers so as to provide proper source
13243 location for the unnamed parameters, embedding the parameter's type? */
13244 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13245 T, Context.getTrivialTypeSourceInfo(T, Loc),
13247 Param->setImplicit();
13251 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13252 // Don't diagnose unused-parameter errors in template instantiations; we
13253 // will already have done so in the template itself.
13254 if (inTemplateInstantiation())
13257 for (const ParmVarDecl *Parameter : Parameters) {
13258 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13259 !Parameter->hasAttr<UnusedAttr>()) {
13260 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13261 << Parameter->getDeclName();
13266 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13267 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13268 if (LangOpts.NumLargeByValueCopy == 0) // No check.
13271 // Warn if the return value is pass-by-value and larger than the specified
13273 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13274 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13275 if (Size > LangOpts.NumLargeByValueCopy)
13276 Diag(D->getLocation(), diag::warn_return_value_size)
13277 << D->getDeclName() << Size;
13280 // Warn if any parameter is pass-by-value and larger than the specified
13282 for (const ParmVarDecl *Parameter : Parameters) {
13283 QualType T = Parameter->getType();
13284 if (T->isDependentType() || !T.isPODType(Context))
13286 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13287 if (Size > LangOpts.NumLargeByValueCopy)
13288 Diag(Parameter->getLocation(), diag::warn_parameter_size)
13289 << Parameter->getDeclName() << Size;
13293 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13294 SourceLocation NameLoc, IdentifierInfo *Name,
13295 QualType T, TypeSourceInfo *TSInfo,
13297 // In ARC, infer a lifetime qualifier for appropriate parameter types.
13298 if (getLangOpts().ObjCAutoRefCount &&
13299 T.getObjCLifetime() == Qualifiers::OCL_None &&
13300 T->isObjCLifetimeType()) {
13302 Qualifiers::ObjCLifetime lifetime;
13304 // Special cases for arrays:
13305 // - if it's const, use __unsafe_unretained
13306 // - otherwise, it's an error
13307 if (T->isArrayType()) {
13308 if (!T.isConstQualified()) {
13309 if (DelayedDiagnostics.shouldDelayDiagnostics())
13310 DelayedDiagnostics.add(
13311 sema::DelayedDiagnostic::makeForbiddenType(
13312 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13314 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13315 << TSInfo->getTypeLoc().getSourceRange();
13317 lifetime = Qualifiers::OCL_ExplicitNone;
13319 lifetime = T->getObjCARCImplicitLifetime();
13321 T = Context.getLifetimeQualifiedType(T, lifetime);
13324 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13325 Context.getAdjustedParameterType(T),
13326 TSInfo, SC, nullptr);
13328 // Make a note if we created a new pack in the scope of a lambda, so that
13329 // we know that references to that pack must also be expanded within the
13331 if (New->isParameterPack())
13332 if (auto *LSI = getEnclosingLambda())
13333 LSI->LocalPacks.push_back(New);
13335 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13336 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13337 checkNonTrivialCUnion(New->getType(), New->getLocation(),
13338 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13340 // Parameters can not be abstract class types.
13341 // For record types, this is done by the AbstractClassUsageDiagnoser once
13342 // the class has been completely parsed.
13343 if (!CurContext->isRecord() &&
13344 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13345 AbstractParamType))
13346 New->setInvalidDecl();
13348 // Parameter declarators cannot be interface types. All ObjC objects are
13349 // passed by reference.
13350 if (T->isObjCObjectType()) {
13351 SourceLocation TypeEndLoc =
13352 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13354 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13355 << FixItHint::CreateInsertion(TypeEndLoc, "*");
13356 T = Context.getObjCObjectPointerType(T);
13360 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13361 // duration shall not be qualified by an address-space qualifier."
13362 // Since all parameters have automatic store duration, they can not have
13363 // an address space.
13364 if (T.getAddressSpace() != LangAS::Default &&
13365 // OpenCL allows function arguments declared to be an array of a type
13366 // to be qualified with an address space.
13367 !(getLangOpts().OpenCL &&
13368 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13369 Diag(NameLoc, diag::err_arg_with_address_space);
13370 New->setInvalidDecl();
13376 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13377 SourceLocation LocAfterDecls) {
13378 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13380 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13381 // for a K&R function.
13382 if (!FTI.hasPrototype) {
13383 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13385 if (FTI.Params[i].Param == nullptr) {
13386 SmallString<256> Code;
13387 llvm::raw_svector_ostream(Code)
13388 << " int " << FTI.Params[i].Ident->getName() << ";\n";
13389 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13390 << FTI.Params[i].Ident
13391 << FixItHint::CreateInsertion(LocAfterDecls, Code);
13393 // Implicitly declare the argument as type 'int' for lack of a better
13395 AttributeFactory attrs;
13396 DeclSpec DS(attrs);
13397 const char* PrevSpec; // unused
13398 unsigned DiagID; // unused
13399 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13400 DiagID, Context.getPrintingPolicy());
13401 // Use the identifier location for the type source range.
13402 DS.SetRangeStart(FTI.Params[i].IdentLoc);
13403 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13404 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13405 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13406 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13413 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13414 MultiTemplateParamsArg TemplateParameterLists,
13415 SkipBodyInfo *SkipBody) {
13416 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13417 assert(D.isFunctionDeclarator() && "Not a function declarator!");
13418 Scope *ParentScope = FnBodyScope->getParent();
13420 D.setFunctionDefinitionKind(FDK_Definition);
13421 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13422 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13425 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13426 Consumer.HandleInlineFunctionDefinition(D);
13430 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13431 const FunctionDecl *&PossiblePrototype) {
13432 // Don't warn about invalid declarations.
13433 if (FD->isInvalidDecl())
13436 // Or declarations that aren't global.
13437 if (!FD->isGlobal())
13440 // Don't warn about C++ member functions.
13441 if (isa<CXXMethodDecl>(FD))
13444 // Don't warn about 'main'.
13445 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13446 if (IdentifierInfo *II = FD->getIdentifier())
13447 if (II->isStr("main"))
13450 // Don't warn about inline functions.
13451 if (FD->isInlined())
13454 // Don't warn about function templates.
13455 if (FD->getDescribedFunctionTemplate())
13458 // Don't warn about function template specializations.
13459 if (FD->isFunctionTemplateSpecialization())
13462 // Don't warn for OpenCL kernels.
13463 if (FD->hasAttr<OpenCLKernelAttr>())
13466 // Don't warn on explicitly deleted functions.
13467 if (FD->isDeleted())
13470 for (const FunctionDecl *Prev = FD->getPreviousDecl();
13471 Prev; Prev = Prev->getPreviousDecl()) {
13472 // Ignore any declarations that occur in function or method
13473 // scope, because they aren't visible from the header.
13474 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13477 PossiblePrototype = Prev;
13478 return Prev->getType()->isFunctionNoProtoType();
13485 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13486 const FunctionDecl *EffectiveDefinition,
13487 SkipBodyInfo *SkipBody) {
13488 const FunctionDecl *Definition = EffectiveDefinition;
13489 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13490 // If this is a friend function defined in a class template, it does not
13491 // have a body until it is used, nevertheless it is a definition, see
13494 // ... for the purpose of determining whether an instantiated redeclaration
13495 // is valid according to [basic.def.odr] and [class.mem], a declaration that
13496 // corresponds to a definition in the template is considered to be a
13499 // The following code must produce redefinition error:
13501 // template<typename T> struct C20 { friend void func_20() {} };
13503 // void func_20() {}
13505 for (auto I : FD->redecls()) {
13506 if (I != FD && !I->isInvalidDecl() &&
13507 I->getFriendObjectKind() != Decl::FOK_None) {
13508 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13509 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13510 // A merged copy of the same function, instantiated as a member of
13511 // the same class, is OK.
13512 if (declaresSameEntity(OrigFD, Original) &&
13513 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13514 cast<Decl>(FD->getLexicalDeclContext())))
13518 if (Original->isThisDeclarationADefinition()) {
13528 // Similar to friend functions a friend function template may be a
13529 // definition and do not have a body if it is instantiated in a class
13531 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13532 for (auto I : FTD->redecls()) {
13533 auto D = cast<FunctionTemplateDecl>(I);
13535 assert(!D->isThisDeclarationADefinition() &&
13536 "More than one definition in redeclaration chain");
13537 if (D->getFriendObjectKind() != Decl::FOK_None)
13538 if (FunctionTemplateDecl *FT =
13539 D->getInstantiatedFromMemberTemplate()) {
13540 if (FT->isThisDeclarationADefinition()) {
13541 Definition = D->getTemplatedDecl();
13552 if (canRedefineFunction(Definition, getLangOpts()))
13555 // Don't emit an error when this is redefinition of a typo-corrected
13557 if (TypoCorrectedFunctionDefinitions.count(Definition))
13560 // If we don't have a visible definition of the function, and it's inline or
13561 // a template, skip the new definition.
13562 if (SkipBody && !hasVisibleDefinition(Definition) &&
13563 (Definition->getFormalLinkage() == InternalLinkage ||
13564 Definition->isInlined() ||
13565 Definition->getDescribedFunctionTemplate() ||
13566 Definition->getNumTemplateParameterLists())) {
13567 SkipBody->ShouldSkip = true;
13568 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13569 if (auto *TD = Definition->getDescribedFunctionTemplate())
13570 makeMergedDefinitionVisible(TD);
13571 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13575 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13576 Definition->getStorageClass() == SC_Extern)
13577 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13578 << FD->getDeclName() << getLangOpts().CPlusPlus;
13580 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13582 Diag(Definition->getLocation(), diag::note_previous_definition);
13583 FD->setInvalidDecl();
13586 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13588 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13590 LambdaScopeInfo *LSI = S.PushLambdaScope();
13591 LSI->CallOperator = CallOperator;
13592 LSI->Lambda = LambdaClass;
13593 LSI->ReturnType = CallOperator->getReturnType();
13594 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13596 if (LCD == LCD_None)
13597 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13598 else if (LCD == LCD_ByCopy)
13599 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13600 else if (LCD == LCD_ByRef)
13601 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13602 DeclarationNameInfo DNI = CallOperator->getNameInfo();
13604 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13605 LSI->Mutable = !CallOperator->isConst();
13607 // Add the captures to the LSI so they can be noted as already
13608 // captured within tryCaptureVar.
13609 auto I = LambdaClass->field_begin();
13610 for (const auto &C : LambdaClass->captures()) {
13611 if (C.capturesVariable()) {
13612 VarDecl *VD = C.getCapturedVar();
13613 if (VD->isInitCapture())
13614 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13615 QualType CaptureType = VD->getType();
13616 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13617 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13618 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13619 /*EllipsisLoc*/C.isPackExpansion()
13620 ? C.getEllipsisLoc() : SourceLocation(),
13621 CaptureType, /*Invalid*/false);
13623 } else if (C.capturesThis()) {
13624 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13625 C.getCaptureKind() == LCK_StarThis);
13627 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13634 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13635 SkipBodyInfo *SkipBody) {
13637 // Parsing the function declaration failed in some way. Push on a fake scope
13638 // anyway so we can try to parse the function body.
13639 PushFunctionScope();
13640 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13644 FunctionDecl *FD = nullptr;
13646 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13647 FD = FunTmpl->getTemplatedDecl();
13649 FD = cast<FunctionDecl>(D);
13651 // Do not push if it is a lambda because one is already pushed when building
13652 // the lambda in ActOnStartOfLambdaDefinition().
13653 if (!isLambdaCallOperator(FD))
13654 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13656 // Check for defining attributes before the check for redefinition.
13657 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13658 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13659 FD->dropAttr<AliasAttr>();
13660 FD->setInvalidDecl();
13662 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13663 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13664 FD->dropAttr<IFuncAttr>();
13665 FD->setInvalidDecl();
13668 // See if this is a redefinition. If 'will have body' is already set, then
13669 // these checks were already performed when it was set.
13670 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13671 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13673 // If we're skipping the body, we're done. Don't enter the scope.
13674 if (SkipBody && SkipBody->ShouldSkip)
13678 // Mark this function as "will have a body eventually". This lets users to
13679 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13681 FD->setWillHaveBody();
13683 // If we are instantiating a generic lambda call operator, push
13684 // a LambdaScopeInfo onto the function stack. But use the information
13685 // that's already been calculated (ActOnLambdaExpr) to prime the current
13686 // LambdaScopeInfo.
13687 // When the template operator is being specialized, the LambdaScopeInfo,
13688 // has to be properly restored so that tryCaptureVariable doesn't try
13689 // and capture any new variables. In addition when calculating potential
13690 // captures during transformation of nested lambdas, it is necessary to
13691 // have the LSI properly restored.
13692 if (isGenericLambdaCallOperatorSpecialization(FD)) {
13693 assert(inTemplateInstantiation() &&
13694 "There should be an active template instantiation on the stack "
13695 "when instantiating a generic lambda!");
13696 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13698 // Enter a new function scope
13699 PushFunctionScope();
13702 // Builtin functions cannot be defined.
13703 if (unsigned BuiltinID = FD->getBuiltinID()) {
13704 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13705 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13706 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13707 FD->setInvalidDecl();
13711 // The return type of a function definition must be complete
13712 // (C99 6.9.1p3, C++ [dcl.fct]p6).
13713 QualType ResultType = FD->getReturnType();
13714 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13715 !FD->isInvalidDecl() &&
13716 RequireCompleteType(FD->getLocation(), ResultType,
13717 diag::err_func_def_incomplete_result))
13718 FD->setInvalidDecl();
13721 PushDeclContext(FnBodyScope, FD);
13723 // Check the validity of our function parameters
13724 CheckParmsForFunctionDef(FD->parameters(),
13725 /*CheckParameterNames=*/true);
13727 // Add non-parameter declarations already in the function to the current
13730 for (Decl *NPD : FD->decls()) {
13731 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13734 assert(!isa<ParmVarDecl>(NonParmDecl) &&
13735 "parameters should not be in newly created FD yet");
13737 // If the decl has a name, make it accessible in the current scope.
13738 if (NonParmDecl->getDeclName())
13739 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13741 // Similarly, dive into enums and fish their constants out, making them
13742 // accessible in this scope.
13743 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13744 for (auto *EI : ED->enumerators())
13745 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13750 // Introduce our parameters into the function scope
13751 for (auto Param : FD->parameters()) {
13752 Param->setOwningFunction(FD);
13754 // If this has an identifier, add it to the scope stack.
13755 if (Param->getIdentifier() && FnBodyScope) {
13756 CheckShadow(FnBodyScope, Param);
13758 PushOnScopeChains(Param, FnBodyScope);
13762 // Ensure that the function's exception specification is instantiated.
13763 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13764 ResolveExceptionSpec(D->getLocation(), FPT);
13766 // dllimport cannot be applied to non-inline function definitions.
13767 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13768 !FD->isTemplateInstantiation()) {
13769 assert(!FD->hasAttr<DLLExportAttr>());
13770 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13771 FD->setInvalidDecl();
13774 // We want to attach documentation to original Decl (which might be
13775 // a function template).
13776 ActOnDocumentableDecl(D);
13777 if (getCurLexicalContext()->isObjCContainer() &&
13778 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13779 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13780 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13785 /// Given the set of return statements within a function body,
13786 /// compute the variables that are subject to the named return value
13789 /// Each of the variables that is subject to the named return value
13790 /// optimization will be marked as NRVO variables in the AST, and any
13791 /// return statement that has a marked NRVO variable as its NRVO candidate can
13792 /// use the named return value optimization.
13794 /// This function applies a very simplistic algorithm for NRVO: if every return
13795 /// statement in the scope of a variable has the same NRVO candidate, that
13796 /// candidate is an NRVO variable.
13797 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13798 ReturnStmt **Returns = Scope->Returns.data();
13800 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13801 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13802 if (!NRVOCandidate->isNRVOVariable())
13803 Returns[I]->setNRVOCandidate(nullptr);
13808 bool Sema::canDelayFunctionBody(const Declarator &D) {
13809 // We can't delay parsing the body of a constexpr function template (yet).
13810 if (D.getDeclSpec().hasConstexprSpecifier())
13813 // We can't delay parsing the body of a function template with a deduced
13814 // return type (yet).
13815 if (D.getDeclSpec().hasAutoTypeSpec()) {
13816 // If the placeholder introduces a non-deduced trailing return type,
13817 // we can still delay parsing it.
13818 if (D.getNumTypeObjects()) {
13819 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13820 if (Outer.Kind == DeclaratorChunk::Function &&
13821 Outer.Fun.hasTrailingReturnType()) {
13822 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13823 return Ty.isNull() || !Ty->isUndeducedType();
13832 bool Sema::canSkipFunctionBody(Decl *D) {
13833 // We cannot skip the body of a function (or function template) which is
13834 // constexpr, since we may need to evaluate its body in order to parse the
13835 // rest of the file.
13836 // We cannot skip the body of a function with an undeduced return type,
13837 // because any callers of that function need to know the type.
13838 if (const FunctionDecl *FD = D->getAsFunction()) {
13839 if (FD->isConstexpr())
13841 // We can't simply call Type::isUndeducedType here, because inside template
13842 // auto can be deduced to a dependent type, which is not considered
13844 if (FD->getReturnType()->getContainedDeducedType())
13847 return Consumer.shouldSkipFunctionBody(D);
13850 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13853 if (FunctionDecl *FD = Decl->getAsFunction())
13854 FD->setHasSkippedBody();
13855 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13856 MD->setHasSkippedBody();
13860 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13861 return ActOnFinishFunctionBody(D, BodyArg, false);
13864 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13866 class ExitFunctionBodyRAII {
13868 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13869 ~ExitFunctionBodyRAII() {
13871 S.PopExpressionEvaluationContext();
13876 bool IsLambda = false;
13879 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13880 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13882 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13883 if (EscapeInfo.count(BD))
13884 return EscapeInfo[BD];
13887 const BlockDecl *CurBD = BD;
13890 R = !CurBD->doesNotEscape();
13893 CurBD = CurBD->getParent()->getInnermostBlockDecl();
13896 return EscapeInfo[BD] = R;
13899 // If the location where 'self' is implicitly retained is inside a escaping
13900 // block, emit a diagnostic.
13901 for (const std::pair<SourceLocation, const BlockDecl *> &P :
13902 S.ImplicitlyRetainedSelfLocs)
13903 if (IsOrNestedInEscapingBlock(P.second))
13904 S.Diag(P.first, diag::warn_implicitly_retains_self)
13905 << FixItHint::CreateInsertion(P.first, "self->");
13908 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13909 bool IsInstantiation) {
13910 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13912 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13913 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13915 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13916 CheckCompletedCoroutineBody(FD, Body);
13918 // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13919 // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13920 // meant to pop the context added in ActOnStartOfFunctionDef().
13921 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13925 FD->setWillHaveBody(false);
13927 if (getLangOpts().CPlusPlus14) {
13928 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13929 FD->getReturnType()->isUndeducedType()) {
13930 // If the function has a deduced result type but contains no 'return'
13931 // statements, the result type as written must be exactly 'auto', and
13932 // the deduced result type is 'void'.
13933 if (!FD->getReturnType()->getAs<AutoType>()) {
13934 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13935 << FD->getReturnType();
13936 FD->setInvalidDecl();
13938 // Substitute 'void' for the 'auto' in the type.
13939 TypeLoc ResultType = getReturnTypeLoc(FD);
13940 Context.adjustDeducedFunctionResultType(
13941 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13944 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13945 // In C++11, we don't use 'auto' deduction rules for lambda call
13946 // operators because we don't support return type deduction.
13947 auto *LSI = getCurLambda();
13948 if (LSI->HasImplicitReturnType) {
13949 deduceClosureReturnType(*LSI);
13951 // C++11 [expr.prim.lambda]p4:
13952 // [...] if there are no return statements in the compound-statement
13953 // [the deduced type is] the type void
13955 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13957 // Update the return type to the deduced type.
13958 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
13959 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13960 Proto->getExtProtoInfo()));
13964 // If the function implicitly returns zero (like 'main') or is naked,
13965 // don't complain about missing return statements.
13966 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13967 WP.disableCheckFallThrough();
13969 // MSVC permits the use of pure specifier (=0) on function definition,
13970 // defined at class scope, warn about this non-standard construct.
13971 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13972 Diag(FD->getLocation(), diag::ext_pure_function_definition);
13974 if (!FD->isInvalidDecl()) {
13975 // Don't diagnose unused parameters of defaulted or deleted functions.
13976 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13977 DiagnoseUnusedParameters(FD->parameters());
13978 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13979 FD->getReturnType(), FD);
13981 // If this is a structor, we need a vtable.
13982 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13983 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13984 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13985 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13987 // Try to apply the named return value optimization. We have to check
13988 // if we can do this here because lambdas keep return statements around
13989 // to deduce an implicit return type.
13990 if (FD->getReturnType()->isRecordType() &&
13991 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13992 computeNRVO(Body, getCurFunction());
13995 // GNU warning -Wmissing-prototypes:
13996 // Warn if a global function is defined without a previous
13997 // prototype declaration. This warning is issued even if the
13998 // definition itself provides a prototype. The aim is to detect
13999 // global functions that fail to be declared in header files.
14000 const FunctionDecl *PossiblePrototype = nullptr;
14001 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14002 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14004 if (PossiblePrototype) {
14005 // We found a declaration that is not a prototype,
14006 // but that could be a zero-parameter prototype
14007 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14008 TypeLoc TL = TI->getTypeLoc();
14009 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14010 Diag(PossiblePrototype->getLocation(),
14011 diag::note_declaration_not_a_prototype)
14012 << (FD->getNumParams() != 0)
14013 << (FD->getNumParams() == 0
14014 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14018 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14019 << /* function */ 1
14020 << (FD->getStorageClass() == SC_None
14021 ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
14026 // GNU warning -Wstrict-prototypes
14027 // Warn if K&R function is defined without a previous declaration.
14028 // This warning is issued only if the definition itself does not provide
14029 // a prototype. Only K&R definitions do not provide a prototype.
14030 // An empty list in a function declarator that is part of a definition
14031 // of that function specifies that the function has no parameters
14032 // (C99 6.7.5.3p14)
14033 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
14034 !LangOpts.CPlusPlus) {
14035 TypeSourceInfo *TI = FD->getTypeSourceInfo();
14036 TypeLoc TL = TI->getTypeLoc();
14037 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14038 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14042 // Warn on CPUDispatch with an actual body.
14043 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14044 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14045 if (!CmpndBody->body_empty())
14046 Diag(CmpndBody->body_front()->getBeginLoc(),
14047 diag::warn_dispatch_body_ignored);
14049 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14050 const CXXMethodDecl *KeyFunction;
14051 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14053 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14054 MD == KeyFunction->getCanonicalDecl()) {
14055 // Update the key-function state if necessary for this ABI.
14056 if (FD->isInlined() &&
14057 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14058 Context.setNonKeyFunction(MD);
14060 // If the newly-chosen key function is already defined, then we
14061 // need to mark the vtable as used retroactively.
14062 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14063 const FunctionDecl *Definition;
14064 if (KeyFunction && KeyFunction->isDefined(Definition))
14065 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14067 // We just defined they key function; mark the vtable as used.
14068 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14073 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14074 "Function parsing confused");
14075 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14076 assert(MD == getCurMethodDecl() && "Method parsing confused");
14078 if (!MD->isInvalidDecl()) {
14079 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14080 MD->getReturnType(), MD);
14083 computeNRVO(Body, getCurFunction());
14085 if (getCurFunction()->ObjCShouldCallSuper) {
14086 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14087 << MD->getSelector().getAsString();
14088 getCurFunction()->ObjCShouldCallSuper = false;
14090 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14091 const ObjCMethodDecl *InitMethod = nullptr;
14092 bool isDesignated =
14093 MD->isDesignatedInitializerForTheInterface(&InitMethod);
14094 assert(isDesignated && InitMethod);
14095 (void)isDesignated;
14097 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14098 auto IFace = MD->getClassInterface();
14101 auto SuperD = IFace->getSuperClass();
14104 return SuperD->getIdentifier() ==
14105 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14107 // Don't issue this warning for unavailable inits or direct subclasses
14109 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14110 Diag(MD->getLocation(),
14111 diag::warn_objc_designated_init_missing_super_call);
14112 Diag(InitMethod->getLocation(),
14113 diag::note_objc_designated_init_marked_here);
14115 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14117 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14118 // Don't issue this warning for unavaialable inits.
14119 if (!MD->isUnavailable())
14120 Diag(MD->getLocation(),
14121 diag::warn_objc_secondary_init_missing_init_call);
14122 getCurFunction()->ObjCWarnForNoInitDelegation = false;
14125 diagnoseImplicitlyRetainedSelf(*this);
14127 // Parsing the function declaration failed in some way. Pop the fake scope
14129 PopFunctionScopeInfo(ActivePolicy, dcl);
14133 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14134 DiagnoseUnguardedAvailabilityViolations(dcl);
14136 assert(!getCurFunction()->ObjCShouldCallSuper &&
14137 "This should only be set for ObjC methods, which should have been "
14138 "handled in the block above.");
14140 // Verify and clean out per-function state.
14141 if (Body && (!FD || !FD->isDefaulted())) {
14142 // C++ constructors that have function-try-blocks can't have return
14143 // statements in the handlers of that block. (C++ [except.handle]p14)
14145 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14146 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14148 // Verify that gotos and switch cases don't jump into scopes illegally.
14149 if (getCurFunction()->NeedsScopeChecking() &&
14150 !PP.isCodeCompletionEnabled())
14151 DiagnoseInvalidJumps(Body);
14153 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14154 if (!Destructor->getParent()->isDependentType())
14155 CheckDestructor(Destructor);
14157 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14158 Destructor->getParent());
14161 // If any errors have occurred, clear out any temporaries that may have
14162 // been leftover. This ensures that these temporaries won't be picked up for
14163 // deletion in some later function.
14164 if (getDiagnostics().hasErrorOccurred() ||
14165 getDiagnostics().getSuppressAllDiagnostics()) {
14166 DiscardCleanupsInEvaluationContext();
14168 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14169 !isa<FunctionTemplateDecl>(dcl)) {
14170 // Since the body is valid, issue any analysis-based warnings that are
14172 ActivePolicy = &WP;
14175 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14176 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14177 FD->setInvalidDecl();
14179 if (FD && FD->hasAttr<NakedAttr>()) {
14180 for (const Stmt *S : Body->children()) {
14181 // Allow local register variables without initializer as they don't
14182 // require prologue.
14183 bool RegisterVariables = false;
14184 if (auto *DS = dyn_cast<DeclStmt>(S)) {
14185 for (const auto *Decl : DS->decls()) {
14186 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14187 RegisterVariables =
14188 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14189 if (!RegisterVariables)
14194 if (RegisterVariables)
14196 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14197 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14198 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14199 FD->setInvalidDecl();
14205 assert(ExprCleanupObjects.size() ==
14206 ExprEvalContexts.back().NumCleanupObjects &&
14207 "Leftover temporaries in function");
14208 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14209 assert(MaybeODRUseExprs.empty() &&
14210 "Leftover expressions for odr-use checking");
14213 if (!IsInstantiation)
14216 PopFunctionScopeInfo(ActivePolicy, dcl);
14217 // If any errors have occurred, clear out any temporaries that may have
14218 // been leftover. This ensures that these temporaries won't be picked up for
14219 // deletion in some later function.
14220 if (getDiagnostics().hasErrorOccurred()) {
14221 DiscardCleanupsInEvaluationContext();
14227 /// When we finish delayed parsing of an attribute, we must attach it to the
14229 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14230 ParsedAttributes &Attrs) {
14231 // Always attach attributes to the underlying decl.
14232 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14233 D = TD->getTemplatedDecl();
14234 ProcessDeclAttributeList(S, D, Attrs);
14236 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14237 if (Method->isStatic())
14238 checkThisInStaticMemberFunctionAttributes(Method);
14241 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14242 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14243 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14244 IdentifierInfo &II, Scope *S) {
14245 // Find the scope in which the identifier is injected and the corresponding
14247 // FIXME: C89 does not say what happens if there is no enclosing block scope.
14248 // In that case, we inject the declaration into the translation unit scope
14250 Scope *BlockScope = S;
14251 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14252 BlockScope = BlockScope->getParent();
14254 Scope *ContextScope = BlockScope;
14255 while (!ContextScope->getEntity())
14256 ContextScope = ContextScope->getParent();
14257 ContextRAII SavedContext(*this, ContextScope->getEntity());
14259 // Before we produce a declaration for an implicitly defined
14260 // function, see whether there was a locally-scoped declaration of
14261 // this name as a function or variable. If so, use that
14262 // (non-visible) declaration, and complain about it.
14263 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14265 // We still need to inject the function into the enclosing block scope so
14266 // that later (non-call) uses can see it.
14267 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14269 // C89 footnote 38:
14270 // If in fact it is not defined as having type "function returning int",
14271 // the behavior is undefined.
14272 if (!isa<FunctionDecl>(ExternCPrev) ||
14273 !Context.typesAreCompatible(
14274 cast<FunctionDecl>(ExternCPrev)->getType(),
14275 Context.getFunctionNoProtoType(Context.IntTy))) {
14276 Diag(Loc, diag::ext_use_out_of_scope_declaration)
14277 << ExternCPrev << !getLangOpts().C99;
14278 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14279 return ExternCPrev;
14283 // Extension in C99. Legal in C90, but warn about it.
14285 if (II.getName().startswith("__builtin_"))
14286 diag_id = diag::warn_builtin_unknown;
14287 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14288 else if (getLangOpts().OpenCL)
14289 diag_id = diag::err_opencl_implicit_function_decl;
14290 else if (getLangOpts().C99)
14291 diag_id = diag::ext_implicit_function_decl;
14293 diag_id = diag::warn_implicit_function_decl;
14294 Diag(Loc, diag_id) << &II;
14296 // If we found a prior declaration of this function, don't bother building
14297 // another one. We've already pushed that one into scope, so there's nothing
14300 return ExternCPrev;
14302 // Because typo correction is expensive, only do it if the implicit
14303 // function declaration is going to be treated as an error.
14304 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14305 TypoCorrection Corrected;
14306 DeclFilterCCC<FunctionDecl> CCC{};
14307 if (S && (Corrected =
14308 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14309 S, nullptr, CCC, CTK_NonError)))
14310 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14311 /*ErrorRecovery*/false);
14314 // Set a Declarator for the implicit definition: int foo();
14316 AttributeFactory attrFactory;
14317 DeclSpec DS(attrFactory);
14319 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14320 Context.getPrintingPolicy());
14321 (void)Error; // Silence warning.
14322 assert(!Error && "Error setting up implicit decl!");
14323 SourceLocation NoLoc;
14324 Declarator D(DS, DeclaratorContext::BlockContext);
14325 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14326 /*IsAmbiguous=*/false,
14327 /*LParenLoc=*/NoLoc,
14328 /*Params=*/nullptr,
14330 /*EllipsisLoc=*/NoLoc,
14331 /*RParenLoc=*/NoLoc,
14332 /*RefQualifierIsLvalueRef=*/true,
14333 /*RefQualifierLoc=*/NoLoc,
14334 /*MutableLoc=*/NoLoc, EST_None,
14335 /*ESpecRange=*/SourceRange(),
14336 /*Exceptions=*/nullptr,
14337 /*ExceptionRanges=*/nullptr,
14338 /*NumExceptions=*/0,
14339 /*NoexceptExpr=*/nullptr,
14340 /*ExceptionSpecTokens=*/nullptr,
14341 /*DeclsInPrototype=*/None, Loc,
14343 std::move(DS.getAttributes()), SourceLocation());
14344 D.SetIdentifier(&II, Loc);
14346 // Insert this function into the enclosing block scope.
14347 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14350 AddKnownFunctionAttributes(FD);
14355 /// Adds any function attributes that we know a priori based on
14356 /// the declaration of this function.
14358 /// These attributes can apply both to implicitly-declared builtins
14359 /// (like __builtin___printf_chk) or to library-declared functions
14360 /// like NSLog or printf.
14362 /// We need to check for duplicate attributes both here and where user-written
14363 /// attributes are applied to declarations.
14364 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14365 if (FD->isInvalidDecl())
14368 // If this is a built-in function, map its builtin attributes to
14369 // actual attributes.
14370 if (unsigned BuiltinID = FD->getBuiltinID()) {
14371 // Handle printf-formatting attributes.
14372 unsigned FormatIdx;
14374 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14375 if (!FD->hasAttr<FormatAttr>()) {
14376 const char *fmt = "printf";
14377 unsigned int NumParams = FD->getNumParams();
14378 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14379 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14381 FD->addAttr(FormatAttr::CreateImplicit(Context,
14382 &Context.Idents.get(fmt),
14384 HasVAListArg ? 0 : FormatIdx+2,
14385 FD->getLocation()));
14388 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14390 if (!FD->hasAttr<FormatAttr>())
14391 FD->addAttr(FormatAttr::CreateImplicit(Context,
14392 &Context.Idents.get("scanf"),
14394 HasVAListArg ? 0 : FormatIdx+2,
14395 FD->getLocation()));
14398 // Handle automatically recognized callbacks.
14399 SmallVector<int, 4> Encoding;
14400 if (!FD->hasAttr<CallbackAttr>() &&
14401 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14402 FD->addAttr(CallbackAttr::CreateImplicit(
14403 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14405 // Mark const if we don't care about errno and that is the only thing
14406 // preventing the function from being const. This allows IRgen to use LLVM
14407 // intrinsics for such functions.
14408 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14409 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14410 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14412 // We make "fma" on some platforms const because we know it does not set
14413 // errno in those environments even though it could set errno based on the
14415 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14416 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14417 !FD->hasAttr<ConstAttr>()) {
14418 switch (BuiltinID) {
14419 case Builtin::BI__builtin_fma:
14420 case Builtin::BI__builtin_fmaf:
14421 case Builtin::BI__builtin_fmal:
14422 case Builtin::BIfma:
14423 case Builtin::BIfmaf:
14424 case Builtin::BIfmal:
14425 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14432 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14433 !FD->hasAttr<ReturnsTwiceAttr>())
14434 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14435 FD->getLocation()));
14436 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14437 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14438 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14439 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14440 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14441 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14442 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14443 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14444 // Add the appropriate attribute, depending on the CUDA compilation mode
14445 // and which target the builtin belongs to. For example, during host
14446 // compilation, aux builtins are __device__, while the rest are __host__.
14447 if (getLangOpts().CUDAIsDevice !=
14448 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14449 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14451 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14455 // If C++ exceptions are enabled but we are told extern "C" functions cannot
14456 // throw, add an implicit nothrow attribute to any extern "C" function we come
14458 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14459 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14460 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14461 if (!FPT || FPT->getExceptionSpecType() == EST_None)
14462 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14465 IdentifierInfo *Name = FD->getIdentifier();
14468 if ((!getLangOpts().CPlusPlus &&
14469 FD->getDeclContext()->isTranslationUnit()) ||
14470 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14471 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14472 LinkageSpecDecl::lang_c)) {
14473 // Okay: this could be a libc/libm/Objective-C function we know
14478 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14479 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14480 // target-specific builtins, perhaps?
14481 if (!FD->hasAttr<FormatAttr>())
14482 FD->addAttr(FormatAttr::CreateImplicit(Context,
14483 &Context.Idents.get("printf"), 2,
14484 Name->isStr("vasprintf") ? 0 : 3,
14485 FD->getLocation()));
14488 if (Name->isStr("__CFStringMakeConstantString")) {
14489 // We already have a __builtin___CFStringMakeConstantString,
14490 // but builds that use -fno-constant-cfstrings don't go through that.
14491 if (!FD->hasAttr<FormatArgAttr>())
14492 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14493 FD->getLocation()));
14497 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14498 TypeSourceInfo *TInfo) {
14499 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14500 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14503 assert(D.isInvalidType() && "no declarator info for valid type");
14504 TInfo = Context.getTrivialTypeSourceInfo(T);
14507 // Scope manipulation handled by caller.
14508 TypedefDecl *NewTD =
14509 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14510 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14512 // Bail out immediately if we have an invalid declaration.
14513 if (D.isInvalidType()) {
14514 NewTD->setInvalidDecl();
14518 if (D.getDeclSpec().isModulePrivateSpecified()) {
14519 if (CurContext->isFunctionOrMethod())
14520 Diag(NewTD->getLocation(), diag::err_module_private_local)
14521 << 2 << NewTD->getDeclName()
14522 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14523 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14525 NewTD->setModulePrivate();
14528 // C++ [dcl.typedef]p8:
14529 // If the typedef declaration defines an unnamed class (or
14530 // enum), the first typedef-name declared by the declaration
14531 // to be that class type (or enum type) is used to denote the
14532 // class type (or enum type) for linkage purposes only.
14533 // We need to check whether the type was declared in the declaration.
14534 switch (D.getDeclSpec().getTypeSpecType()) {
14537 case TST_interface:
14540 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14541 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14552 /// Check that this is a valid underlying type for an enum declaration.
14553 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14554 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14555 QualType T = TI->getType();
14557 if (T->isDependentType())
14560 if (const BuiltinType *BT = T->getAs<BuiltinType>())
14561 if (BT->isInteger())
14564 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14568 /// Check whether this is a valid redeclaration of a previous enumeration.
14569 /// \return true if the redeclaration was invalid.
14570 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14571 QualType EnumUnderlyingTy, bool IsFixed,
14572 const EnumDecl *Prev) {
14573 if (IsScoped != Prev->isScoped()) {
14574 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14575 << Prev->isScoped();
14576 Diag(Prev->getLocation(), diag::note_previous_declaration);
14580 if (IsFixed && Prev->isFixed()) {
14581 if (!EnumUnderlyingTy->isDependentType() &&
14582 !Prev->getIntegerType()->isDependentType() &&
14583 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14584 Prev->getIntegerType())) {
14585 // TODO: Highlight the underlying type of the redeclaration.
14586 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14587 << EnumUnderlyingTy << Prev->getIntegerType();
14588 Diag(Prev->getLocation(), diag::note_previous_declaration)
14589 << Prev->getIntegerTypeRange();
14592 } else if (IsFixed != Prev->isFixed()) {
14593 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14594 << Prev->isFixed();
14595 Diag(Prev->getLocation(), diag::note_previous_declaration);
14602 /// Get diagnostic %select index for tag kind for
14603 /// redeclaration diagnostic message.
14604 /// WARNING: Indexes apply to particular diagnostics only!
14606 /// \returns diagnostic %select index.
14607 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14609 case TTK_Struct: return 0;
14610 case TTK_Interface: return 1;
14611 case TTK_Class: return 2;
14612 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14616 /// Determine if tag kind is a class-key compatible with
14617 /// class for redeclaration (class, struct, or __interface).
14619 /// \returns true iff the tag kind is compatible.
14620 static bool isClassCompatTagKind(TagTypeKind Tag)
14622 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14625 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14627 if (isa<TypedefDecl>(PrevDecl))
14628 return NTK_Typedef;
14629 else if (isa<TypeAliasDecl>(PrevDecl))
14630 return NTK_TypeAlias;
14631 else if (isa<ClassTemplateDecl>(PrevDecl))
14632 return NTK_Template;
14633 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14634 return NTK_TypeAliasTemplate;
14635 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14636 return NTK_TemplateTemplateArgument;
14639 case TTK_Interface:
14641 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14643 return NTK_NonUnion;
14645 return NTK_NonEnum;
14647 llvm_unreachable("invalid TTK");
14650 /// Determine whether a tag with a given kind is acceptable
14651 /// as a redeclaration of the given tag declaration.
14653 /// \returns true if the new tag kind is acceptable, false otherwise.
14654 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14655 TagTypeKind NewTag, bool isDefinition,
14656 SourceLocation NewTagLoc,
14657 const IdentifierInfo *Name) {
14658 // C++ [dcl.type.elab]p3:
14659 // The class-key or enum keyword present in the
14660 // elaborated-type-specifier shall agree in kind with the
14661 // declaration to which the name in the elaborated-type-specifier
14662 // refers. This rule also applies to the form of
14663 // elaborated-type-specifier that declares a class-name or
14664 // friend class since it can be construed as referring to the
14665 // definition of the class. Thus, in any
14666 // elaborated-type-specifier, the enum keyword shall be used to
14667 // refer to an enumeration (7.2), the union class-key shall be
14668 // used to refer to a union (clause 9), and either the class or
14669 // struct class-key shall be used to refer to a class (clause 9)
14670 // declared using the class or struct class-key.
14671 TagTypeKind OldTag = Previous->getTagKind();
14672 if (OldTag != NewTag &&
14673 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14676 // Tags are compatible, but we might still want to warn on mismatched tags.
14677 // Non-class tags can't be mismatched at this point.
14678 if (!isClassCompatTagKind(NewTag))
14681 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14682 // by our warning analysis. We don't want to warn about mismatches with (eg)
14683 // declarations in system headers that are designed to be specialized, but if
14684 // a user asks us to warn, we should warn if their code contains mismatched
14686 auto IsIgnoredLoc = [&](SourceLocation Loc) {
14687 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14690 if (IsIgnoredLoc(NewTagLoc))
14693 auto IsIgnored = [&](const TagDecl *Tag) {
14694 return IsIgnoredLoc(Tag->getLocation());
14696 while (IsIgnored(Previous)) {
14697 Previous = Previous->getPreviousDecl();
14700 OldTag = Previous->getTagKind();
14703 bool isTemplate = false;
14704 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14705 isTemplate = Record->getDescribedClassTemplate();
14707 if (inTemplateInstantiation()) {
14708 if (OldTag != NewTag) {
14709 // In a template instantiation, do not offer fix-its for tag mismatches
14710 // since they usually mess up the template instead of fixing the problem.
14711 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14712 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14713 << getRedeclDiagFromTagKind(OldTag);
14714 // FIXME: Note previous location?
14719 if (isDefinition) {
14720 // On definitions, check all previous tags and issue a fix-it for each
14721 // one that doesn't match the current tag.
14722 if (Previous->getDefinition()) {
14723 // Don't suggest fix-its for redefinitions.
14727 bool previousMismatch = false;
14728 for (const TagDecl *I : Previous->redecls()) {
14729 if (I->getTagKind() != NewTag) {
14730 // Ignore previous declarations for which the warning was disabled.
14734 if (!previousMismatch) {
14735 previousMismatch = true;
14736 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14737 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14738 << getRedeclDiagFromTagKind(I->getTagKind());
14740 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14741 << getRedeclDiagFromTagKind(NewTag)
14742 << FixItHint::CreateReplacement(I->getInnerLocStart(),
14743 TypeWithKeyword::getTagTypeKindName(NewTag));
14749 // Identify the prevailing tag kind: this is the kind of the definition (if
14750 // there is a non-ignored definition), or otherwise the kind of the prior
14751 // (non-ignored) declaration.
14752 const TagDecl *PrevDef = Previous->getDefinition();
14753 if (PrevDef && IsIgnored(PrevDef))
14755 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14756 if (Redecl->getTagKind() != NewTag) {
14757 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14758 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14759 << getRedeclDiagFromTagKind(OldTag);
14760 Diag(Redecl->getLocation(), diag::note_previous_use);
14762 // If there is a previous definition, suggest a fix-it.
14764 Diag(NewTagLoc, diag::note_struct_class_suggestion)
14765 << getRedeclDiagFromTagKind(Redecl->getTagKind())
14766 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14767 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14774 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14775 /// from an outer enclosing namespace or file scope inside a friend declaration.
14776 /// This should provide the commented out code in the following snippet:
14780 /// struct Y { friend struct /*N::*/ X; };
14783 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14784 SourceLocation NameLoc) {
14785 // While the decl is in a namespace, do repeated lookup of that name and see
14786 // if we get the same namespace back. If we do not, continue until
14787 // translation unit scope, at which point we have a fully qualified NNS.
14788 SmallVector<IdentifierInfo *, 4> Namespaces;
14789 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14790 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14791 // This tag should be declared in a namespace, which can only be enclosed by
14792 // other namespaces. Bail if there's an anonymous namespace in the chain.
14793 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14794 if (!Namespace || Namespace->isAnonymousNamespace())
14795 return FixItHint();
14796 IdentifierInfo *II = Namespace->getIdentifier();
14797 Namespaces.push_back(II);
14798 NamedDecl *Lookup = SemaRef.LookupSingleName(
14799 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14800 if (Lookup == Namespace)
14804 // Once we have all the namespaces, reverse them to go outermost first, and
14806 SmallString<64> Insertion;
14807 llvm::raw_svector_ostream OS(Insertion);
14808 if (DC->isTranslationUnit())
14810 std::reverse(Namespaces.begin(), Namespaces.end());
14811 for (auto *II : Namespaces)
14812 OS << II->getName() << "::";
14813 return FixItHint::CreateInsertion(NameLoc, Insertion);
14816 /// Determine whether a tag originally declared in context \p OldDC can
14817 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14818 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14819 /// using-declaration).
14820 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14821 DeclContext *NewDC) {
14822 OldDC = OldDC->getRedeclContext();
14823 NewDC = NewDC->getRedeclContext();
14825 if (OldDC->Equals(NewDC))
14828 // In MSVC mode, we allow a redeclaration if the contexts are related (either
14829 // encloses the other).
14830 if (S.getLangOpts().MSVCCompat &&
14831 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14837 /// This is invoked when we see 'struct foo' or 'struct {'. In the
14838 /// former case, Name will be non-null. In the later case, Name will be null.
14839 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14840 /// reference/declaration/definition of a tag.
14842 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14843 /// trailing-type-specifier) other than one in an alias-declaration.
14845 /// \param SkipBody If non-null, will be set to indicate if the caller should
14846 /// skip the definition of this tag and treat it as if it were a declaration.
14847 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14848 SourceLocation KWLoc, CXXScopeSpec &SS,
14849 IdentifierInfo *Name, SourceLocation NameLoc,
14850 const ParsedAttributesView &Attrs, AccessSpecifier AS,
14851 SourceLocation ModulePrivateLoc,
14852 MultiTemplateParamsArg TemplateParameterLists,
14853 bool &OwnedDecl, bool &IsDependent,
14854 SourceLocation ScopedEnumKWLoc,
14855 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14856 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14857 SkipBodyInfo *SkipBody) {
14858 // If this is not a definition, it must have a name.
14859 IdentifierInfo *OrigName = Name;
14860 assert((Name != nullptr || TUK == TUK_Definition) &&
14861 "Nameless record must be a definition!");
14862 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14865 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14866 bool ScopedEnum = ScopedEnumKWLoc.isValid();
14868 // FIXME: Check member specializations more carefully.
14869 bool isMemberSpecialization = false;
14870 bool Invalid = false;
14872 // We only need to do this matching if we have template parameters
14873 // or a scope specifier, which also conveniently avoids this work
14874 // for non-C++ cases.
14875 if (TemplateParameterLists.size() > 0 ||
14876 (SS.isNotEmpty() && TUK != TUK_Reference)) {
14877 if (TemplateParameterList *TemplateParams =
14878 MatchTemplateParametersToScopeSpecifier(
14879 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14880 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14881 if (Kind == TTK_Enum) {
14882 Diag(KWLoc, diag::err_enum_template);
14886 if (TemplateParams->size() > 0) {
14887 // This is a declaration or definition of a class template (which may
14888 // be a member of another template).
14894 DeclResult Result = CheckClassTemplate(
14895 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14896 AS, ModulePrivateLoc,
14897 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14898 TemplateParameterLists.data(), SkipBody);
14899 return Result.get();
14901 // The "template<>" header is extraneous.
14902 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14903 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14904 isMemberSpecialization = true;
14909 // Figure out the underlying type if this a enum declaration. We need to do
14910 // this early, because it's needed to detect if this is an incompatible
14912 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14913 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14915 if (Kind == TTK_Enum) {
14916 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14917 // No underlying type explicitly specified, or we failed to parse the
14918 // type, default to int.
14919 EnumUnderlying = Context.IntTy.getTypePtr();
14920 } else if (UnderlyingType.get()) {
14921 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14922 // integral type; any cv-qualification is ignored.
14923 TypeSourceInfo *TI = nullptr;
14924 GetTypeFromParser(UnderlyingType.get(), &TI);
14925 EnumUnderlying = TI;
14927 if (CheckEnumUnderlyingType(TI))
14928 // Recover by falling back to int.
14929 EnumUnderlying = Context.IntTy.getTypePtr();
14931 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14932 UPPC_FixedUnderlyingType))
14933 EnumUnderlying = Context.IntTy.getTypePtr();
14935 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
14936 // For MSVC ABI compatibility, unfixed enums must use an underlying type
14937 // of 'int'. However, if this is an unfixed forward declaration, don't set
14938 // the underlying type unless the user enables -fms-compatibility. This
14939 // makes unfixed forward declared enums incomplete and is more conforming.
14940 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14941 EnumUnderlying = Context.IntTy.getTypePtr();
14945 DeclContext *SearchDC = CurContext;
14946 DeclContext *DC = CurContext;
14947 bool isStdBadAlloc = false;
14948 bool isStdAlignValT = false;
14950 RedeclarationKind Redecl = forRedeclarationInCurContext();
14951 if (TUK == TUK_Friend || TUK == TUK_Reference)
14952 Redecl = NotForRedeclaration;
14954 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14955 /// implemented asks for structural equivalence checking, the returned decl
14956 /// here is passed back to the parser, allowing the tag body to be parsed.
14957 auto createTagFromNewDecl = [&]() -> TagDecl * {
14958 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14959 // If there is an identifier, use the location of the identifier as the
14960 // location of the decl, otherwise use the location of the struct/union
14962 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14963 TagDecl *New = nullptr;
14965 if (Kind == TTK_Enum) {
14966 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14967 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14968 // If this is an undefined enum, bail.
14969 if (TUK != TUK_Definition && !Invalid)
14971 if (EnumUnderlying) {
14972 EnumDecl *ED = cast<EnumDecl>(New);
14973 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14974 ED->setIntegerTypeSourceInfo(TI);
14976 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14977 ED->setPromotionType(ED->getIntegerType());
14979 } else { // struct/union
14980 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14984 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14985 // Add alignment attributes if necessary; these attributes are checked
14986 // when the ASTContext lays out the structure.
14988 // It is important for implementing the correct semantics that this
14989 // happen here (in ActOnTag). The #pragma pack stack is
14990 // maintained as a result of parser callbacks which can occur at
14991 // many points during the parsing of a struct declaration (because
14992 // the #pragma tokens are effectively skipped over during the
14993 // parsing of the struct).
14994 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14995 AddAlignmentAttributesForRecord(RD);
14996 AddMsStructLayoutForRecord(RD);
14999 New->setLexicalDeclContext(CurContext);
15003 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15004 if (Name && SS.isNotEmpty()) {
15005 // We have a nested-name tag ('struct foo::bar').
15007 // Check for invalid 'foo::'.
15008 if (SS.isInvalid()) {
15010 goto CreateNewDecl;
15013 // If this is a friend or a reference to a class in a dependent
15014 // context, don't try to make a decl for it.
15015 if (TUK == TUK_Friend || TUK == TUK_Reference) {
15016 DC = computeDeclContext(SS, false);
15018 IsDependent = true;
15022 DC = computeDeclContext(SS, true);
15024 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15030 if (RequireCompleteDeclContext(SS, DC))
15034 // Look-up name inside 'foo::'.
15035 LookupQualifiedName(Previous, DC);
15037 if (Previous.isAmbiguous())
15040 if (Previous.empty()) {
15041 // Name lookup did not find anything. However, if the
15042 // nested-name-specifier refers to the current instantiation,
15043 // and that current instantiation has any dependent base
15044 // classes, we might find something at instantiation time: treat
15045 // this as a dependent elaborated-type-specifier.
15046 // But this only makes any sense for reference-like lookups.
15047 if (Previous.wasNotFoundInCurrentInstantiation() &&
15048 (TUK == TUK_Reference || TUK == TUK_Friend)) {
15049 IsDependent = true;
15053 // A tag 'foo::bar' must already exist.
15054 Diag(NameLoc, diag::err_not_tag_in_scope)
15055 << Kind << Name << DC << SS.getRange();
15058 goto CreateNewDecl;
15061 // C++14 [class.mem]p14:
15062 // If T is the name of a class, then each of the following shall have a
15063 // name different from T:
15064 // -- every member of class T that is itself a type
15065 if (TUK != TUK_Reference && TUK != TUK_Friend &&
15066 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15069 // If this is a named struct, check to see if there was a previous forward
15070 // declaration or definition.
15071 // FIXME: We're looking into outer scopes here, even when we
15072 // shouldn't be. Doing so can result in ambiguities that we
15073 // shouldn't be diagnosing.
15074 LookupName(Previous, S);
15076 // When declaring or defining a tag, ignore ambiguities introduced
15077 // by types using'ed into this scope.
15078 if (Previous.isAmbiguous() &&
15079 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15080 LookupResult::Filter F = Previous.makeFilter();
15081 while (F.hasNext()) {
15082 NamedDecl *ND = F.next();
15083 if (!ND->getDeclContext()->getRedeclContext()->Equals(
15084 SearchDC->getRedeclContext()))
15090 // C++11 [namespace.memdef]p3:
15091 // If the name in a friend declaration is neither qualified nor
15092 // a template-id and the declaration is a function or an
15093 // elaborated-type-specifier, the lookup to determine whether
15094 // the entity has been previously declared shall not consider
15095 // any scopes outside the innermost enclosing namespace.
15097 // MSVC doesn't implement the above rule for types, so a friend tag
15098 // declaration may be a redeclaration of a type declared in an enclosing
15099 // scope. They do implement this rule for friend functions.
15101 // Does it matter that this should be by scope instead of by
15102 // semantic context?
15103 if (!Previous.empty() && TUK == TUK_Friend) {
15104 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15105 LookupResult::Filter F = Previous.makeFilter();
15106 bool FriendSawTagOutsideEnclosingNamespace = false;
15107 while (F.hasNext()) {
15108 NamedDecl *ND = F.next();
15109 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15110 if (DC->isFileContext() &&
15111 !EnclosingNS->Encloses(ND->getDeclContext())) {
15112 if (getLangOpts().MSVCCompat)
15113 FriendSawTagOutsideEnclosingNamespace = true;
15120 // Diagnose this MSVC extension in the easy case where lookup would have
15121 // unambiguously found something outside the enclosing namespace.
15122 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15123 NamedDecl *ND = Previous.getFoundDecl();
15124 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15125 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15129 // Note: there used to be some attempt at recovery here.
15130 if (Previous.isAmbiguous())
15133 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15134 // FIXME: This makes sure that we ignore the contexts associated
15135 // with C structs, unions, and enums when looking for a matching
15136 // tag declaration or definition. See the similar lookup tweak
15137 // in Sema::LookupName; is there a better way to deal with this?
15138 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15139 SearchDC = SearchDC->getParent();
15143 if (Previous.isSingleResult() &&
15144 Previous.getFoundDecl()->isTemplateParameter()) {
15145 // Maybe we will complain about the shadowed template parameter.
15146 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15147 // Just pretend that we didn't see the previous declaration.
15151 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15152 DC->Equals(getStdNamespace())) {
15153 if (Name->isStr("bad_alloc")) {
15154 // This is a declaration of or a reference to "std::bad_alloc".
15155 isStdBadAlloc = true;
15157 // If std::bad_alloc has been implicitly declared (but made invisible to
15158 // name lookup), fill in this implicit declaration as the previous
15159 // declaration, so that the declarations get chained appropriately.
15160 if (Previous.empty() && StdBadAlloc)
15161 Previous.addDecl(getStdBadAlloc());
15162 } else if (Name->isStr("align_val_t")) {
15163 isStdAlignValT = true;
15164 if (Previous.empty() && StdAlignValT)
15165 Previous.addDecl(getStdAlignValT());
15169 // If we didn't find a previous declaration, and this is a reference
15170 // (or friend reference), move to the correct scope. In C++, we
15171 // also need to do a redeclaration lookup there, just in case
15172 // there's a shadow friend decl.
15173 if (Name && Previous.empty() &&
15174 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15175 if (Invalid) goto CreateNewDecl;
15176 assert(SS.isEmpty());
15178 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15179 // C++ [basic.scope.pdecl]p5:
15180 // -- for an elaborated-type-specifier of the form
15182 // class-key identifier
15184 // if the elaborated-type-specifier is used in the
15185 // decl-specifier-seq or parameter-declaration-clause of a
15186 // function defined in namespace scope, the identifier is
15187 // declared as a class-name in the namespace that contains
15188 // the declaration; otherwise, except as a friend
15189 // declaration, the identifier is declared in the smallest
15190 // non-class, non-function-prototype scope that contains the
15193 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15194 // C structs and unions.
15196 // It is an error in C++ to declare (rather than define) an enum
15197 // type, including via an elaborated type specifier. We'll
15198 // diagnose that later; for now, declare the enum in the same
15199 // scope as we would have picked for any other tag type.
15201 // GNU C also supports this behavior as part of its incomplete
15202 // enum types extension, while GNU C++ does not.
15204 // Find the context where we'll be declaring the tag.
15205 // FIXME: We would like to maintain the current DeclContext as the
15206 // lexical context,
15207 SearchDC = getTagInjectionContext(SearchDC);
15209 // Find the scope where we'll be declaring the tag.
15210 S = getTagInjectionScope(S, getLangOpts());
15212 assert(TUK == TUK_Friend);
15213 // C++ [namespace.memdef]p3:
15214 // If a friend declaration in a non-local class first declares a
15215 // class or function, the friend class or function is a member of
15216 // the innermost enclosing namespace.
15217 SearchDC = SearchDC->getEnclosingNamespaceContext();
15220 // In C++, we need to do a redeclaration lookup to properly
15221 // diagnose some problems.
15222 // FIXME: redeclaration lookup is also used (with and without C++) to find a
15223 // hidden declaration so that we don't get ambiguity errors when using a
15224 // type declared by an elaborated-type-specifier. In C that is not correct
15225 // and we should instead merge compatible types found by lookup.
15226 if (getLangOpts().CPlusPlus) {
15227 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15228 LookupQualifiedName(Previous, SearchDC);
15230 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15231 LookupName(Previous, S);
15235 // If we have a known previous declaration to use, then use it.
15236 if (Previous.empty() && SkipBody && SkipBody->Previous)
15237 Previous.addDecl(SkipBody->Previous);
15239 if (!Previous.empty()) {
15240 NamedDecl *PrevDecl = Previous.getFoundDecl();
15241 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15243 // It's okay to have a tag decl in the same scope as a typedef
15244 // which hides a tag decl in the same scope. Finding this
15245 // insanity with a redeclaration lookup can only actually happen
15248 // This is also okay for elaborated-type-specifiers, which is
15249 // technically forbidden by the current standard but which is
15250 // okay according to the likely resolution of an open issue;
15251 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15252 if (getLangOpts().CPlusPlus) {
15253 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15254 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15255 TagDecl *Tag = TT->getDecl();
15256 if (Tag->getDeclName() == Name &&
15257 Tag->getDeclContext()->getRedeclContext()
15258 ->Equals(TD->getDeclContext()->getRedeclContext())) {
15261 Previous.addDecl(Tag);
15262 Previous.resolveKind();
15268 // If this is a redeclaration of a using shadow declaration, it must
15269 // declare a tag in the same context. In MSVC mode, we allow a
15270 // redefinition if either context is within the other.
15271 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15272 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15273 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15274 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15275 !(OldTag && isAcceptableTagRedeclContext(
15276 *this, OldTag->getDeclContext(), SearchDC))) {
15277 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15278 Diag(Shadow->getTargetDecl()->getLocation(),
15279 diag::note_using_decl_target);
15280 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15282 // Recover by ignoring the old declaration.
15284 goto CreateNewDecl;
15288 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15289 // If this is a use of a previous tag, or if the tag is already declared
15290 // in the same scope (so that the definition/declaration completes or
15291 // rementions the tag), reuse the decl.
15292 if (TUK == TUK_Reference || TUK == TUK_Friend ||
15293 isDeclInScope(DirectPrevDecl, SearchDC, S,
15294 SS.isNotEmpty() || isMemberSpecialization)) {
15295 // Make sure that this wasn't declared as an enum and now used as a
15296 // struct or something similar.
15297 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15298 TUK == TUK_Definition, KWLoc,
15300 bool SafeToContinue
15301 = (PrevTagDecl->getTagKind() != TTK_Enum &&
15303 if (SafeToContinue)
15304 Diag(KWLoc, diag::err_use_with_wrong_tag)
15306 << FixItHint::CreateReplacement(SourceRange(KWLoc),
15307 PrevTagDecl->getKindName());
15309 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15310 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15312 if (SafeToContinue)
15313 Kind = PrevTagDecl->getTagKind();
15315 // Recover by making this an anonymous redefinition.
15322 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15323 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15325 // If this is an elaborated-type-specifier for a scoped enumeration,
15326 // the 'class' keyword is not necessary and not permitted.
15327 if (TUK == TUK_Reference || TUK == TUK_Friend) {
15329 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
15330 << PrevEnum->isScoped()
15331 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
15332 return PrevTagDecl;
15335 QualType EnumUnderlyingTy;
15336 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15337 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15338 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15339 EnumUnderlyingTy = QualType(T, 0);
15341 // All conflicts with previous declarations are recovered by
15342 // returning the previous declaration, unless this is a definition,
15343 // in which case we want the caller to bail out.
15344 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15345 ScopedEnum, EnumUnderlyingTy,
15346 IsFixed, PrevEnum))
15347 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15350 // C++11 [class.mem]p1:
15351 // A member shall not be declared twice in the member-specification,
15352 // except that a nested class or member class template can be declared
15353 // and then later defined.
15354 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15355 S->isDeclScope(PrevDecl)) {
15356 Diag(NameLoc, diag::ext_member_redeclared);
15357 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15361 // If this is a use, just return the declaration we found, unless
15362 // we have attributes.
15363 if (TUK == TUK_Reference || TUK == TUK_Friend) {
15364 if (!Attrs.empty()) {
15365 // FIXME: Diagnose these attributes. For now, we create a new
15366 // declaration to hold them.
15367 } else if (TUK == TUK_Reference &&
15368 (PrevTagDecl->getFriendObjectKind() ==
15369 Decl::FOK_Undeclared ||
15370 PrevDecl->getOwningModule() != getCurrentModule()) &&
15372 // This declaration is a reference to an existing entity, but
15373 // has different visibility from that entity: it either makes
15374 // a friend visible or it makes a type visible in a new module.
15375 // In either case, create a new declaration. We only do this if
15376 // the declaration would have meant the same thing if no prior
15377 // declaration were found, that is, if it was found in the same
15378 // scope where we would have injected a declaration.
15379 if (!getTagInjectionContext(CurContext)->getRedeclContext()
15380 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15381 return PrevTagDecl;
15382 // This is in the injected scope, create a new declaration in
15384 S = getTagInjectionScope(S, getLangOpts());
15386 return PrevTagDecl;
15390 // Diagnose attempts to redefine a tag.
15391 if (TUK == TUK_Definition) {
15392 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15393 // If we're defining a specialization and the previous definition
15394 // is from an implicit instantiation, don't emit an error
15395 // here; we'll catch this in the general case below.
15396 bool IsExplicitSpecializationAfterInstantiation = false;
15397 if (isMemberSpecialization) {
15398 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15399 IsExplicitSpecializationAfterInstantiation =
15400 RD->getTemplateSpecializationKind() !=
15401 TSK_ExplicitSpecialization;
15402 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15403 IsExplicitSpecializationAfterInstantiation =
15404 ED->getTemplateSpecializationKind() !=
15405 TSK_ExplicitSpecialization;
15408 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15409 // not keep more that one definition around (merge them). However,
15410 // ensure the decl passes the structural compatibility check in
15411 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15412 NamedDecl *Hidden = nullptr;
15413 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15414 // There is a definition of this tag, but it is not visible. We
15415 // explicitly make use of C++'s one definition rule here, and
15416 // assume that this definition is identical to the hidden one
15417 // we already have. Make the existing definition visible and
15418 // use it in place of this one.
15419 if (!getLangOpts().CPlusPlus) {
15420 // Postpone making the old definition visible until after we
15421 // complete parsing the new one and do the structural
15423 SkipBody->CheckSameAsPrevious = true;
15424 SkipBody->New = createTagFromNewDecl();
15425 SkipBody->Previous = Def;
15428 SkipBody->ShouldSkip = true;
15429 SkipBody->Previous = Def;
15430 makeMergedDefinitionVisible(Hidden);
15431 // Carry on and handle it like a normal definition. We'll
15432 // skip starting the definitiion later.
15434 } else if (!IsExplicitSpecializationAfterInstantiation) {
15435 // A redeclaration in function prototype scope in C isn't
15436 // visible elsewhere, so merely issue a warning.
15437 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15438 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15440 Diag(NameLoc, diag::err_redefinition) << Name;
15441 notePreviousDefinition(Def,
15442 NameLoc.isValid() ? NameLoc : KWLoc);
15443 // If this is a redefinition, recover by making this
15444 // struct be anonymous, which will make any later
15445 // references get the previous definition.
15451 // If the type is currently being defined, complain
15452 // about a nested redefinition.
15453 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15454 if (TD->isBeingDefined()) {
15455 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15456 Diag(PrevTagDecl->getLocation(),
15457 diag::note_previous_definition);
15464 // Okay, this is definition of a previously declared or referenced
15465 // tag. We're going to create a new Decl for it.
15468 // Okay, we're going to make a redeclaration. If this is some kind
15469 // of reference, make sure we build the redeclaration in the same DC
15470 // as the original, and ignore the current access specifier.
15471 if (TUK == TUK_Friend || TUK == TUK_Reference) {
15472 SearchDC = PrevTagDecl->getDeclContext();
15476 // If we get here we have (another) forward declaration or we
15477 // have a definition. Just create a new decl.
15480 // If we get here, this is a definition of a new tag type in a nested
15481 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15482 // new decl/type. We set PrevDecl to NULL so that the entities
15483 // have distinct types.
15486 // If we get here, we're going to create a new Decl. If PrevDecl
15487 // is non-NULL, it's a definition of the tag declared by
15488 // PrevDecl. If it's NULL, we have a new definition.
15490 // Otherwise, PrevDecl is not a tag, but was found with tag
15491 // lookup. This is only actually possible in C++, where a few
15492 // things like templates still live in the tag namespace.
15494 // Use a better diagnostic if an elaborated-type-specifier
15495 // found the wrong kind of type on the first
15496 // (non-redeclaration) lookup.
15497 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15498 !Previous.isForRedeclaration()) {
15499 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15500 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15502 Diag(PrevDecl->getLocation(), diag::note_declared_at);
15505 // Otherwise, only diagnose if the declaration is in scope.
15506 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15507 SS.isNotEmpty() || isMemberSpecialization)) {
15510 // Diagnose implicit declarations introduced by elaborated types.
15511 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15512 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15513 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15514 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15517 // Otherwise it's a declaration. Call out a particularly common
15519 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15521 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15522 Diag(NameLoc, diag::err_tag_definition_of_typedef)
15523 << Name << Kind << TND->getUnderlyingType();
15524 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15527 // Otherwise, diagnose.
15529 // The tag name clashes with something else in the target scope,
15530 // issue an error and recover by making this tag be anonymous.
15531 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15532 notePreviousDefinition(PrevDecl, NameLoc);
15537 // The existing declaration isn't relevant to us; we're in a
15538 // new scope, so clear out the previous declaration.
15545 TagDecl *PrevDecl = nullptr;
15546 if (Previous.isSingleResult())
15547 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15549 // If there is an identifier, use the location of the identifier as the
15550 // location of the decl, otherwise use the location of the struct/union
15552 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15554 // Otherwise, create a new declaration. If there is a previous
15555 // declaration of the same entity, the two will be linked via
15559 if (Kind == TTK_Enum) {
15560 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15561 // enum X { A, B, C } D; D should chain to X.
15562 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15563 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15564 ScopedEnumUsesClassTag, IsFixed);
15566 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15567 StdAlignValT = cast<EnumDecl>(New);
15569 // If this is an undefined enum, warn.
15570 if (TUK != TUK_Definition && !Invalid) {
15572 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15573 // C++0x: 7.2p2: opaque-enum-declaration.
15574 // Conflicts are diagnosed above. Do nothing.
15576 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15577 Diag(Loc, diag::ext_forward_ref_enum_def)
15579 Diag(Def->getLocation(), diag::note_previous_definition);
15581 unsigned DiagID = diag::ext_forward_ref_enum;
15582 if (getLangOpts().MSVCCompat)
15583 DiagID = diag::ext_ms_forward_ref_enum;
15584 else if (getLangOpts().CPlusPlus)
15585 DiagID = diag::err_forward_ref_enum;
15590 if (EnumUnderlying) {
15591 EnumDecl *ED = cast<EnumDecl>(New);
15592 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15593 ED->setIntegerTypeSourceInfo(TI);
15595 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15596 ED->setPromotionType(ED->getIntegerType());
15597 assert(ED->isComplete() && "enum with type should be complete");
15600 // struct/union/class
15602 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15603 // struct X { int A; } D; D should chain to X.
15604 if (getLangOpts().CPlusPlus) {
15605 // FIXME: Look for a way to use RecordDecl for simple structs.
15606 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15607 cast_or_null<CXXRecordDecl>(PrevDecl));
15609 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15610 StdBadAlloc = cast<CXXRecordDecl>(New);
15612 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15613 cast_or_null<RecordDecl>(PrevDecl));
15616 // C++11 [dcl.type]p3:
15617 // A type-specifier-seq shall not define a class or enumeration [...].
15618 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15619 TUK == TUK_Definition) {
15620 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15621 << Context.getTagDeclType(New);
15625 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15626 DC->getDeclKind() == Decl::Enum) {
15627 Diag(New->getLocation(), diag::err_type_defined_in_enum)
15628 << Context.getTagDeclType(New);
15632 // Maybe add qualifier info.
15633 if (SS.isNotEmpty()) {
15635 // If this is either a declaration or a definition, check the
15636 // nested-name-specifier against the current context.
15637 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15638 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15639 isMemberSpecialization))
15642 New->setQualifierInfo(SS.getWithLocInContext(Context));
15643 if (TemplateParameterLists.size() > 0) {
15644 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15651 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15652 // Add alignment attributes if necessary; these attributes are checked when
15653 // the ASTContext lays out the structure.
15655 // It is important for implementing the correct semantics that this
15656 // happen here (in ActOnTag). The #pragma pack stack is
15657 // maintained as a result of parser callbacks which can occur at
15658 // many points during the parsing of a struct declaration (because
15659 // the #pragma tokens are effectively skipped over during the
15660 // parsing of the struct).
15661 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15662 AddAlignmentAttributesForRecord(RD);
15663 AddMsStructLayoutForRecord(RD);
15667 if (ModulePrivateLoc.isValid()) {
15668 if (isMemberSpecialization)
15669 Diag(New->getLocation(), diag::err_module_private_specialization)
15671 << FixItHint::CreateRemoval(ModulePrivateLoc);
15672 // __module_private__ does not apply to local classes. However, we only
15673 // diagnose this as an error when the declaration specifiers are
15674 // freestanding. Here, we just ignore the __module_private__.
15675 else if (!SearchDC->isFunctionOrMethod())
15676 New->setModulePrivate();
15679 // If this is a specialization of a member class (of a class template),
15680 // check the specialization.
15681 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15684 // If we're declaring or defining a tag in function prototype scope in C,
15685 // note that this type can only be used within the function and add it to
15686 // the list of decls to inject into the function definition scope.
15687 if ((Name || Kind == TTK_Enum) &&
15688 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15689 if (getLangOpts().CPlusPlus) {
15690 // C++ [dcl.fct]p6:
15691 // Types shall not be defined in return or parameter types.
15692 if (TUK == TUK_Definition && !IsTypeSpecifier) {
15693 Diag(Loc, diag::err_type_defined_in_param_type)
15697 } else if (!PrevDecl) {
15698 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15703 New->setInvalidDecl();
15705 // Set the lexical context. If the tag has a C++ scope specifier, the
15706 // lexical context will be different from the semantic context.
15707 New->setLexicalDeclContext(CurContext);
15709 // Mark this as a friend decl if applicable.
15710 // In Microsoft mode, a friend declaration also acts as a forward
15711 // declaration so we always pass true to setObjectOfFriendDecl to make
15712 // the tag name visible.
15713 if (TUK == TUK_Friend)
15714 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15716 // Set the access specifier.
15717 if (!Invalid && SearchDC->isRecord())
15718 SetMemberAccessSpecifier(New, PrevDecl, AS);
15721 CheckRedeclarationModuleOwnership(New, PrevDecl);
15723 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15724 New->startDefinition();
15726 ProcessDeclAttributeList(S, New, Attrs);
15727 AddPragmaAttributes(S, New);
15729 // If this has an identifier, add it to the scope stack.
15730 if (TUK == TUK_Friend) {
15731 // We might be replacing an existing declaration in the lookup tables;
15732 // if so, borrow its access specifier.
15734 New->setAccess(PrevDecl->getAccess());
15736 DeclContext *DC = New->getDeclContext()->getRedeclContext();
15737 DC->makeDeclVisibleInContext(New);
15738 if (Name) // can be null along some error paths
15739 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15740 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15742 S = getNonFieldDeclScope(S);
15743 PushOnScopeChains(New, S, true);
15745 CurContext->addDecl(New);
15748 // If this is the C FILE type, notify the AST context.
15749 if (IdentifierInfo *II = New->getIdentifier())
15750 if (!New->isInvalidDecl() &&
15751 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15753 Context.setFILEDecl(New);
15756 mergeDeclAttributes(New, PrevDecl);
15758 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
15759 inferGslOwnerPointerAttribute(CXXRD);
15761 // If there's a #pragma GCC visibility in scope, set the visibility of this
15763 AddPushedVisibilityAttribute(New);
15765 if (isMemberSpecialization && !New->isInvalidDecl())
15766 CompleteMemberSpecialization(New, Previous);
15769 // In C++, don't return an invalid declaration. We can't recover well from
15770 // the cases where we make the type anonymous.
15771 if (Invalid && getLangOpts().CPlusPlus) {
15772 if (New->isBeingDefined())
15773 if (auto RD = dyn_cast<RecordDecl>(New))
15774 RD->completeDefinition();
15776 } else if (SkipBody && SkipBody->ShouldSkip) {
15777 return SkipBody->Previous;
15783 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15784 AdjustDeclIfTemplate(TagD);
15785 TagDecl *Tag = cast<TagDecl>(TagD);
15787 // Enter the tag context.
15788 PushDeclContext(S, Tag);
15790 ActOnDocumentableDecl(TagD);
15792 // If there's a #pragma GCC visibility in scope, set the visibility of this
15794 AddPushedVisibilityAttribute(Tag);
15797 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15798 SkipBodyInfo &SkipBody) {
15799 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15802 // Make the previous decl visible.
15803 makeMergedDefinitionVisible(SkipBody.Previous);
15807 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15808 assert(isa<ObjCContainerDecl>(IDecl) &&
15809 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15810 DeclContext *OCD = cast<DeclContext>(IDecl);
15811 assert(getContainingDC(OCD) == CurContext &&
15812 "The next DeclContext should be lexically contained in the current one.");
15817 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15818 SourceLocation FinalLoc,
15819 bool IsFinalSpelledSealed,
15820 SourceLocation LBraceLoc) {
15821 AdjustDeclIfTemplate(TagD);
15822 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15824 FieldCollector->StartClass();
15826 if (!Record->getIdentifier())
15829 if (FinalLoc.isValid())
15830 Record->addAttr(FinalAttr::Create(
15831 Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
15832 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
15835 // [...] The class-name is also inserted into the scope of the
15836 // class itself; this is known as the injected-class-name. For
15837 // purposes of access checking, the injected-class-name is treated
15838 // as if it were a public member name.
15839 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15840 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15841 Record->getLocation(), Record->getIdentifier(),
15842 /*PrevDecl=*/nullptr,
15843 /*DelayTypeCreation=*/true);
15844 Context.getTypeDeclType(InjectedClassName, Record);
15845 InjectedClassName->setImplicit();
15846 InjectedClassName->setAccess(AS_public);
15847 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15848 InjectedClassName->setDescribedClassTemplate(Template);
15849 PushOnScopeChains(InjectedClassName, S);
15850 assert(InjectedClassName->isInjectedClassName() &&
15851 "Broken injected-class-name");
15854 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15855 SourceRange BraceRange) {
15856 AdjustDeclIfTemplate(TagD);
15857 TagDecl *Tag = cast<TagDecl>(TagD);
15858 Tag->setBraceRange(BraceRange);
15860 // Make sure we "complete" the definition even it is invalid.
15861 if (Tag->isBeingDefined()) {
15862 assert(Tag->isInvalidDecl() && "We should already have completed it");
15863 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15864 RD->completeDefinition();
15867 if (isa<CXXRecordDecl>(Tag)) {
15868 FieldCollector->FinishClass();
15871 // Exit this scope of this tag's definition.
15874 if (getCurLexicalContext()->isObjCContainer() &&
15875 Tag->getDeclContext()->isFileContext())
15876 Tag->setTopLevelDeclInObjCContainer();
15878 // Notify the consumer that we've defined a tag.
15879 if (!Tag->isInvalidDecl())
15880 Consumer.HandleTagDeclDefinition(Tag);
15883 void Sema::ActOnObjCContainerFinishDefinition() {
15884 // Exit this scope of this interface definition.
15888 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15889 assert(DC == CurContext && "Mismatch of container contexts");
15890 OriginalLexicalContext = DC;
15891 ActOnObjCContainerFinishDefinition();
15894 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15895 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15896 OriginalLexicalContext = nullptr;
15899 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15900 AdjustDeclIfTemplate(TagD);
15901 TagDecl *Tag = cast<TagDecl>(TagD);
15902 Tag->setInvalidDecl();
15904 // Make sure we "complete" the definition even it is invalid.
15905 if (Tag->isBeingDefined()) {
15906 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15907 RD->completeDefinition();
15910 // We're undoing ActOnTagStartDefinition here, not
15911 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15912 // the FieldCollector.
15917 // Note that FieldName may be null for anonymous bitfields.
15918 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15919 IdentifierInfo *FieldName,
15920 QualType FieldTy, bool IsMsStruct,
15921 Expr *BitWidth, bool *ZeroWidth) {
15922 // Default to true; that shouldn't confuse checks for emptiness
15926 // C99 6.7.2.1p4 - verify the field type.
15927 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15928 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15929 // Handle incomplete types with specific error.
15930 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15931 return ExprError();
15933 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15934 << FieldName << FieldTy << BitWidth->getSourceRange();
15935 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15936 << FieldTy << BitWidth->getSourceRange();
15937 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15938 UPPC_BitFieldWidth))
15939 return ExprError();
15941 // If the bit-width is type- or value-dependent, don't try to check
15943 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15946 llvm::APSInt Value;
15947 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15948 if (ICE.isInvalid())
15950 BitWidth = ICE.get();
15952 if (Value != 0 && ZeroWidth)
15953 *ZeroWidth = false;
15955 // Zero-width bitfield is ok for anonymous field.
15956 if (Value == 0 && FieldName)
15957 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15959 if (Value.isSigned() && Value.isNegative()) {
15961 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15962 << FieldName << Value.toString(10);
15963 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15964 << Value.toString(10);
15967 if (!FieldTy->isDependentType()) {
15968 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15969 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15970 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15972 // Over-wide bitfields are an error in C or when using the MSVC bitfield
15974 bool CStdConstraintViolation =
15975 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15976 bool MSBitfieldViolation =
15977 Value.ugt(TypeStorageSize) &&
15978 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15979 if (CStdConstraintViolation || MSBitfieldViolation) {
15980 unsigned DiagWidth =
15981 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15983 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15984 << FieldName << (unsigned)Value.getZExtValue()
15985 << !CStdConstraintViolation << DiagWidth;
15987 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15988 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15992 // Warn on types where the user might conceivably expect to get all
15993 // specified bits as value bits: that's all integral types other than
15995 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15997 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15998 << FieldName << (unsigned)Value.getZExtValue()
15999 << (unsigned)TypeWidth;
16001 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
16002 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
16009 /// ActOnField - Each field of a C struct/union is passed into this in order
16010 /// to create a FieldDecl object for it.
16011 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16012 Declarator &D, Expr *BitfieldWidth) {
16013 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16014 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16015 /*InitStyle=*/ICIS_NoInit, AS_public);
16019 /// HandleField - Analyze a field of a C struct or a C++ data member.
16021 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16022 SourceLocation DeclStart,
16023 Declarator &D, Expr *BitWidth,
16024 InClassInitStyle InitStyle,
16025 AccessSpecifier AS) {
16026 if (D.isDecompositionDeclarator()) {
16027 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16028 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16029 << Decomp.getSourceRange();
16033 IdentifierInfo *II = D.getIdentifier();
16034 SourceLocation Loc = DeclStart;
16035 if (II) Loc = D.getIdentifierLoc();
16037 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16038 QualType T = TInfo->getType();
16039 if (getLangOpts().CPlusPlus) {
16040 CheckExtraCXXDefaultArguments(D);
16042 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16043 UPPC_DataMemberType)) {
16044 D.setInvalidType();
16046 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16050 DiagnoseFunctionSpecifiers(D.getDeclSpec());
16052 if (D.getDeclSpec().isInlineSpecified())
16053 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16054 << getLangOpts().CPlusPlus17;
16055 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16056 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16057 diag::err_invalid_thread)
16058 << DeclSpec::getSpecifierName(TSCS);
16060 // Check to see if this name was declared as a member previously
16061 NamedDecl *PrevDecl = nullptr;
16062 LookupResult Previous(*this, II, Loc, LookupMemberName,
16063 ForVisibleRedeclaration);
16064 LookupName(Previous, S);
16065 switch (Previous.getResultKind()) {
16066 case LookupResult::Found:
16067 case LookupResult::FoundUnresolvedValue:
16068 PrevDecl = Previous.getAsSingle<NamedDecl>();
16071 case LookupResult::FoundOverloaded:
16072 PrevDecl = Previous.getRepresentativeDecl();
16075 case LookupResult::NotFound:
16076 case LookupResult::NotFoundInCurrentInstantiation:
16077 case LookupResult::Ambiguous:
16080 Previous.suppressDiagnostics();
16082 if (PrevDecl && PrevDecl->isTemplateParameter()) {
16083 // Maybe we will complain about the shadowed template parameter.
16084 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16085 // Just pretend that we didn't see the previous declaration.
16086 PrevDecl = nullptr;
16089 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16090 PrevDecl = nullptr;
16093 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16094 SourceLocation TSSL = D.getBeginLoc();
16096 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16097 TSSL, AS, PrevDecl, &D);
16099 if (NewFD->isInvalidDecl())
16100 Record->setInvalidDecl();
16102 if (D.getDeclSpec().isModulePrivateSpecified())
16103 NewFD->setModulePrivate();
16105 if (NewFD->isInvalidDecl() && PrevDecl) {
16106 // Don't introduce NewFD into scope; there's already something
16107 // with the same name in the same scope.
16109 PushOnScopeChains(NewFD, S);
16111 Record->addDecl(NewFD);
16116 /// Build a new FieldDecl and check its well-formedness.
16118 /// This routine builds a new FieldDecl given the fields name, type,
16119 /// record, etc. \p PrevDecl should refer to any previous declaration
16120 /// with the same name and in the same scope as the field to be
16123 /// \returns a new FieldDecl.
16125 /// \todo The Declarator argument is a hack. It will be removed once
16126 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16127 TypeSourceInfo *TInfo,
16128 RecordDecl *Record, SourceLocation Loc,
16129 bool Mutable, Expr *BitWidth,
16130 InClassInitStyle InitStyle,
16131 SourceLocation TSSL,
16132 AccessSpecifier AS, NamedDecl *PrevDecl,
16134 IdentifierInfo *II = Name.getAsIdentifierInfo();
16135 bool InvalidDecl = false;
16136 if (D) InvalidDecl = D->isInvalidType();
16138 // If we receive a broken type, recover by assuming 'int' and
16139 // marking this declaration as invalid.
16141 InvalidDecl = true;
16145 QualType EltTy = Context.getBaseElementType(T);
16146 if (!EltTy->isDependentType()) {
16147 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
16148 // Fields of incomplete type force their record to be invalid.
16149 Record->setInvalidDecl();
16150 InvalidDecl = true;
16153 EltTy->isIncompleteType(&Def);
16154 if (Def && Def->isInvalidDecl()) {
16155 Record->setInvalidDecl();
16156 InvalidDecl = true;
16161 // TR 18037 does not allow fields to be declared with address space
16162 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16163 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16164 Diag(Loc, diag::err_field_with_address_space);
16165 Record->setInvalidDecl();
16166 InvalidDecl = true;
16169 if (LangOpts.OpenCL) {
16170 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16171 // used as structure or union field: image, sampler, event or block types.
16172 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16173 T->isBlockPointerType()) {
16174 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16175 Record->setInvalidDecl();
16176 InvalidDecl = true;
16178 // OpenCL v1.2 s6.9.c: bitfields are not supported.
16180 Diag(Loc, diag::err_opencl_bitfields);
16181 InvalidDecl = true;
16185 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16186 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16187 T.hasQualifiers()) {
16188 InvalidDecl = true;
16189 Diag(Loc, diag::err_anon_bitfield_qualifiers);
16192 // C99 6.7.2.1p8: A member of a structure or union may have any type other
16193 // than a variably modified type.
16194 if (!InvalidDecl && T->isVariablyModifiedType()) {
16195 bool SizeIsNegative;
16196 llvm::APSInt Oversized;
16198 TypeSourceInfo *FixedTInfo =
16199 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16203 Diag(Loc, diag::warn_illegal_constant_array_size);
16204 TInfo = FixedTInfo;
16205 T = FixedTInfo->getType();
16207 if (SizeIsNegative)
16208 Diag(Loc, diag::err_typecheck_negative_array_size);
16209 else if (Oversized.getBoolValue())
16210 Diag(Loc, diag::err_array_too_large)
16211 << Oversized.toString(10);
16213 Diag(Loc, diag::err_typecheck_field_variable_size);
16214 InvalidDecl = true;
16218 // Fields can not have abstract class types
16219 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16220 diag::err_abstract_type_in_decl,
16221 AbstractFieldType))
16222 InvalidDecl = true;
16224 bool ZeroWidth = false;
16226 BitWidth = nullptr;
16227 // If this is declared as a bit-field, check the bit-field.
16229 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16232 InvalidDecl = true;
16233 BitWidth = nullptr;
16238 // Check that 'mutable' is consistent with the type of the declaration.
16239 if (!InvalidDecl && Mutable) {
16240 unsigned DiagID = 0;
16241 if (T->isReferenceType())
16242 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16243 : diag::err_mutable_reference;
16244 else if (T.isConstQualified())
16245 DiagID = diag::err_mutable_const;
16248 SourceLocation ErrLoc = Loc;
16249 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16250 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16251 Diag(ErrLoc, DiagID);
16252 if (DiagID != diag::ext_mutable_reference) {
16254 InvalidDecl = true;
16259 // C++11 [class.union]p8 (DR1460):
16260 // At most one variant member of a union may have a
16261 // brace-or-equal-initializer.
16262 if (InitStyle != ICIS_NoInit)
16263 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16265 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16266 BitWidth, Mutable, InitStyle);
16268 NewFD->setInvalidDecl();
16270 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16271 Diag(Loc, diag::err_duplicate_member) << II;
16272 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16273 NewFD->setInvalidDecl();
16276 if (!InvalidDecl && getLangOpts().CPlusPlus) {
16277 if (Record->isUnion()) {
16278 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16279 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16280 if (RDecl->getDefinition()) {
16281 // C++ [class.union]p1: An object of a class with a non-trivial
16282 // constructor, a non-trivial copy constructor, a non-trivial
16283 // destructor, or a non-trivial copy assignment operator
16284 // cannot be a member of a union, nor can an array of such
16286 if (CheckNontrivialField(NewFD))
16287 NewFD->setInvalidDecl();
16291 // C++ [class.union]p1: If a union contains a member of reference type,
16292 // the program is ill-formed, except when compiling with MSVC extensions
16294 if (EltTy->isReferenceType()) {
16295 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16296 diag::ext_union_member_of_reference_type :
16297 diag::err_union_member_of_reference_type)
16298 << NewFD->getDeclName() << EltTy;
16299 if (!getLangOpts().MicrosoftExt)
16300 NewFD->setInvalidDecl();
16305 // FIXME: We need to pass in the attributes given an AST
16306 // representation, not a parser representation.
16308 // FIXME: The current scope is almost... but not entirely... correct here.
16309 ProcessDeclAttributes(getCurScope(), NewFD, *D);
16311 if (NewFD->hasAttrs())
16312 CheckAlignasUnderalignment(NewFD);
16315 // In auto-retain/release, infer strong retension for fields of
16316 // retainable type.
16317 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16318 NewFD->setInvalidDecl();
16320 if (T.isObjCGCWeak())
16321 Diag(Loc, diag::warn_attribute_weak_on_field);
16323 NewFD->setAccess(AS);
16327 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16329 assert(getLangOpts().CPlusPlus && "valid check only for C++");
16331 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16334 QualType EltTy = Context.getBaseElementType(FD->getType());
16335 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16336 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16337 if (RDecl->getDefinition()) {
16338 // We check for copy constructors before constructors
16339 // because otherwise we'll never get complaints about
16340 // copy constructors.
16342 CXXSpecialMember member = CXXInvalid;
16343 // We're required to check for any non-trivial constructors. Since the
16344 // implicit default constructor is suppressed if there are any
16345 // user-declared constructors, we just need to check that there is a
16346 // trivial default constructor and a trivial copy constructor. (We don't
16347 // worry about move constructors here, since this is a C++98 check.)
16348 if (RDecl->hasNonTrivialCopyConstructor())
16349 member = CXXCopyConstructor;
16350 else if (!RDecl->hasTrivialDefaultConstructor())
16351 member = CXXDefaultConstructor;
16352 else if (RDecl->hasNonTrivialCopyAssignment())
16353 member = CXXCopyAssignment;
16354 else if (RDecl->hasNonTrivialDestructor())
16355 member = CXXDestructor;
16357 if (member != CXXInvalid) {
16358 if (!getLangOpts().CPlusPlus11 &&
16359 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16360 // Objective-C++ ARC: it is an error to have a non-trivial field of
16361 // a union. However, system headers in Objective-C programs
16362 // occasionally have Objective-C lifetime objects within unions,
16363 // and rather than cause the program to fail, we make those
16364 // members unavailable.
16365 SourceLocation Loc = FD->getLocation();
16366 if (getSourceManager().isInSystemHeader(Loc)) {
16367 if (!FD->hasAttr<UnavailableAttr>())
16368 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16369 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16374 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16375 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16376 diag::err_illegal_union_or_anon_struct_member)
16377 << FD->getParent()->isUnion() << FD->getDeclName() << member;
16378 DiagnoseNontrivial(RDecl, member);
16379 return !getLangOpts().CPlusPlus11;
16387 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16388 /// AST enum value.
16389 static ObjCIvarDecl::AccessControl
16390 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16391 switch (ivarVisibility) {
16392 default: llvm_unreachable("Unknown visitibility kind");
16393 case tok::objc_private: return ObjCIvarDecl::Private;
16394 case tok::objc_public: return ObjCIvarDecl::Public;
16395 case tok::objc_protected: return ObjCIvarDecl::Protected;
16396 case tok::objc_package: return ObjCIvarDecl::Package;
16400 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16401 /// in order to create an IvarDecl object for it.
16402 Decl *Sema::ActOnIvar(Scope *S,
16403 SourceLocation DeclStart,
16404 Declarator &D, Expr *BitfieldWidth,
16405 tok::ObjCKeywordKind Visibility) {
16407 IdentifierInfo *II = D.getIdentifier();
16408 Expr *BitWidth = (Expr*)BitfieldWidth;
16409 SourceLocation Loc = DeclStart;
16410 if (II) Loc = D.getIdentifierLoc();
16412 // FIXME: Unnamed fields can be handled in various different ways, for
16413 // example, unnamed unions inject all members into the struct namespace!
16415 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16416 QualType T = TInfo->getType();
16419 // 6.7.2.1p3, 6.7.2.1p4
16420 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16422 D.setInvalidType();
16429 if (T->isReferenceType()) {
16430 Diag(Loc, diag::err_ivar_reference_type);
16431 D.setInvalidType();
16433 // C99 6.7.2.1p8: A member of a structure or union may have any type other
16434 // than a variably modified type.
16435 else if (T->isVariablyModifiedType()) {
16436 Diag(Loc, diag::err_typecheck_ivar_variable_size);
16437 D.setInvalidType();
16440 // Get the visibility (access control) for this ivar.
16441 ObjCIvarDecl::AccessControl ac =
16442 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16443 : ObjCIvarDecl::None;
16444 // Must set ivar's DeclContext to its enclosing interface.
16445 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16446 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16448 ObjCContainerDecl *EnclosingContext;
16449 if (ObjCImplementationDecl *IMPDecl =
16450 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16451 if (LangOpts.ObjCRuntime.isFragile()) {
16452 // Case of ivar declared in an implementation. Context is that of its class.
16453 EnclosingContext = IMPDecl->getClassInterface();
16454 assert(EnclosingContext && "Implementation has no class interface!");
16457 EnclosingContext = EnclosingDecl;
16459 if (ObjCCategoryDecl *CDecl =
16460 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16461 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16462 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16466 EnclosingContext = EnclosingDecl;
16469 // Construct the decl.
16470 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16471 DeclStart, Loc, II, T,
16472 TInfo, ac, (Expr *)BitfieldWidth);
16475 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16476 ForVisibleRedeclaration);
16477 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16478 && !isa<TagDecl>(PrevDecl)) {
16479 Diag(Loc, diag::err_duplicate_member) << II;
16480 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16481 NewID->setInvalidDecl();
16485 // Process attributes attached to the ivar.
16486 ProcessDeclAttributes(S, NewID, D);
16488 if (D.isInvalidType())
16489 NewID->setInvalidDecl();
16491 // In ARC, infer 'retaining' for ivars of retainable type.
16492 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16493 NewID->setInvalidDecl();
16495 if (D.getDeclSpec().isModulePrivateSpecified())
16496 NewID->setModulePrivate();
16499 // FIXME: When interfaces are DeclContexts, we'll need to add
16500 // these to the interface.
16502 IdResolver.AddDecl(NewID);
16505 if (LangOpts.ObjCRuntime.isNonFragile() &&
16506 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16507 Diag(Loc, diag::warn_ivars_in_interface);
16512 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16513 /// class and class extensions. For every class \@interface and class
16514 /// extension \@interface, if the last ivar is a bitfield of any type,
16515 /// then add an implicit `char :0` ivar to the end of that interface.
16516 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16517 SmallVectorImpl<Decl *> &AllIvarDecls) {
16518 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16521 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16522 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16524 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16526 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16528 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16529 if (!CD->IsClassExtension())
16532 // No need to add this to end of @implementation.
16536 // All conditions are met. Add a new bitfield to the tail end of ivars.
16537 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16538 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16540 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16541 DeclLoc, DeclLoc, nullptr,
16543 Context.getTrivialTypeSourceInfo(Context.CharTy,
16545 ObjCIvarDecl::Private, BW,
16547 AllIvarDecls.push_back(Ivar);
16550 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16551 ArrayRef<Decl *> Fields, SourceLocation LBrac,
16552 SourceLocation RBrac,
16553 const ParsedAttributesView &Attrs) {
16554 assert(EnclosingDecl && "missing record or interface decl");
16556 // If this is an Objective-C @implementation or category and we have
16557 // new fields here we should reset the layout of the interface since
16558 // it will now change.
16559 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16560 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16561 switch (DC->getKind()) {
16563 case Decl::ObjCCategory:
16564 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16566 case Decl::ObjCImplementation:
16568 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16573 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16574 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16576 // Start counting up the number of named members; make sure to include
16577 // members of anonymous structs and unions in the total.
16578 unsigned NumNamedMembers = 0;
16580 for (const auto *I : Record->decls()) {
16581 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16582 if (IFD->getDeclName())
16587 // Verify that all the fields are okay.
16588 SmallVector<FieldDecl*, 32> RecFields;
16590 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16592 FieldDecl *FD = cast<FieldDecl>(*i);
16594 // Get the type for the field.
16595 const Type *FDTy = FD->getType().getTypePtr();
16597 if (!FD->isAnonymousStructOrUnion()) {
16598 // Remember all fields written by the user.
16599 RecFields.push_back(FD);
16602 // If the field is already invalid for some reason, don't emit more
16603 // diagnostics about it.
16604 if (FD->isInvalidDecl()) {
16605 EnclosingDecl->setInvalidDecl();
16610 // A structure or union shall not contain a member with
16611 // incomplete or function type (hence, a structure shall not
16612 // contain an instance of itself, but may contain a pointer to
16613 // an instance of itself), except that the last member of a
16614 // structure with more than one named member may have incomplete
16615 // array type; such a structure (and any union containing,
16616 // possibly recursively, a member that is such a structure)
16617 // shall not be a member of a structure or an element of an
16619 bool IsLastField = (i + 1 == Fields.end());
16620 if (FDTy->isFunctionType()) {
16621 // Field declared as a function.
16622 Diag(FD->getLocation(), diag::err_field_declared_as_function)
16623 << FD->getDeclName();
16624 FD->setInvalidDecl();
16625 EnclosingDecl->setInvalidDecl();
16627 } else if (FDTy->isIncompleteArrayType() &&
16628 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16630 // Flexible array member.
16631 // Microsoft and g++ is more permissive regarding flexible array.
16632 // It will accept flexible array in union and also
16633 // as the sole element of a struct/class.
16634 unsigned DiagID = 0;
16635 if (!Record->isUnion() && !IsLastField) {
16636 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16637 << FD->getDeclName() << FD->getType() << Record->getTagKind();
16638 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16639 FD->setInvalidDecl();
16640 EnclosingDecl->setInvalidDecl();
16642 } else if (Record->isUnion())
16643 DiagID = getLangOpts().MicrosoftExt
16644 ? diag::ext_flexible_array_union_ms
16645 : getLangOpts().CPlusPlus
16646 ? diag::ext_flexible_array_union_gnu
16647 : diag::err_flexible_array_union;
16648 else if (NumNamedMembers < 1)
16649 DiagID = getLangOpts().MicrosoftExt
16650 ? diag::ext_flexible_array_empty_aggregate_ms
16651 : getLangOpts().CPlusPlus
16652 ? diag::ext_flexible_array_empty_aggregate_gnu
16653 : diag::err_flexible_array_empty_aggregate;
16656 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16657 << Record->getTagKind();
16658 // While the layout of types that contain virtual bases is not specified
16659 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16660 // virtual bases after the derived members. This would make a flexible
16661 // array member declared at the end of an object not adjacent to the end
16663 if (CXXRecord && CXXRecord->getNumVBases() != 0)
16664 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16665 << FD->getDeclName() << Record->getTagKind();
16666 if (!getLangOpts().C99)
16667 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16668 << FD->getDeclName() << Record->getTagKind();
16670 // If the element type has a non-trivial destructor, we would not
16671 // implicitly destroy the elements, so disallow it for now.
16673 // FIXME: GCC allows this. We should probably either implicitly delete
16674 // the destructor of the containing class, or just allow this.
16675 QualType BaseElem = Context.getBaseElementType(FD->getType());
16676 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16677 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16678 << FD->getDeclName() << FD->getType();
16679 FD->setInvalidDecl();
16680 EnclosingDecl->setInvalidDecl();
16683 // Okay, we have a legal flexible array member at the end of the struct.
16684 Record->setHasFlexibleArrayMember(true);
16686 // In ObjCContainerDecl ivars with incomplete array type are accepted,
16687 // unless they are followed by another ivar. That check is done
16688 // elsewhere, after synthesized ivars are known.
16690 } else if (!FDTy->isDependentType() &&
16691 RequireCompleteType(FD->getLocation(), FD->getType(),
16692 diag::err_field_incomplete)) {
16694 FD->setInvalidDecl();
16695 EnclosingDecl->setInvalidDecl();
16697 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16698 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16699 // A type which contains a flexible array member is considered to be a
16700 // flexible array member.
16701 Record->setHasFlexibleArrayMember(true);
16702 if (!Record->isUnion()) {
16703 // If this is a struct/class and this is not the last element, reject
16704 // it. Note that GCC supports variable sized arrays in the middle of
16707 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16708 << FD->getDeclName() << FD->getType();
16710 // We support flexible arrays at the end of structs in
16711 // other structs as an extension.
16712 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16713 << FD->getDeclName();
16717 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16718 RequireNonAbstractType(FD->getLocation(), FD->getType(),
16719 diag::err_abstract_type_in_decl,
16720 AbstractIvarType)) {
16721 // Ivars can not have abstract class types
16722 FD->setInvalidDecl();
16724 if (Record && FDTTy->getDecl()->hasObjectMember())
16725 Record->setHasObjectMember(true);
16726 if (Record && FDTTy->getDecl()->hasVolatileMember())
16727 Record->setHasVolatileMember(true);
16728 } else if (FDTy->isObjCObjectType()) {
16729 /// A field cannot be an Objective-c object
16730 Diag(FD->getLocation(), diag::err_statically_allocated_object)
16731 << FixItHint::CreateInsertion(FD->getLocation(), "*");
16732 QualType T = Context.getObjCObjectPointerType(FD->getType());
16734 } else if (Record && Record->isUnion() &&
16735 FD->getType().hasNonTrivialObjCLifetime() &&
16736 getSourceManager().isInSystemHeader(FD->getLocation()) &&
16737 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
16738 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
16739 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
16740 // For backward compatibility, fields of C unions declared in system
16741 // headers that have non-trivial ObjC ownership qualifications are marked
16742 // as unavailable unless the qualifier is explicit and __strong. This can
16743 // break ABI compatibility between programs compiled with ARC and MRR, but
16744 // is a better option than rejecting programs using those unions under
16746 FD->addAttr(UnavailableAttr::CreateImplicit(
16747 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
16748 FD->getLocation()));
16749 } else if (getLangOpts().ObjC &&
16750 getLangOpts().getGC() != LangOptions::NonGC &&
16751 Record && !Record->hasObjectMember()) {
16752 if (FD->getType()->isObjCObjectPointerType() ||
16753 FD->getType().isObjCGCStrong())
16754 Record->setHasObjectMember(true);
16755 else if (Context.getAsArrayType(FD->getType())) {
16756 QualType BaseType = Context.getBaseElementType(FD->getType());
16757 if (BaseType->isRecordType() &&
16758 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
16759 Record->setHasObjectMember(true);
16760 else if (BaseType->isObjCObjectPointerType() ||
16761 BaseType.isObjCGCStrong())
16762 Record->setHasObjectMember(true);
16766 if (Record && !getLangOpts().CPlusPlus &&
16767 !shouldIgnoreForRecordTriviality(FD)) {
16768 QualType FT = FD->getType();
16769 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
16770 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16771 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
16773 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
16775 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16776 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
16777 Record->setNonTrivialToPrimitiveCopy(true);
16778 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
16779 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
16781 if (FT.isDestructedType()) {
16782 Record->setNonTrivialToPrimitiveDestroy(true);
16783 Record->setParamDestroyedInCallee(true);
16784 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
16785 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
16788 if (const auto *RT = FT->getAs<RecordType>()) {
16789 if (RT->getDecl()->getArgPassingRestrictions() ==
16790 RecordDecl::APK_CanNeverPassInRegs)
16791 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16792 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16793 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16796 if (Record && FD->getType().isVolatileQualified())
16797 Record->setHasVolatileMember(true);
16798 // Keep track of the number of named members.
16799 if (FD->getIdentifier())
16803 // Okay, we successfully defined 'Record'.
16805 bool Completed = false;
16807 if (!CXXRecord->isInvalidDecl()) {
16808 // Set access bits correctly on the directly-declared conversions.
16809 for (CXXRecordDecl::conversion_iterator
16810 I = CXXRecord->conversion_begin(),
16811 E = CXXRecord->conversion_end(); I != E; ++I)
16812 I.setAccess((*I)->getAccess());
16815 if (!CXXRecord->isDependentType()) {
16816 // Add any implicitly-declared members to this class.
16817 AddImplicitlyDeclaredMembersToClass(CXXRecord);
16819 if (!CXXRecord->isInvalidDecl()) {
16820 // If we have virtual base classes, we may end up finding multiple
16821 // final overriders for a given virtual function. Check for this
16823 if (CXXRecord->getNumVBases()) {
16824 CXXFinalOverriderMap FinalOverriders;
16825 CXXRecord->getFinalOverriders(FinalOverriders);
16827 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16828 MEnd = FinalOverriders.end();
16830 for (OverridingMethods::iterator SO = M->second.begin(),
16831 SOEnd = M->second.end();
16832 SO != SOEnd; ++SO) {
16833 assert(SO->second.size() > 0 &&
16834 "Virtual function without overriding functions?");
16835 if (SO->second.size() == 1)
16838 // C++ [class.virtual]p2:
16839 // In a derived class, if a virtual member function of a base
16840 // class subobject has more than one final overrider the
16841 // program is ill-formed.
16842 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16843 << (const NamedDecl *)M->first << Record;
16844 Diag(M->first->getLocation(),
16845 diag::note_overridden_virtual_function);
16846 for (OverridingMethods::overriding_iterator
16847 OM = SO->second.begin(),
16848 OMEnd = SO->second.end();
16850 Diag(OM->Method->getLocation(), diag::note_final_overrider)
16851 << (const NamedDecl *)M->first << OM->Method->getParent();
16853 Record->setInvalidDecl();
16856 CXXRecord->completeDefinition(&FinalOverriders);
16864 Record->completeDefinition();
16866 // Handle attributes before checking the layout.
16867 ProcessDeclAttributeList(S, Record, Attrs);
16869 // We may have deferred checking for a deleted destructor. Check now.
16871 auto *Dtor = CXXRecord->getDestructor();
16872 if (Dtor && Dtor->isImplicit() &&
16873 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16874 CXXRecord->setImplicitDestructorIsDeleted();
16875 SetDeclDeleted(Dtor, CXXRecord->getLocation());
16879 if (Record->hasAttrs()) {
16880 CheckAlignasUnderalignment(Record);
16882 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16883 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16884 IA->getRange(), IA->getBestCase(),
16885 IA->getInheritanceModel());
16888 // Check if the structure/union declaration is a type that can have zero
16889 // size in C. For C this is a language extension, for C++ it may cause
16890 // compatibility problems.
16891 bool CheckForZeroSize;
16892 if (!getLangOpts().CPlusPlus) {
16893 CheckForZeroSize = true;
16895 // For C++ filter out types that cannot be referenced in C code.
16896 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16898 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16899 !CXXRecord->isDependentType() &&
16900 CXXRecord->isCLike();
16902 if (CheckForZeroSize) {
16903 bool ZeroSize = true;
16904 bool IsEmpty = true;
16905 unsigned NonBitFields = 0;
16906 for (RecordDecl::field_iterator I = Record->field_begin(),
16907 E = Record->field_end();
16908 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16910 if (I->isUnnamedBitfield()) {
16911 if (!I->isZeroLengthBitField(Context))
16915 QualType FieldType = I->getType();
16916 if (FieldType->isIncompleteType() ||
16917 !Context.getTypeSizeInChars(FieldType).isZero())
16922 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16923 // allowed in C++, but warn if its declaration is inside
16924 // extern "C" block.
16926 Diag(RecLoc, getLangOpts().CPlusPlus ?
16927 diag::warn_zero_size_struct_union_in_extern_c :
16928 diag::warn_zero_size_struct_union_compat)
16929 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16932 // Structs without named members are extension in C (C99 6.7.2.1p7),
16933 // but are accepted by GCC.
16934 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16935 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16936 diag::ext_no_named_members_in_struct_union)
16937 << Record->isUnion();
16941 ObjCIvarDecl **ClsFields =
16942 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16943 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16944 ID->setEndOfDefinitionLoc(RBrac);
16945 // Add ivar's to class's DeclContext.
16946 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16947 ClsFields[i]->setLexicalDeclContext(ID);
16948 ID->addDecl(ClsFields[i]);
16950 // Must enforce the rule that ivars in the base classes may not be
16952 if (ID->getSuperClass())
16953 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16954 } else if (ObjCImplementationDecl *IMPDecl =
16955 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16956 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16957 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16958 // Ivar declared in @implementation never belongs to the implementation.
16959 // Only it is in implementation's lexical context.
16960 ClsFields[I]->setLexicalDeclContext(IMPDecl);
16961 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16962 IMPDecl->setIvarLBraceLoc(LBrac);
16963 IMPDecl->setIvarRBraceLoc(RBrac);
16964 } else if (ObjCCategoryDecl *CDecl =
16965 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16966 // case of ivars in class extension; all other cases have been
16967 // reported as errors elsewhere.
16968 // FIXME. Class extension does not have a LocEnd field.
16969 // CDecl->setLocEnd(RBrac);
16970 // Add ivar's to class extension's DeclContext.
16971 // Diagnose redeclaration of private ivars.
16972 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16973 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16975 if (const ObjCIvarDecl *ClsIvar =
16976 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16977 Diag(ClsFields[i]->getLocation(),
16978 diag::err_duplicate_ivar_declaration);
16979 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16982 for (const auto *Ext : IDecl->known_extensions()) {
16983 if (const ObjCIvarDecl *ClsExtIvar
16984 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16985 Diag(ClsFields[i]->getLocation(),
16986 diag::err_duplicate_ivar_declaration);
16987 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16992 ClsFields[i]->setLexicalDeclContext(CDecl);
16993 CDecl->addDecl(ClsFields[i]);
16995 CDecl->setIvarLBraceLoc(LBrac);
16996 CDecl->setIvarRBraceLoc(RBrac);
17001 /// Determine whether the given integral value is representable within
17002 /// the given type T.
17003 static bool isRepresentableIntegerValue(ASTContext &Context,
17004 llvm::APSInt &Value,
17006 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17007 "Integral type required!");
17008 unsigned BitWidth = Context.getIntWidth(T);
17010 if (Value.isUnsigned() || Value.isNonNegative()) {
17011 if (T->isSignedIntegerOrEnumerationType())
17013 return Value.getActiveBits() <= BitWidth;
17015 return Value.getMinSignedBits() <= BitWidth;
17018 // Given an integral type, return the next larger integral type
17019 // (or a NULL type of no such type exists).
17020 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17021 // FIXME: Int128/UInt128 support, which also needs to be introduced into
17022 // enum checking below.
17023 assert((T->isIntegralType(Context) ||
17024 T->isEnumeralType()) && "Integral type required!");
17025 const unsigned NumTypes = 4;
17026 QualType SignedIntegralTypes[NumTypes] = {
17027 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17029 QualType UnsignedIntegralTypes[NumTypes] = {
17030 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17031 Context.UnsignedLongLongTy
17034 unsigned BitWidth = Context.getTypeSize(T);
17035 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17036 : UnsignedIntegralTypes;
17037 for (unsigned I = 0; I != NumTypes; ++I)
17038 if (Context.getTypeSize(Types[I]) > BitWidth)
17044 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17045 EnumConstantDecl *LastEnumConst,
17046 SourceLocation IdLoc,
17047 IdentifierInfo *Id,
17049 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17050 llvm::APSInt EnumVal(IntWidth);
17053 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17057 Val = DefaultLvalueConversion(Val).get();
17060 if (Enum->isDependentType() || Val->isTypeDependent())
17061 EltTy = Context.DependentTy;
17063 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17064 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17065 // constant-expression in the enumerator-definition shall be a converted
17066 // constant expression of the underlying type.
17067 EltTy = Enum->getIntegerType();
17068 ExprResult Converted =
17069 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17071 if (Converted.isInvalid())
17074 Val = Converted.get();
17075 } else if (!Val->isValueDependent() &&
17076 !(Val = VerifyIntegerConstantExpression(Val,
17077 &EnumVal).get())) {
17078 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17080 if (Enum->isComplete()) {
17081 EltTy = Enum->getIntegerType();
17083 // In Obj-C and Microsoft mode, require the enumeration value to be
17084 // representable in the underlying type of the enumeration. In C++11,
17085 // we perform a non-narrowing conversion as part of converted constant
17086 // expression checking.
17087 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17088 if (Context.getTargetInfo()
17090 .isWindowsMSVCEnvironment()) {
17091 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17093 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17097 // Cast to the underlying type.
17098 Val = ImpCastExprToType(Val, EltTy,
17099 EltTy->isBooleanType() ? CK_IntegralToBoolean
17102 } else if (getLangOpts().CPlusPlus) {
17103 // C++11 [dcl.enum]p5:
17104 // If the underlying type is not fixed, the type of each enumerator
17105 // is the type of its initializing value:
17106 // - If an initializer is specified for an enumerator, the
17107 // initializing value has the same type as the expression.
17108 EltTy = Val->getType();
17111 // The expression that defines the value of an enumeration constant
17112 // shall be an integer constant expression that has a value
17113 // representable as an int.
17115 // Complain if the value is not representable in an int.
17116 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17117 Diag(IdLoc, diag::ext_enum_value_not_int)
17118 << EnumVal.toString(10) << Val->getSourceRange()
17119 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17120 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17121 // Force the type of the expression to 'int'.
17122 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17124 EltTy = Val->getType();
17131 if (Enum->isDependentType())
17132 EltTy = Context.DependentTy;
17133 else if (!LastEnumConst) {
17134 // C++0x [dcl.enum]p5:
17135 // If the underlying type is not fixed, the type of each enumerator
17136 // is the type of its initializing value:
17137 // - If no initializer is specified for the first enumerator, the
17138 // initializing value has an unspecified integral type.
17140 // GCC uses 'int' for its unspecified integral type, as does
17142 if (Enum->isFixed()) {
17143 EltTy = Enum->getIntegerType();
17146 EltTy = Context.IntTy;
17149 // Assign the last value + 1.
17150 EnumVal = LastEnumConst->getInitVal();
17152 EltTy = LastEnumConst->getType();
17154 // Check for overflow on increment.
17155 if (EnumVal < LastEnumConst->getInitVal()) {
17156 // C++0x [dcl.enum]p5:
17157 // If the underlying type is not fixed, the type of each enumerator
17158 // is the type of its initializing value:
17160 // - Otherwise the type of the initializing value is the same as
17161 // the type of the initializing value of the preceding enumerator
17162 // unless the incremented value is not representable in that type,
17163 // in which case the type is an unspecified integral type
17164 // sufficient to contain the incremented value. If no such type
17165 // exists, the program is ill-formed.
17166 QualType T = getNextLargerIntegralType(Context, EltTy);
17167 if (T.isNull() || Enum->isFixed()) {
17168 // There is no integral type larger enough to represent this
17169 // value. Complain, then allow the value to wrap around.
17170 EnumVal = LastEnumConst->getInitVal();
17171 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17173 if (Enum->isFixed())
17174 // When the underlying type is fixed, this is ill-formed.
17175 Diag(IdLoc, diag::err_enumerator_wrapped)
17176 << EnumVal.toString(10)
17179 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17180 << EnumVal.toString(10);
17185 // Retrieve the last enumerator's value, extent that type to the
17186 // type that is supposed to be large enough to represent the incremented
17187 // value, then increment.
17188 EnumVal = LastEnumConst->getInitVal();
17189 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17190 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17193 // If we're not in C++, diagnose the overflow of enumerator values,
17194 // which in C99 means that the enumerator value is not representable in
17195 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17196 // permits enumerator values that are representable in some larger
17198 if (!getLangOpts().CPlusPlus && !T.isNull())
17199 Diag(IdLoc, diag::warn_enum_value_overflow);
17200 } else if (!getLangOpts().CPlusPlus &&
17201 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17202 // Enforce C99 6.7.2.2p2 even when we compute the next value.
17203 Diag(IdLoc, diag::ext_enum_value_not_int)
17204 << EnumVal.toString(10) << 1;
17209 if (!EltTy->isDependentType()) {
17210 // Make the enumerator value match the signedness and size of the
17211 // enumerator's type.
17212 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17213 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17216 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17220 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17221 SourceLocation IILoc) {
17222 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17223 !getLangOpts().CPlusPlus)
17224 return SkipBodyInfo();
17226 // We have an anonymous enum definition. Look up the first enumerator to
17227 // determine if we should merge the definition with an existing one and
17229 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17230 forRedeclarationInCurContext());
17231 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17233 return SkipBodyInfo();
17235 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17237 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17239 Skip.Previous = Hidden;
17243 return SkipBodyInfo();
17246 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17247 SourceLocation IdLoc, IdentifierInfo *Id,
17248 const ParsedAttributesView &Attrs,
17249 SourceLocation EqualLoc, Expr *Val) {
17250 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17251 EnumConstantDecl *LastEnumConst =
17252 cast_or_null<EnumConstantDecl>(lastEnumConst);
17254 // The scope passed in may not be a decl scope. Zip up the scope tree until
17255 // we find one that is.
17256 S = getNonFieldDeclScope(S);
17258 // Verify that there isn't already something declared with this name in this
17260 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17262 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17264 if (PrevDecl && PrevDecl->isTemplateParameter()) {
17265 // Maybe we will complain about the shadowed template parameter.
17266 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17267 // Just pretend that we didn't see the previous declaration.
17268 PrevDecl = nullptr;
17271 // C++ [class.mem]p15:
17272 // If T is the name of a class, then each of the following shall have a name
17273 // different from T:
17274 // - every enumerator of every member of class T that is an unscoped
17276 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17277 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17278 DeclarationNameInfo(Id, IdLoc));
17280 EnumConstantDecl *New =
17281 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17286 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17287 // Check for other kinds of shadowing not already handled.
17288 CheckShadow(New, PrevDecl, R);
17291 // When in C++, we may get a TagDecl with the same name; in this case the
17292 // enum constant will 'hide' the tag.
17293 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17294 "Received TagDecl when not in C++!");
17295 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17296 if (isa<EnumConstantDecl>(PrevDecl))
17297 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17299 Diag(IdLoc, diag::err_redefinition) << Id;
17300 notePreviousDefinition(PrevDecl, IdLoc);
17305 // Process attributes.
17306 ProcessDeclAttributeList(S, New, Attrs);
17307 AddPragmaAttributes(S, New);
17309 // Register this decl in the current scope stack.
17310 New->setAccess(TheEnumDecl->getAccess());
17311 PushOnScopeChains(New, S);
17313 ActOnDocumentableDecl(New);
17318 // Returns true when the enum initial expression does not trigger the
17319 // duplicate enum warning. A few common cases are exempted as follows:
17320 // Element2 = Element1
17321 // Element2 = Element1 + 1
17322 // Element2 = Element1 - 1
17323 // Where Element2 and Element1 are from the same enum.
17324 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17325 Expr *InitExpr = ECD->getInitExpr();
17328 InitExpr = InitExpr->IgnoreImpCasts();
17330 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17331 if (!BO->isAdditiveOp())
17333 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17336 if (IL->getValue() != 1)
17339 InitExpr = BO->getLHS();
17342 // This checks if the elements are from the same enum.
17343 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17347 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17351 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17358 // Emits a warning when an element is implicitly set a value that
17359 // a previous element has already been set to.
17360 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17361 EnumDecl *Enum, QualType EnumType) {
17362 // Avoid anonymous enums
17363 if (!Enum->getIdentifier())
17366 // Only check for small enums.
17367 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17370 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17373 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17374 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17376 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17377 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17379 // Use int64_t as a key to avoid needing special handling for DenseMap keys.
17380 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17381 llvm::APSInt Val = D->getInitVal();
17382 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17385 DuplicatesVector DupVector;
17386 ValueToVectorMap EnumMap;
17388 // Populate the EnumMap with all values represented by enum constants without
17390 for (auto *Element : Elements) {
17391 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17393 // Null EnumConstantDecl means a previous diagnostic has been emitted for
17394 // this constant. Skip this enum since it may be ill-formed.
17399 // Constants with initalizers are handled in the next loop.
17400 if (ECD->getInitExpr())
17403 // Duplicate values are handled in the next loop.
17404 EnumMap.insert({EnumConstantToKey(ECD), ECD});
17407 if (EnumMap.size() == 0)
17410 // Create vectors for any values that has duplicates.
17411 for (auto *Element : Elements) {
17412 // The last loop returned if any constant was null.
17413 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17414 if (!ValidDuplicateEnum(ECD, Enum))
17417 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17418 if (Iter == EnumMap.end())
17421 DeclOrVector& Entry = Iter->second;
17422 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17423 // Ensure constants are different.
17427 // Create new vector and push values onto it.
17428 auto Vec = std::make_unique<ECDVector>();
17430 Vec->push_back(ECD);
17432 // Update entry to point to the duplicates vector.
17435 // Store the vector somewhere we can consult later for quick emission of
17437 DupVector.emplace_back(std::move(Vec));
17441 ECDVector *Vec = Entry.get<ECDVector*>();
17442 // Make sure constants are not added more than once.
17443 if (*Vec->begin() == ECD)
17446 Vec->push_back(ECD);
17449 // Emit diagnostics.
17450 for (const auto &Vec : DupVector) {
17451 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17453 // Emit warning for one enum constant.
17454 auto *FirstECD = Vec->front();
17455 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17456 << FirstECD << FirstECD->getInitVal().toString(10)
17457 << FirstECD->getSourceRange();
17459 // Emit one note for each of the remaining enum constants with
17461 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17462 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17463 << ECD << ECD->getInitVal().toString(10)
17464 << ECD->getSourceRange();
17468 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17469 bool AllowMask) const {
17470 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17471 assert(ED->isCompleteDefinition() && "expected enum definition");
17473 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17474 llvm::APInt &FlagBits = R.first->second;
17477 for (auto *E : ED->enumerators()) {
17478 const auto &EVal = E->getInitVal();
17479 // Only single-bit enumerators introduce new flag values.
17480 if (EVal.isPowerOf2())
17481 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17485 // A value is in a flag enum if either its bits are a subset of the enum's
17486 // flag bits (the first condition) or we are allowing masks and the same is
17487 // true of its complement (the second condition). When masks are allowed, we
17488 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17490 // While it's true that any value could be used as a mask, the assumption is
17491 // that a mask will have all of the insignificant bits set. Anything else is
17492 // likely a logic error.
17493 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17494 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17497 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17498 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17499 const ParsedAttributesView &Attrs) {
17500 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17501 QualType EnumType = Context.getTypeDeclType(Enum);
17503 ProcessDeclAttributeList(S, Enum, Attrs);
17505 if (Enum->isDependentType()) {
17506 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17507 EnumConstantDecl *ECD =
17508 cast_or_null<EnumConstantDecl>(Elements[i]);
17509 if (!ECD) continue;
17511 ECD->setType(EnumType);
17514 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17518 // TODO: If the result value doesn't fit in an int, it must be a long or long
17519 // long value. ISO C does not support this, but GCC does as an extension,
17521 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17522 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17523 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17525 // Verify that all the values are okay, compute the size of the values, and
17526 // reverse the list.
17527 unsigned NumNegativeBits = 0;
17528 unsigned NumPositiveBits = 0;
17530 // Keep track of whether all elements have type int.
17531 bool AllElementsInt = true;
17533 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17534 EnumConstantDecl *ECD =
17535 cast_or_null<EnumConstantDecl>(Elements[i]);
17536 if (!ECD) continue; // Already issued a diagnostic.
17538 const llvm::APSInt &InitVal = ECD->getInitVal();
17540 // Keep track of the size of positive and negative values.
17541 if (InitVal.isUnsigned() || InitVal.isNonNegative())
17542 NumPositiveBits = std::max(NumPositiveBits,
17543 (unsigned)InitVal.getActiveBits());
17545 NumNegativeBits = std::max(NumNegativeBits,
17546 (unsigned)InitVal.getMinSignedBits());
17548 // Keep track of whether every enum element has type int (very common).
17549 if (AllElementsInt)
17550 AllElementsInt = ECD->getType() == Context.IntTy;
17553 // Figure out the type that should be used for this enum.
17555 unsigned BestWidth;
17557 // C++0x N3000 [conv.prom]p3:
17558 // An rvalue of an unscoped enumeration type whose underlying
17559 // type is not fixed can be converted to an rvalue of the first
17560 // of the following types that can represent all the values of
17561 // the enumeration: int, unsigned int, long int, unsigned long
17562 // int, long long int, or unsigned long long int.
17564 // An identifier declared as an enumeration constant has type int.
17565 // The C99 rule is modified by a gcc extension
17566 QualType BestPromotionType;
17568 bool Packed = Enum->hasAttr<PackedAttr>();
17569 // -fshort-enums is the equivalent to specifying the packed attribute on all
17570 // enum definitions.
17571 if (LangOpts.ShortEnums)
17574 // If the enum already has a type because it is fixed or dictated by the
17575 // target, promote that type instead of analyzing the enumerators.
17576 if (Enum->isComplete()) {
17577 BestType = Enum->getIntegerType();
17578 if (BestType->isPromotableIntegerType())
17579 BestPromotionType = Context.getPromotedIntegerType(BestType);
17581 BestPromotionType = BestType;
17583 BestWidth = Context.getIntWidth(BestType);
17585 else if (NumNegativeBits) {
17586 // If there is a negative value, figure out the smallest integer type (of
17587 // int/long/longlong) that fits.
17588 // If it's packed, check also if it fits a char or a short.
17589 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17590 BestType = Context.SignedCharTy;
17591 BestWidth = CharWidth;
17592 } else if (Packed && NumNegativeBits <= ShortWidth &&
17593 NumPositiveBits < ShortWidth) {
17594 BestType = Context.ShortTy;
17595 BestWidth = ShortWidth;
17596 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17597 BestType = Context.IntTy;
17598 BestWidth = IntWidth;
17600 BestWidth = Context.getTargetInfo().getLongWidth();
17602 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17603 BestType = Context.LongTy;
17605 BestWidth = Context.getTargetInfo().getLongLongWidth();
17607 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17608 Diag(Enum->getLocation(), diag::ext_enum_too_large);
17609 BestType = Context.LongLongTy;
17612 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17614 // If there is no negative value, figure out the smallest type that fits
17615 // all of the enumerator values.
17616 // If it's packed, check also if it fits a char or a short.
17617 if (Packed && NumPositiveBits <= CharWidth) {
17618 BestType = Context.UnsignedCharTy;
17619 BestPromotionType = Context.IntTy;
17620 BestWidth = CharWidth;
17621 } else if (Packed && NumPositiveBits <= ShortWidth) {
17622 BestType = Context.UnsignedShortTy;
17623 BestPromotionType = Context.IntTy;
17624 BestWidth = ShortWidth;
17625 } else if (NumPositiveBits <= IntWidth) {
17626 BestType = Context.UnsignedIntTy;
17627 BestWidth = IntWidth;
17629 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17630 ? Context.UnsignedIntTy : Context.IntTy;
17631 } else if (NumPositiveBits <=
17632 (BestWidth = Context.getTargetInfo().getLongWidth())) {
17633 BestType = Context.UnsignedLongTy;
17635 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17636 ? Context.UnsignedLongTy : Context.LongTy;
17638 BestWidth = Context.getTargetInfo().getLongLongWidth();
17639 assert(NumPositiveBits <= BestWidth &&
17640 "How could an initializer get larger than ULL?");
17641 BestType = Context.UnsignedLongLongTy;
17643 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17644 ? Context.UnsignedLongLongTy : Context.LongLongTy;
17648 // Loop over all of the enumerator constants, changing their types to match
17649 // the type of the enum if needed.
17650 for (auto *D : Elements) {
17651 auto *ECD = cast_or_null<EnumConstantDecl>(D);
17652 if (!ECD) continue; // Already issued a diagnostic.
17654 // Standard C says the enumerators have int type, but we allow, as an
17655 // extension, the enumerators to be larger than int size. If each
17656 // enumerator value fits in an int, type it as an int, otherwise type it the
17657 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
17658 // that X has type 'int', not 'unsigned'.
17660 // Determine whether the value fits into an int.
17661 llvm::APSInt InitVal = ECD->getInitVal();
17663 // If it fits into an integer type, force it. Otherwise force it to match
17664 // the enum decl type.
17668 if (!getLangOpts().CPlusPlus &&
17669 !Enum->isFixed() &&
17670 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17671 NewTy = Context.IntTy;
17672 NewWidth = IntWidth;
17674 } else if (ECD->getType() == BestType) {
17675 // Already the right type!
17676 if (getLangOpts().CPlusPlus)
17677 // C++ [dcl.enum]p4: Following the closing brace of an
17678 // enum-specifier, each enumerator has the type of its
17680 ECD->setType(EnumType);
17684 NewWidth = BestWidth;
17685 NewSign = BestType->isSignedIntegerOrEnumerationType();
17688 // Adjust the APSInt value.
17689 InitVal = InitVal.extOrTrunc(NewWidth);
17690 InitVal.setIsSigned(NewSign);
17691 ECD->setInitVal(InitVal);
17693 // Adjust the Expr initializer and type.
17694 if (ECD->getInitExpr() &&
17695 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17696 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17698 ECD->getInitExpr(),
17699 /*base paths*/ nullptr,
17701 if (getLangOpts().CPlusPlus)
17702 // C++ [dcl.enum]p4: Following the closing brace of an
17703 // enum-specifier, each enumerator has the type of its
17705 ECD->setType(EnumType);
17707 ECD->setType(NewTy);
17710 Enum->completeDefinition(BestType, BestPromotionType,
17711 NumPositiveBits, NumNegativeBits);
17713 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17715 if (Enum->isClosedFlag()) {
17716 for (Decl *D : Elements) {
17717 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17718 if (!ECD) continue; // Already issued a diagnostic.
17720 llvm::APSInt InitVal = ECD->getInitVal();
17721 if (InitVal != 0 && !InitVal.isPowerOf2() &&
17722 !IsValueInFlagEnum(Enum, InitVal, true))
17723 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17728 // Now that the enum type is defined, ensure it's not been underaligned.
17729 if (Enum->hasAttrs())
17730 CheckAlignasUnderalignment(Enum);
17733 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17734 SourceLocation StartLoc,
17735 SourceLocation EndLoc) {
17736 StringLiteral *AsmString = cast<StringLiteral>(expr);
17738 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17739 AsmString, StartLoc,
17741 CurContext->addDecl(New);
17745 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17746 IdentifierInfo* AliasName,
17747 SourceLocation PragmaLoc,
17748 SourceLocation NameLoc,
17749 SourceLocation AliasNameLoc) {
17750 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17751 LookupOrdinaryName);
17752 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
17753 AttributeCommonInfo::AS_Pragma);
17754 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
17755 Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
17757 // If a declaration that:
17758 // 1) declares a function or a variable
17759 // 2) has external linkage
17760 // already exists, add a label attribute to it.
17761 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17762 if (isDeclExternC(PrevDecl))
17763 PrevDecl->addAttr(Attr);
17765 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17766 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17767 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17769 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17772 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17773 SourceLocation PragmaLoc,
17774 SourceLocation NameLoc) {
17775 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17778 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
17780 (void)WeakUndeclaredIdentifiers.insert(
17781 std::pair<IdentifierInfo*,WeakInfo>
17782 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17786 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17787 IdentifierInfo* AliasName,
17788 SourceLocation PragmaLoc,
17789 SourceLocation NameLoc,
17790 SourceLocation AliasNameLoc) {
17791 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17792 LookupOrdinaryName);
17793 WeakInfo W = WeakInfo(Name, NameLoc);
17795 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17796 if (!PrevDecl->hasAttr<AliasAttr>())
17797 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17798 DeclApplyPragmaWeak(TUScope, ND, W);
17800 (void)WeakUndeclaredIdentifiers.insert(
17801 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17805 Decl *Sema::getObjCDeclContext() const {
17806 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17809 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) {
17810 // Templates are emitted when they're instantiated.
17811 if (FD->isDependentContext())
17812 return FunctionEmissionStatus::TemplateDiscarded;
17814 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
17815 if (LangOpts.OpenMPIsDevice) {
17816 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17817 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17818 if (DevTy.hasValue()) {
17819 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
17820 OMPES = FunctionEmissionStatus::OMPDiscarded;
17821 else if (DeviceKnownEmittedFns.count(FD) > 0)
17822 OMPES = FunctionEmissionStatus::Emitted;
17824 } else if (LangOpts.OpenMP) {
17825 // In OpenMP 4.5 all the functions are host functions.
17826 if (LangOpts.OpenMP <= 45) {
17827 OMPES = FunctionEmissionStatus::Emitted;
17829 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17830 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17831 // In OpenMP 5.0 or above, DevTy may be changed later by
17832 // #pragma omp declare target to(*) device_type(*). Therefore DevTy
17833 // having no value does not imply host. The emission status will be
17834 // checked again at the end of compilation unit.
17835 if (DevTy.hasValue()) {
17836 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
17837 OMPES = FunctionEmissionStatus::OMPDiscarded;
17838 } else if (DeviceKnownEmittedFns.count(FD) > 0) {
17839 OMPES = FunctionEmissionStatus::Emitted;
17844 if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
17845 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
17848 if (LangOpts.CUDA) {
17849 // When compiling for device, host functions are never emitted. Similarly,
17850 // when compiling for host, device and global functions are never emitted.
17851 // (Technically, we do emit a host-side stub for global functions, but this
17852 // doesn't count for our purposes here.)
17853 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
17854 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
17855 return FunctionEmissionStatus::CUDADiscarded;
17856 if (!LangOpts.CUDAIsDevice &&
17857 (T == Sema::CFT_Device || T == Sema::CFT_Global))
17858 return FunctionEmissionStatus::CUDADiscarded;
17860 // Check whether this function is externally visible -- if so, it's
17863 // We have to check the GVA linkage of the function's *definition* -- if we
17864 // only have a declaration, we don't know whether or not the function will
17865 // be emitted, because (say) the definition could include "inline".
17866 FunctionDecl *Def = FD->getDefinition();
17869 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
17870 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
17871 return FunctionEmissionStatus::Emitted;
17874 // Otherwise, the function is known-emitted if it's in our set of
17875 // known-emitted functions.
17876 return (DeviceKnownEmittedFns.count(FD) > 0)
17877 ? FunctionEmissionStatus::Emitted
17878 : FunctionEmissionStatus::Unknown;
17881 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
17882 // Host-side references to a __global__ function refer to the stub, so the
17883 // function itself is never emitted and therefore should not be marked.
17884 // If we have host fn calls kernel fn calls host+device, the HD function
17885 // does not get instantiated on the host. We model this by omitting at the
17886 // call to the kernel from the callgraph. This ensures that, when compiling
17887 // for host, only HD functions actually called from the host get marked as
17889 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
17890 IdentifyCUDATarget(Callee) == CFT_Global;