[lld][WebAssembly] Add `--table-base` setting
[llvm-project.git] / clang / lib / Sema / SemaDecl.cpp
blob4eacc05f85e69eea53a54ecf203c012356140a2d
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for declarations.
11 //===----------------------------------------------------------------------===//
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/Randstruct.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/HLSLRuntime.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
36 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
37 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
38 #include "clang/Sema/CXXFieldCollector.h"
39 #include "clang/Sema/DeclSpec.h"
40 #include "clang/Sema/DelayedDiagnostic.h"
41 #include "clang/Sema/Initialization.h"
42 #include "clang/Sema/Lookup.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaInternal.h"
47 #include "clang/Sema/Template.h"
48 #include "llvm/ADT/SmallString.h"
49 #include "llvm/ADT/StringExtras.h"
50 #include "llvm/TargetParser/Triple.h"
51 #include <algorithm>
52 #include <cstring>
53 #include <functional>
54 #include <optional>
55 #include <unordered_map>
57 using namespace clang;
58 using namespace sema;
60 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
61 if (OwnedType) {
62 Decl *Group[2] = { OwnedType, Ptr };
63 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
66 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
69 namespace {
71 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
72 public:
73 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
74 bool AllowTemplates = false,
75 bool AllowNonTemplates = true)
76 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
77 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
78 WantExpressionKeywords = false;
79 WantCXXNamedCasts = false;
80 WantRemainingKeywords = false;
83 bool ValidateCandidate(const TypoCorrection &candidate) override {
84 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
85 if (!AllowInvalidDecl && ND->isInvalidDecl())
86 return false;
88 if (getAsTypeTemplateDecl(ND))
89 return AllowTemplates;
91 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
92 if (!IsType)
93 return false;
95 if (AllowNonTemplates)
96 return true;
98 // An injected-class-name of a class template (specialization) is valid
99 // as a template or as a non-template.
100 if (AllowTemplates) {
101 auto *RD = dyn_cast<CXXRecordDecl>(ND);
102 if (!RD || !RD->isInjectedClassName())
103 return false;
104 RD = cast<CXXRecordDecl>(RD->getDeclContext());
105 return RD->getDescribedClassTemplate() ||
106 isa<ClassTemplateSpecializationDecl>(RD);
109 return false;
112 return !WantClassName && candidate.isKeyword();
115 std::unique_ptr<CorrectionCandidateCallback> clone() override {
116 return std::make_unique<TypeNameValidatorCCC>(*this);
119 private:
120 bool AllowInvalidDecl;
121 bool WantClassName;
122 bool AllowTemplates;
123 bool AllowNonTemplates;
126 } // end anonymous namespace
128 /// Determine whether the token kind starts a simple-type-specifier.
129 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
130 switch (Kind) {
131 // FIXME: Take into account the current language when deciding whether a
132 // token kind is a valid type specifier
133 case tok::kw_short:
134 case tok::kw_long:
135 case tok::kw___int64:
136 case tok::kw___int128:
137 case tok::kw_signed:
138 case tok::kw_unsigned:
139 case tok::kw_void:
140 case tok::kw_char:
141 case tok::kw_int:
142 case tok::kw_half:
143 case tok::kw_float:
144 case tok::kw_double:
145 case tok::kw___bf16:
146 case tok::kw__Float16:
147 case tok::kw___float128:
148 case tok::kw___ibm128:
149 case tok::kw_wchar_t:
150 case tok::kw_bool:
151 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
152 #include "clang/Basic/TransformTypeTraits.def"
153 case tok::kw___auto_type:
154 return true;
156 case tok::annot_typename:
157 case tok::kw_char16_t:
158 case tok::kw_char32_t:
159 case tok::kw_typeof:
160 case tok::annot_decltype:
161 case tok::kw_decltype:
162 return getLangOpts().CPlusPlus;
164 case tok::kw_char8_t:
165 return getLangOpts().Char8;
167 default:
168 break;
171 return false;
174 namespace {
175 enum class UnqualifiedTypeNameLookupResult {
176 NotFound,
177 FoundNonType,
178 FoundType
180 } // end anonymous namespace
182 /// Tries to perform unqualified lookup of the type decls in bases for
183 /// dependent class.
184 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
185 /// type decl, \a FoundType if only type decls are found.
186 static UnqualifiedTypeNameLookupResult
187 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
188 SourceLocation NameLoc,
189 const CXXRecordDecl *RD) {
190 if (!RD->hasDefinition())
191 return UnqualifiedTypeNameLookupResult::NotFound;
192 // Look for type decls in base classes.
193 UnqualifiedTypeNameLookupResult FoundTypeDecl =
194 UnqualifiedTypeNameLookupResult::NotFound;
195 for (const auto &Base : RD->bases()) {
196 const CXXRecordDecl *BaseRD = nullptr;
197 if (auto *BaseTT = Base.getType()->getAs<TagType>())
198 BaseRD = BaseTT->getAsCXXRecordDecl();
199 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
200 // Look for type decls in dependent base classes that have known primary
201 // templates.
202 if (!TST || !TST->isDependentType())
203 continue;
204 auto *TD = TST->getTemplateName().getAsTemplateDecl();
205 if (!TD)
206 continue;
207 if (auto *BasePrimaryTemplate =
208 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
209 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
210 BaseRD = BasePrimaryTemplate;
211 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
212 if (const ClassTemplatePartialSpecializationDecl *PS =
213 CTD->findPartialSpecialization(Base.getType()))
214 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
215 BaseRD = PS;
219 if (BaseRD) {
220 for (NamedDecl *ND : BaseRD->lookup(&II)) {
221 if (!isa<TypeDecl>(ND))
222 return UnqualifiedTypeNameLookupResult::FoundNonType;
223 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
226 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
227 case UnqualifiedTypeNameLookupResult::FoundNonType:
228 return UnqualifiedTypeNameLookupResult::FoundNonType;
229 case UnqualifiedTypeNameLookupResult::FoundType:
230 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
231 break;
232 case UnqualifiedTypeNameLookupResult::NotFound:
233 break;
239 return FoundTypeDecl;
242 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
243 const IdentifierInfo &II,
244 SourceLocation NameLoc) {
245 // Lookup in the parent class template context, if any.
246 const CXXRecordDecl *RD = nullptr;
247 UnqualifiedTypeNameLookupResult FoundTypeDecl =
248 UnqualifiedTypeNameLookupResult::NotFound;
249 for (DeclContext *DC = S.CurContext;
250 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
251 DC = DC->getParent()) {
252 // Look for type decls in dependent base classes that have known primary
253 // templates.
254 RD = dyn_cast<CXXRecordDecl>(DC);
255 if (RD && RD->getDescribedClassTemplate())
256 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
258 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
259 return nullptr;
261 // We found some types in dependent base classes. Recover as if the user
262 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
263 // lookup during template instantiation.
264 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
266 ASTContext &Context = S.Context;
267 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
268 cast<Type>(Context.getRecordType(RD)));
269 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
271 CXXScopeSpec SS;
272 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
274 TypeLocBuilder Builder;
275 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
276 DepTL.setNameLoc(NameLoc);
277 DepTL.setElaboratedKeywordLoc(SourceLocation());
278 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
279 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
282 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
283 static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T,
284 SourceLocation NameLoc,
285 bool WantNontrivialTypeSourceInfo = true) {
286 switch (T->getTypeClass()) {
287 case Type::DeducedTemplateSpecialization:
288 case Type::Enum:
289 case Type::InjectedClassName:
290 case Type::Record:
291 case Type::Typedef:
292 case Type::UnresolvedUsing:
293 case Type::Using:
294 break;
295 // These can never be qualified so an ElaboratedType node
296 // would carry no additional meaning.
297 case Type::ObjCInterface:
298 case Type::ObjCTypeParam:
299 case Type::TemplateTypeParm:
300 return ParsedType::make(T);
301 default:
302 llvm_unreachable("Unexpected Type Class");
305 if (!SS || SS->isEmpty())
306 return ParsedType::make(
307 S.Context.getElaboratedType(ETK_None, nullptr, T, nullptr));
309 QualType ElTy = S.getElaboratedType(ETK_None, *SS, T);
310 if (!WantNontrivialTypeSourceInfo)
311 return ParsedType::make(ElTy);
313 TypeLocBuilder Builder;
314 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
315 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
316 ElabTL.setElaboratedKeywordLoc(SourceLocation());
317 ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context));
318 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
321 /// If the identifier refers to a type name within this scope,
322 /// return the declaration of that type.
324 /// This routine performs ordinary name lookup of the identifier II
325 /// within the given scope, with optional C++ scope specifier SS, to
326 /// determine whether the name refers to a type. If so, returns an
327 /// opaque pointer (actually a QualType) corresponding to that
328 /// type. Otherwise, returns NULL.
329 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
330 Scope *S, CXXScopeSpec *SS, bool isClassName,
331 bool HasTrailingDot, ParsedType ObjectTypePtr,
332 bool IsCtorOrDtorName,
333 bool WantNontrivialTypeSourceInfo,
334 bool IsClassTemplateDeductionContext,
335 ImplicitTypenameContext AllowImplicitTypename,
336 IdentifierInfo **CorrectedII) {
337 // FIXME: Consider allowing this outside C++1z mode as an extension.
338 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
339 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
340 !isClassName && !HasTrailingDot;
342 // Determine where we will perform name lookup.
343 DeclContext *LookupCtx = nullptr;
344 if (ObjectTypePtr) {
345 QualType ObjectType = ObjectTypePtr.get();
346 if (ObjectType->isRecordType())
347 LookupCtx = computeDeclContext(ObjectType);
348 } else if (SS && SS->isNotEmpty()) {
349 LookupCtx = computeDeclContext(*SS, false);
351 if (!LookupCtx) {
352 if (isDependentScopeSpecifier(*SS)) {
353 // C++ [temp.res]p3:
354 // A qualified-id that refers to a type and in which the
355 // nested-name-specifier depends on a template-parameter (14.6.2)
356 // shall be prefixed by the keyword typename to indicate that the
357 // qualified-id denotes a type, forming an
358 // elaborated-type-specifier (7.1.5.3).
360 // We therefore do not perform any name lookup if the result would
361 // refer to a member of an unknown specialization.
362 // In C++2a, in several contexts a 'typename' is not required. Also
363 // allow this as an extension.
364 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
365 !isClassName && !IsCtorOrDtorName)
366 return nullptr;
367 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
368 if (IsImplicitTypename) {
369 SourceLocation QualifiedLoc = SS->getRange().getBegin();
370 if (getLangOpts().CPlusPlus20)
371 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
372 else
373 Diag(QualifiedLoc, diag::ext_implicit_typename)
374 << SS->getScopeRep() << II.getName()
375 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
378 // We know from the grammar that this name refers to a type,
379 // so build a dependent node to describe the type.
380 if (WantNontrivialTypeSourceInfo)
381 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
382 (ImplicitTypenameContext)IsImplicitTypename)
383 .get();
385 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
386 QualType T =
387 CheckTypenameType(IsImplicitTypename ? ETK_Typename : ETK_None,
388 SourceLocation(), QualifierLoc, II, NameLoc);
389 return ParsedType::make(T);
392 return nullptr;
395 if (!LookupCtx->isDependentContext() &&
396 RequireCompleteDeclContext(*SS, LookupCtx))
397 return nullptr;
400 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
401 // lookup for class-names.
402 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
403 LookupOrdinaryName;
404 LookupResult Result(*this, &II, NameLoc, Kind);
405 if (LookupCtx) {
406 // Perform "qualified" name lookup into the declaration context we
407 // computed, which is either the type of the base of a member access
408 // expression or the declaration context associated with a prior
409 // nested-name-specifier.
410 LookupQualifiedName(Result, LookupCtx);
412 if (ObjectTypePtr && Result.empty()) {
413 // C++ [basic.lookup.classref]p3:
414 // If the unqualified-id is ~type-name, the type-name is looked up
415 // in the context of the entire postfix-expression. If the type T of
416 // the object expression is of a class type C, the type-name is also
417 // looked up in the scope of class C. At least one of the lookups shall
418 // find a name that refers to (possibly cv-qualified) T.
419 LookupName(Result, S);
421 } else {
422 // Perform unqualified name lookup.
423 LookupName(Result, S);
425 // For unqualified lookup in a class template in MSVC mode, look into
426 // dependent base classes where the primary class template is known.
427 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
428 if (ParsedType TypeInBase =
429 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
430 return TypeInBase;
434 NamedDecl *IIDecl = nullptr;
435 UsingShadowDecl *FoundUsingShadow = nullptr;
436 switch (Result.getResultKind()) {
437 case LookupResult::NotFound:
438 case LookupResult::NotFoundInCurrentInstantiation:
439 if (CorrectedII) {
440 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
441 AllowDeducedTemplate);
442 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
443 S, SS, CCC, CTK_ErrorRecovery);
444 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
445 TemplateTy Template;
446 bool MemberOfUnknownSpecialization;
447 UnqualifiedId TemplateName;
448 TemplateName.setIdentifier(NewII, NameLoc);
449 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
450 CXXScopeSpec NewSS, *NewSSPtr = SS;
451 if (SS && NNS) {
452 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
453 NewSSPtr = &NewSS;
455 if (Correction && (NNS || NewII != &II) &&
456 // Ignore a correction to a template type as the to-be-corrected
457 // identifier is not a template (typo correction for template names
458 // is handled elsewhere).
459 !(getLangOpts().CPlusPlus && NewSSPtr &&
460 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
461 Template, MemberOfUnknownSpecialization))) {
462 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
463 isClassName, HasTrailingDot, ObjectTypePtr,
464 IsCtorOrDtorName,
465 WantNontrivialTypeSourceInfo,
466 IsClassTemplateDeductionContext);
467 if (Ty) {
468 diagnoseTypo(Correction,
469 PDiag(diag::err_unknown_type_or_class_name_suggest)
470 << Result.getLookupName() << isClassName);
471 if (SS && NNS)
472 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
473 *CorrectedII = NewII;
474 return Ty;
478 // If typo correction failed or was not performed, fall through
479 [[fallthrough]];
480 case LookupResult::FoundOverloaded:
481 case LookupResult::FoundUnresolvedValue:
482 Result.suppressDiagnostics();
483 return nullptr;
485 case LookupResult::Ambiguous:
486 // Recover from type-hiding ambiguities by hiding the type. We'll
487 // do the lookup again when looking for an object, and we can
488 // diagnose the error then. If we don't do this, then the error
489 // about hiding the type will be immediately followed by an error
490 // that only makes sense if the identifier was treated like a type.
491 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
492 Result.suppressDiagnostics();
493 return nullptr;
496 // Look to see if we have a type anywhere in the list of results.
497 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
498 Res != ResEnd; ++Res) {
499 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
500 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
501 RealRes) ||
502 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
503 if (!IIDecl ||
504 // Make the selection of the recovery decl deterministic.
505 RealRes->getLocation() < IIDecl->getLocation()) {
506 IIDecl = RealRes;
507 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
512 if (!IIDecl) {
513 // None of the entities we found is a type, so there is no way
514 // to even assume that the result is a type. In this case, don't
515 // complain about the ambiguity. The parser will either try to
516 // perform this lookup again (e.g., as an object name), which
517 // will produce the ambiguity, or will complain that it expected
518 // a type name.
519 Result.suppressDiagnostics();
520 return nullptr;
523 // We found a type within the ambiguous lookup; diagnose the
524 // ambiguity and then return that type. This might be the right
525 // answer, or it might not be, but it suppresses any attempt to
526 // perform the name lookup again.
527 break;
529 case LookupResult::Found:
530 IIDecl = Result.getFoundDecl();
531 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
532 break;
535 assert(IIDecl && "Didn't find decl");
537 QualType T;
538 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
539 // C++ [class.qual]p2: A lookup that would find the injected-class-name
540 // instead names the constructors of the class, except when naming a class.
541 // This is ill-formed when we're not actually forming a ctor or dtor name.
542 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
543 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
544 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
545 FoundRD->isInjectedClassName() &&
546 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
547 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
548 << &II << /*Type*/1;
550 DiagnoseUseOfDecl(IIDecl, NameLoc);
552 T = Context.getTypeDeclType(TD);
553 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
554 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
555 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
556 if (!HasTrailingDot)
557 T = Context.getObjCInterfaceType(IDecl);
558 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
559 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
560 (void)DiagnoseUseOfDecl(UD, NameLoc);
561 // Recover with 'int'
562 return ParsedType::make(Context.IntTy);
563 } else if (AllowDeducedTemplate) {
564 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
565 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
566 TemplateName Template =
567 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
568 T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
569 false);
570 // Don't wrap in a further UsingType.
571 FoundUsingShadow = nullptr;
575 if (T.isNull()) {
576 // If it's not plausibly a type, suppress diagnostics.
577 Result.suppressDiagnostics();
578 return nullptr;
581 if (FoundUsingShadow)
582 T = Context.getUsingType(FoundUsingShadow, T);
584 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
587 // Builds a fake NNS for the given decl context.
588 static NestedNameSpecifier *
589 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
590 for (;; DC = DC->getLookupParent()) {
591 DC = DC->getPrimaryContext();
592 auto *ND = dyn_cast<NamespaceDecl>(DC);
593 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
594 return NestedNameSpecifier::Create(Context, nullptr, ND);
595 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
596 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
597 RD->getTypeForDecl());
598 else if (isa<TranslationUnitDecl>(DC))
599 return NestedNameSpecifier::GlobalSpecifier(Context);
601 llvm_unreachable("something isn't in TU scope?");
604 /// Find the parent class with dependent bases of the innermost enclosing method
605 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
606 /// up allowing unqualified dependent type names at class-level, which MSVC
607 /// correctly rejects.
608 static const CXXRecordDecl *
609 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
610 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
611 DC = DC->getPrimaryContext();
612 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
613 if (MD->getParent()->hasAnyDependentBases())
614 return MD->getParent();
616 return nullptr;
619 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
620 SourceLocation NameLoc,
621 bool IsTemplateTypeArg) {
622 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
624 NestedNameSpecifier *NNS = nullptr;
625 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
626 // If we weren't able to parse a default template argument, delay lookup
627 // until instantiation time by making a non-dependent DependentTypeName. We
628 // pretend we saw a NestedNameSpecifier referring to the current scope, and
629 // lookup is retried.
630 // FIXME: This hurts our diagnostic quality, since we get errors like "no
631 // type named 'Foo' in 'current_namespace'" when the user didn't write any
632 // name specifiers.
633 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
634 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
635 } else if (const CXXRecordDecl *RD =
636 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
637 // Build a DependentNameType that will perform lookup into RD at
638 // instantiation time.
639 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
640 RD->getTypeForDecl());
642 // Diagnose that this identifier was undeclared, and retry the lookup during
643 // template instantiation.
644 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
645 << RD;
646 } else {
647 // This is not a situation that we should recover from.
648 return ParsedType();
651 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
653 // Build type location information. We synthesized the qualifier, so we have
654 // to build a fake NestedNameSpecifierLoc.
655 NestedNameSpecifierLocBuilder NNSLocBuilder;
656 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
657 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
659 TypeLocBuilder Builder;
660 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
661 DepTL.setNameLoc(NameLoc);
662 DepTL.setElaboratedKeywordLoc(SourceLocation());
663 DepTL.setQualifierLoc(QualifierLoc);
664 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
667 /// isTagName() - This method is called *for error recovery purposes only*
668 /// to determine if the specified name is a valid tag name ("struct foo"). If
669 /// so, this returns the TST for the tag corresponding to it (TST_enum,
670 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
671 /// cases in C where the user forgot to specify the tag.
672 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
673 // Do a tag name lookup in this scope.
674 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
675 LookupName(R, S, false);
676 R.suppressDiagnostics();
677 if (R.getResultKind() == LookupResult::Found)
678 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
679 switch (TD->getTagKind()) {
680 case TTK_Struct: return DeclSpec::TST_struct;
681 case TTK_Interface: return DeclSpec::TST_interface;
682 case TTK_Union: return DeclSpec::TST_union;
683 case TTK_Class: return DeclSpec::TST_class;
684 case TTK_Enum: return DeclSpec::TST_enum;
688 return DeclSpec::TST_unspecified;
691 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
692 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
693 /// then downgrade the missing typename error to a warning.
694 /// This is needed for MSVC compatibility; Example:
695 /// @code
696 /// template<class T> class A {
697 /// public:
698 /// typedef int TYPE;
699 /// };
700 /// template<class T> class B : public A<T> {
701 /// public:
702 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
703 /// };
704 /// @endcode
705 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
706 if (CurContext->isRecord()) {
707 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
708 return true;
710 const Type *Ty = SS->getScopeRep()->getAsType();
712 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
713 for (const auto &Base : RD->bases())
714 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
715 return true;
716 return S->isFunctionPrototypeScope();
718 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
721 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
722 SourceLocation IILoc,
723 Scope *S,
724 CXXScopeSpec *SS,
725 ParsedType &SuggestedType,
726 bool IsTemplateName) {
727 // Don't report typename errors for editor placeholders.
728 if (II->isEditorPlaceholder())
729 return;
730 // We don't have anything to suggest (yet).
731 SuggestedType = nullptr;
733 // There may have been a typo in the name of the type. Look up typo
734 // results, in case we have something that we can suggest.
735 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
736 /*AllowTemplates=*/IsTemplateName,
737 /*AllowNonTemplates=*/!IsTemplateName);
738 if (TypoCorrection Corrected =
739 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
740 CCC, CTK_ErrorRecovery)) {
741 // FIXME: Support error recovery for the template-name case.
742 bool CanRecover = !IsTemplateName;
743 if (Corrected.isKeyword()) {
744 // We corrected to a keyword.
745 diagnoseTypo(Corrected,
746 PDiag(IsTemplateName ? diag::err_no_template_suggest
747 : diag::err_unknown_typename_suggest)
748 << II);
749 II = Corrected.getCorrectionAsIdentifierInfo();
750 } else {
751 // We found a similarly-named type or interface; suggest that.
752 if (!SS || !SS->isSet()) {
753 diagnoseTypo(Corrected,
754 PDiag(IsTemplateName ? diag::err_no_template_suggest
755 : diag::err_unknown_typename_suggest)
756 << II, CanRecover);
757 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
758 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
759 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
760 II->getName().equals(CorrectedStr);
761 diagnoseTypo(Corrected,
762 PDiag(IsTemplateName
763 ? diag::err_no_member_template_suggest
764 : diag::err_unknown_nested_typename_suggest)
765 << II << DC << DroppedSpecifier << SS->getRange(),
766 CanRecover);
767 } else {
768 llvm_unreachable("could not have corrected a typo here");
771 if (!CanRecover)
772 return;
774 CXXScopeSpec tmpSS;
775 if (Corrected.getCorrectionSpecifier())
776 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
777 SourceRange(IILoc));
778 // FIXME: Support class template argument deduction here.
779 SuggestedType =
780 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
781 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
782 /*IsCtorOrDtorName=*/false,
783 /*WantNontrivialTypeSourceInfo=*/true);
785 return;
788 if (getLangOpts().CPlusPlus && !IsTemplateName) {
789 // See if II is a class template that the user forgot to pass arguments to.
790 UnqualifiedId Name;
791 Name.setIdentifier(II, IILoc);
792 CXXScopeSpec EmptySS;
793 TemplateTy TemplateResult;
794 bool MemberOfUnknownSpecialization;
795 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
796 Name, nullptr, true, TemplateResult,
797 MemberOfUnknownSpecialization) == TNK_Type_template) {
798 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
799 return;
803 // FIXME: Should we move the logic that tries to recover from a missing tag
804 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
806 if (!SS || (!SS->isSet() && !SS->isInvalid()))
807 Diag(IILoc, IsTemplateName ? diag::err_no_template
808 : diag::err_unknown_typename)
809 << II;
810 else if (DeclContext *DC = computeDeclContext(*SS, false))
811 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
812 : diag::err_typename_nested_not_found)
813 << II << DC << SS->getRange();
814 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
815 SuggestedType =
816 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
817 } else if (isDependentScopeSpecifier(*SS)) {
818 unsigned DiagID = diag::err_typename_missing;
819 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
820 DiagID = diag::ext_typename_missing;
822 Diag(SS->getRange().getBegin(), DiagID)
823 << SS->getScopeRep() << II->getName()
824 << SourceRange(SS->getRange().getBegin(), IILoc)
825 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
826 SuggestedType = ActOnTypenameType(S, SourceLocation(),
827 *SS, *II, IILoc).get();
828 } else {
829 assert(SS && SS->isInvalid() &&
830 "Invalid scope specifier has already been diagnosed");
834 /// Determine whether the given result set contains either a type name
835 /// or
836 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
837 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
838 NextToken.is(tok::less);
840 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
841 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
842 return true;
844 if (CheckTemplate && isa<TemplateDecl>(*I))
845 return true;
848 return false;
851 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
852 Scope *S, CXXScopeSpec &SS,
853 IdentifierInfo *&Name,
854 SourceLocation NameLoc) {
855 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
856 SemaRef.LookupParsedName(R, S, &SS);
857 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
858 StringRef FixItTagName;
859 switch (Tag->getTagKind()) {
860 case TTK_Class:
861 FixItTagName = "class ";
862 break;
864 case TTK_Enum:
865 FixItTagName = "enum ";
866 break;
868 case TTK_Struct:
869 FixItTagName = "struct ";
870 break;
872 case TTK_Interface:
873 FixItTagName = "__interface ";
874 break;
876 case TTK_Union:
877 FixItTagName = "union ";
878 break;
881 StringRef TagName = FixItTagName.drop_back();
882 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
883 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
884 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
886 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
887 I != IEnd; ++I)
888 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
889 << Name << TagName;
891 // Replace lookup results with just the tag decl.
892 Result.clear(Sema::LookupTagName);
893 SemaRef.LookupParsedName(Result, S, &SS);
894 return true;
897 return false;
900 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
901 IdentifierInfo *&Name,
902 SourceLocation NameLoc,
903 const Token &NextToken,
904 CorrectionCandidateCallback *CCC) {
905 DeclarationNameInfo NameInfo(Name, NameLoc);
906 ObjCMethodDecl *CurMethod = getCurMethodDecl();
908 assert(NextToken.isNot(tok::coloncolon) &&
909 "parse nested name specifiers before calling ClassifyName");
910 if (getLangOpts().CPlusPlus && SS.isSet() &&
911 isCurrentClassName(*Name, S, &SS)) {
912 // Per [class.qual]p2, this names the constructors of SS, not the
913 // injected-class-name. We don't have a classification for that.
914 // There's not much point caching this result, since the parser
915 // will reject it later.
916 return NameClassification::Unknown();
919 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
920 LookupParsedName(Result, S, &SS, !CurMethod);
922 if (SS.isInvalid())
923 return NameClassification::Error();
925 // For unqualified lookup in a class template in MSVC mode, look into
926 // dependent base classes where the primary class template is known.
927 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
928 if (ParsedType TypeInBase =
929 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
930 return TypeInBase;
933 // Perform lookup for Objective-C instance variables (including automatically
934 // synthesized instance variables), if we're in an Objective-C method.
935 // FIXME: This lookup really, really needs to be folded in to the normal
936 // unqualified lookup mechanism.
937 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
938 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
939 if (Ivar.isInvalid())
940 return NameClassification::Error();
941 if (Ivar.isUsable())
942 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
944 // We defer builtin creation until after ivar lookup inside ObjC methods.
945 if (Result.empty())
946 LookupBuiltin(Result);
949 bool SecondTry = false;
950 bool IsFilteredTemplateName = false;
952 Corrected:
953 switch (Result.getResultKind()) {
954 case LookupResult::NotFound:
955 // If an unqualified-id is followed by a '(', then we have a function
956 // call.
957 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
958 // In C++, this is an ADL-only call.
959 // FIXME: Reference?
960 if (getLangOpts().CPlusPlus)
961 return NameClassification::UndeclaredNonType();
963 // C90 6.3.2.2:
964 // If the expression that precedes the parenthesized argument list in a
965 // function call consists solely of an identifier, and if no
966 // declaration is visible for this identifier, the identifier is
967 // implicitly declared exactly as if, in the innermost block containing
968 // the function call, the declaration
970 // extern int identifier ();
972 // appeared.
974 // We also allow this in C99 as an extension. However, this is not
975 // allowed in all language modes as functions without prototypes may not
976 // be supported.
977 if (getLangOpts().implicitFunctionsAllowed()) {
978 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
979 return NameClassification::NonType(D);
983 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
984 // In C++20 onwards, this could be an ADL-only call to a function
985 // template, and we're required to assume that this is a template name.
987 // FIXME: Find a way to still do typo correction in this case.
988 TemplateName Template =
989 Context.getAssumedTemplateName(NameInfo.getName());
990 return NameClassification::UndeclaredTemplate(Template);
993 // In C, we first see whether there is a tag type by the same name, in
994 // which case it's likely that the user just forgot to write "enum",
995 // "struct", or "union".
996 if (!getLangOpts().CPlusPlus && !SecondTry &&
997 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
998 break;
1001 // Perform typo correction to determine if there is another name that is
1002 // close to this name.
1003 if (!SecondTry && CCC) {
1004 SecondTry = true;
1005 if (TypoCorrection Corrected =
1006 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1007 &SS, *CCC, CTK_ErrorRecovery)) {
1008 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1009 unsigned QualifiedDiag = diag::err_no_member_suggest;
1011 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1012 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1013 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1014 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1015 UnqualifiedDiag = diag::err_no_template_suggest;
1016 QualifiedDiag = diag::err_no_member_template_suggest;
1017 } else if (UnderlyingFirstDecl &&
1018 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1019 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1020 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1021 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1022 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1025 if (SS.isEmpty()) {
1026 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1027 } else {// FIXME: is this even reachable? Test it.
1028 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1029 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1030 Name->getName().equals(CorrectedStr);
1031 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1032 << Name << computeDeclContext(SS, false)
1033 << DroppedSpecifier << SS.getRange());
1036 // Update the name, so that the caller has the new name.
1037 Name = Corrected.getCorrectionAsIdentifierInfo();
1039 // Typo correction corrected to a keyword.
1040 if (Corrected.isKeyword())
1041 return Name;
1043 // Also update the LookupResult...
1044 // FIXME: This should probably go away at some point
1045 Result.clear();
1046 Result.setLookupName(Corrected.getCorrection());
1047 if (FirstDecl)
1048 Result.addDecl(FirstDecl);
1050 // If we found an Objective-C instance variable, let
1051 // LookupInObjCMethod build the appropriate expression to
1052 // reference the ivar.
1053 // FIXME: This is a gross hack.
1054 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1055 DeclResult R =
1056 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1057 if (R.isInvalid())
1058 return NameClassification::Error();
1059 if (R.isUsable())
1060 return NameClassification::NonType(Ivar);
1063 goto Corrected;
1067 // We failed to correct; just fall through and let the parser deal with it.
1068 Result.suppressDiagnostics();
1069 return NameClassification::Unknown();
1071 case LookupResult::NotFoundInCurrentInstantiation: {
1072 // We performed name lookup into the current instantiation, and there were
1073 // dependent bases, so we treat this result the same way as any other
1074 // dependent nested-name-specifier.
1076 // C++ [temp.res]p2:
1077 // A name used in a template declaration or definition and that is
1078 // dependent on a template-parameter is assumed not to name a type
1079 // unless the applicable name lookup finds a type name or the name is
1080 // qualified by the keyword typename.
1082 // FIXME: If the next token is '<', we might want to ask the parser to
1083 // perform some heroics to see if we actually have a
1084 // template-argument-list, which would indicate a missing 'template'
1085 // keyword here.
1086 return NameClassification::DependentNonType();
1089 case LookupResult::Found:
1090 case LookupResult::FoundOverloaded:
1091 case LookupResult::FoundUnresolvedValue:
1092 break;
1094 case LookupResult::Ambiguous:
1095 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1096 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1097 /*AllowDependent=*/false)) {
1098 // C++ [temp.local]p3:
1099 // A lookup that finds an injected-class-name (10.2) can result in an
1100 // ambiguity in certain cases (for example, if it is found in more than
1101 // one base class). If all of the injected-class-names that are found
1102 // refer to specializations of the same class template, and if the name
1103 // is followed by a template-argument-list, the reference refers to the
1104 // class template itself and not a specialization thereof, and is not
1105 // ambiguous.
1107 // This filtering can make an ambiguous result into an unambiguous one,
1108 // so try again after filtering out template names.
1109 FilterAcceptableTemplateNames(Result);
1110 if (!Result.isAmbiguous()) {
1111 IsFilteredTemplateName = true;
1112 break;
1116 // Diagnose the ambiguity and return an error.
1117 return NameClassification::Error();
1120 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1121 (IsFilteredTemplateName ||
1122 hasAnyAcceptableTemplateNames(
1123 Result, /*AllowFunctionTemplates=*/true,
1124 /*AllowDependent=*/false,
1125 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1126 getLangOpts().CPlusPlus20))) {
1127 // C++ [temp.names]p3:
1128 // After name lookup (3.4) finds that a name is a template-name or that
1129 // an operator-function-id or a literal- operator-id refers to a set of
1130 // overloaded functions any member of which is a function template if
1131 // this is followed by a <, the < is always taken as the delimiter of a
1132 // template-argument-list and never as the less-than operator.
1133 // C++2a [temp.names]p2:
1134 // A name is also considered to refer to a template if it is an
1135 // unqualified-id followed by a < and name lookup finds either one
1136 // or more functions or finds nothing.
1137 if (!IsFilteredTemplateName)
1138 FilterAcceptableTemplateNames(Result);
1140 bool IsFunctionTemplate;
1141 bool IsVarTemplate;
1142 TemplateName Template;
1143 if (Result.end() - Result.begin() > 1) {
1144 IsFunctionTemplate = true;
1145 Template = Context.getOverloadedTemplateName(Result.begin(),
1146 Result.end());
1147 } else if (!Result.empty()) {
1148 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1149 *Result.begin(), /*AllowFunctionTemplates=*/true,
1150 /*AllowDependent=*/false));
1151 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1152 IsVarTemplate = isa<VarTemplateDecl>(TD);
1154 UsingShadowDecl *FoundUsingShadow =
1155 dyn_cast<UsingShadowDecl>(*Result.begin());
1156 assert(!FoundUsingShadow ||
1157 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1158 Template =
1159 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1160 if (SS.isNotEmpty())
1161 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1162 /*TemplateKeyword=*/false,
1163 Template);
1164 } else {
1165 // All results were non-template functions. This is a function template
1166 // name.
1167 IsFunctionTemplate = true;
1168 Template = Context.getAssumedTemplateName(NameInfo.getName());
1171 if (IsFunctionTemplate) {
1172 // Function templates always go through overload resolution, at which
1173 // point we'll perform the various checks (e.g., accessibility) we need
1174 // to based on which function we selected.
1175 Result.suppressDiagnostics();
1177 return NameClassification::FunctionTemplate(Template);
1180 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1181 : NameClassification::TypeTemplate(Template);
1184 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1185 QualType T = Context.getTypeDeclType(Type);
1186 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1187 T = Context.getUsingType(USD, T);
1188 return buildNamedType(*this, &SS, T, NameLoc);
1191 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1192 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1193 DiagnoseUseOfDecl(Type, NameLoc);
1194 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1195 return BuildTypeFor(Type, *Result.begin());
1198 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1199 if (!Class) {
1200 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1201 if (ObjCCompatibleAliasDecl *Alias =
1202 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1203 Class = Alias->getClassInterface();
1206 if (Class) {
1207 DiagnoseUseOfDecl(Class, NameLoc);
1209 if (NextToken.is(tok::period)) {
1210 // Interface. <something> is parsed as a property reference expression.
1211 // Just return "unknown" as a fall-through for now.
1212 Result.suppressDiagnostics();
1213 return NameClassification::Unknown();
1216 QualType T = Context.getObjCInterfaceType(Class);
1217 return ParsedType::make(T);
1220 if (isa<ConceptDecl>(FirstDecl))
1221 return NameClassification::Concept(
1222 TemplateName(cast<TemplateDecl>(FirstDecl)));
1224 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1225 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1226 return NameClassification::Error();
1229 // We can have a type template here if we're classifying a template argument.
1230 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1231 !isa<VarTemplateDecl>(FirstDecl))
1232 return NameClassification::TypeTemplate(
1233 TemplateName(cast<TemplateDecl>(FirstDecl)));
1235 // Check for a tag type hidden by a non-type decl in a few cases where it
1236 // seems likely a type is wanted instead of the non-type that was found.
1237 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1238 if ((NextToken.is(tok::identifier) ||
1239 (NextIsOp &&
1240 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1241 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1242 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1243 DiagnoseUseOfDecl(Type, NameLoc);
1244 return BuildTypeFor(Type, *Result.begin());
1247 // If we already know which single declaration is referenced, just annotate
1248 // that declaration directly. Defer resolving even non-overloaded class
1249 // member accesses, as we need to defer certain access checks until we know
1250 // the context.
1251 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1252 if (Result.isSingleResult() && !ADL &&
1253 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1254 return NameClassification::NonType(Result.getRepresentativeDecl());
1256 // Otherwise, this is an overload set that we will need to resolve later.
1257 Result.suppressDiagnostics();
1258 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1259 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1260 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1261 Result.begin(), Result.end()));
1264 ExprResult
1265 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1266 SourceLocation NameLoc) {
1267 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1268 CXXScopeSpec SS;
1269 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1270 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1273 ExprResult
1274 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1275 IdentifierInfo *Name,
1276 SourceLocation NameLoc,
1277 bool IsAddressOfOperand) {
1278 DeclarationNameInfo NameInfo(Name, NameLoc);
1279 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1280 NameInfo, IsAddressOfOperand,
1281 /*TemplateArgs=*/nullptr);
1284 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1285 NamedDecl *Found,
1286 SourceLocation NameLoc,
1287 const Token &NextToken) {
1288 if (getCurMethodDecl() && SS.isEmpty())
1289 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1290 return BuildIvarRefExpr(S, NameLoc, Ivar);
1292 // Reconstruct the lookup result.
1293 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1294 Result.addDecl(Found);
1295 Result.resolveKind();
1297 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1298 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1301 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1302 // For an implicit class member access, transform the result into a member
1303 // access expression if necessary.
1304 auto *ULE = cast<UnresolvedLookupExpr>(E);
1305 if ((*ULE->decls_begin())->isCXXClassMember()) {
1306 CXXScopeSpec SS;
1307 SS.Adopt(ULE->getQualifierLoc());
1309 // Reconstruct the lookup result.
1310 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1311 LookupOrdinaryName);
1312 Result.setNamingClass(ULE->getNamingClass());
1313 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1314 Result.addDecl(*I, I.getAccess());
1315 Result.resolveKind();
1316 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1317 nullptr, S);
1320 // Otherwise, this is already in the form we needed, and no further checks
1321 // are necessary.
1322 return ULE;
1325 Sema::TemplateNameKindForDiagnostics
1326 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1327 auto *TD = Name.getAsTemplateDecl();
1328 if (!TD)
1329 return TemplateNameKindForDiagnostics::DependentTemplate;
1330 if (isa<ClassTemplateDecl>(TD))
1331 return TemplateNameKindForDiagnostics::ClassTemplate;
1332 if (isa<FunctionTemplateDecl>(TD))
1333 return TemplateNameKindForDiagnostics::FunctionTemplate;
1334 if (isa<VarTemplateDecl>(TD))
1335 return TemplateNameKindForDiagnostics::VarTemplate;
1336 if (isa<TypeAliasTemplateDecl>(TD))
1337 return TemplateNameKindForDiagnostics::AliasTemplate;
1338 if (isa<TemplateTemplateParmDecl>(TD))
1339 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1340 if (isa<ConceptDecl>(TD))
1341 return TemplateNameKindForDiagnostics::Concept;
1342 return TemplateNameKindForDiagnostics::DependentTemplate;
1345 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1346 assert(DC->getLexicalParent() == CurContext &&
1347 "The next DeclContext should be lexically contained in the current one.");
1348 CurContext = DC;
1349 S->setEntity(DC);
1352 void Sema::PopDeclContext() {
1353 assert(CurContext && "DeclContext imbalance!");
1355 CurContext = CurContext->getLexicalParent();
1356 assert(CurContext && "Popped translation unit!");
1359 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1360 Decl *D) {
1361 // Unlike PushDeclContext, the context to which we return is not necessarily
1362 // the containing DC of TD, because the new context will be some pre-existing
1363 // TagDecl definition instead of a fresh one.
1364 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1365 CurContext = cast<TagDecl>(D)->getDefinition();
1366 assert(CurContext && "skipping definition of undefined tag");
1367 // Start lookups from the parent of the current context; we don't want to look
1368 // into the pre-existing complete definition.
1369 S->setEntity(CurContext->getLookupParent());
1370 return Result;
1373 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1374 CurContext = static_cast<decltype(CurContext)>(Context);
1377 /// EnterDeclaratorContext - Used when we must lookup names in the context
1378 /// of a declarator's nested name specifier.
1380 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1381 // C++0x [basic.lookup.unqual]p13:
1382 // A name used in the definition of a static data member of class
1383 // X (after the qualified-id of the static member) is looked up as
1384 // if the name was used in a member function of X.
1385 // C++0x [basic.lookup.unqual]p14:
1386 // If a variable member of a namespace is defined outside of the
1387 // scope of its namespace then any name used in the definition of
1388 // the variable member (after the declarator-id) is looked up as
1389 // if the definition of the variable member occurred in its
1390 // namespace.
1391 // Both of these imply that we should push a scope whose context
1392 // is the semantic context of the declaration. We can't use
1393 // PushDeclContext here because that context is not necessarily
1394 // lexically contained in the current context. Fortunately,
1395 // the containing scope should have the appropriate information.
1397 assert(!S->getEntity() && "scope already has entity");
1399 #ifndef NDEBUG
1400 Scope *Ancestor = S->getParent();
1401 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1402 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1403 #endif
1405 CurContext = DC;
1406 S->setEntity(DC);
1408 if (S->getParent()->isTemplateParamScope()) {
1409 // Also set the corresponding entities for all immediately-enclosing
1410 // template parameter scopes.
1411 EnterTemplatedContext(S->getParent(), DC);
1415 void Sema::ExitDeclaratorContext(Scope *S) {
1416 assert(S->getEntity() == CurContext && "Context imbalance!");
1418 // Switch back to the lexical context. The safety of this is
1419 // enforced by an assert in EnterDeclaratorContext.
1420 Scope *Ancestor = S->getParent();
1421 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1422 CurContext = Ancestor->getEntity();
1424 // We don't need to do anything with the scope, which is going to
1425 // disappear.
1428 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1429 assert(S->isTemplateParamScope() &&
1430 "expected to be initializing a template parameter scope");
1432 // C++20 [temp.local]p7:
1433 // In the definition of a member of a class template that appears outside
1434 // of the class template definition, the name of a member of the class
1435 // template hides the name of a template-parameter of any enclosing class
1436 // templates (but not a template-parameter of the member if the member is a
1437 // class or function template).
1438 // C++20 [temp.local]p9:
1439 // In the definition of a class template or in the definition of a member
1440 // of such a template that appears outside of the template definition, for
1441 // each non-dependent base class (13.8.2.1), if the name of the base class
1442 // or the name of a member of the base class is the same as the name of a
1443 // template-parameter, the base class name or member name hides the
1444 // template-parameter name (6.4.10).
1446 // This means that a template parameter scope should be searched immediately
1447 // after searching the DeclContext for which it is a template parameter
1448 // scope. For example, for
1449 // template<typename T> template<typename U> template<typename V>
1450 // void N::A<T>::B<U>::f(...)
1451 // we search V then B<U> (and base classes) then U then A<T> (and base
1452 // classes) then T then N then ::.
1453 unsigned ScopeDepth = getTemplateDepth(S);
1454 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1455 DeclContext *SearchDCAfterScope = DC;
1456 for (; DC; DC = DC->getLookupParent()) {
1457 if (const TemplateParameterList *TPL =
1458 cast<Decl>(DC)->getDescribedTemplateParams()) {
1459 unsigned DCDepth = TPL->getDepth() + 1;
1460 if (DCDepth > ScopeDepth)
1461 continue;
1462 if (ScopeDepth == DCDepth)
1463 SearchDCAfterScope = DC = DC->getLookupParent();
1464 break;
1467 S->setLookupEntity(SearchDCAfterScope);
1471 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1472 // We assume that the caller has already called
1473 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1474 FunctionDecl *FD = D->getAsFunction();
1475 if (!FD)
1476 return;
1478 // Same implementation as PushDeclContext, but enters the context
1479 // from the lexical parent, rather than the top-level class.
1480 assert(CurContext == FD->getLexicalParent() &&
1481 "The next DeclContext should be lexically contained in the current one.");
1482 CurContext = FD;
1483 S->setEntity(CurContext);
1485 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1486 ParmVarDecl *Param = FD->getParamDecl(P);
1487 // If the parameter has an identifier, then add it to the scope
1488 if (Param->getIdentifier()) {
1489 S->AddDecl(Param);
1490 IdResolver.AddDecl(Param);
1495 void Sema::ActOnExitFunctionContext() {
1496 // Same implementation as PopDeclContext, but returns to the lexical parent,
1497 // rather than the top-level class.
1498 assert(CurContext && "DeclContext imbalance!");
1499 CurContext = CurContext->getLexicalParent();
1500 assert(CurContext && "Popped translation unit!");
1503 /// Determine whether overloading is allowed for a new function
1504 /// declaration considering prior declarations of the same name.
1506 /// This routine determines whether overloading is possible, not
1507 /// whether a new declaration actually overloads a previous one.
1508 /// It will return true in C++ (where overloads are alway permitted)
1509 /// or, as a C extension, when either the new declaration or a
1510 /// previous one is declared with the 'overloadable' attribute.
1511 static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1512 ASTContext &Context,
1513 const FunctionDecl *New) {
1514 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1515 return true;
1517 // Multiversion function declarations are not overloads in the
1518 // usual sense of that term, but lookup will report that an
1519 // overload set was found if more than one multiversion function
1520 // declaration is present for the same name. It is therefore
1521 // inadequate to assume that some prior declaration(s) had
1522 // the overloadable attribute; checking is required. Since one
1523 // declaration is permitted to omit the attribute, it is necessary
1524 // to check at least two; hence the 'any_of' check below. Note that
1525 // the overloadable attribute is implicitly added to declarations
1526 // that were required to have it but did not.
1527 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1528 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1529 return ND->hasAttr<OverloadableAttr>();
1531 } else if (Previous.getResultKind() == LookupResult::Found)
1532 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1534 return false;
1537 /// Add this decl to the scope shadowed decl chains.
1538 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1539 // Move up the scope chain until we find the nearest enclosing
1540 // non-transparent context. The declaration will be introduced into this
1541 // scope.
1542 while (S->getEntity() && S->getEntity()->isTransparentContext())
1543 S = S->getParent();
1545 // Add scoped declarations into their context, so that they can be
1546 // found later. Declarations without a context won't be inserted
1547 // into any context.
1548 if (AddToContext)
1549 CurContext->addDecl(D);
1551 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1552 // are function-local declarations.
1553 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1554 return;
1556 // Template instantiations should also not be pushed into scope.
1557 if (isa<FunctionDecl>(D) &&
1558 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1559 return;
1561 // If this replaces anything in the current scope,
1562 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1563 IEnd = IdResolver.end();
1564 for (; I != IEnd; ++I) {
1565 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1566 S->RemoveDecl(*I);
1567 IdResolver.RemoveDecl(*I);
1569 // Should only need to replace one decl.
1570 break;
1574 S->AddDecl(D);
1576 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1577 // Implicitly-generated labels may end up getting generated in an order that
1578 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1579 // the label at the appropriate place in the identifier chain.
1580 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1581 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1582 if (IDC == CurContext) {
1583 if (!S->isDeclScope(*I))
1584 continue;
1585 } else if (IDC->Encloses(CurContext))
1586 break;
1589 IdResolver.InsertDeclAfter(I, D);
1590 } else {
1591 IdResolver.AddDecl(D);
1593 warnOnReservedIdentifier(D);
1596 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1597 bool AllowInlineNamespace) const {
1598 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1601 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1602 DeclContext *TargetDC = DC->getPrimaryContext();
1603 do {
1604 if (DeclContext *ScopeDC = S->getEntity())
1605 if (ScopeDC->getPrimaryContext() == TargetDC)
1606 return S;
1607 } while ((S = S->getParent()));
1609 return nullptr;
1612 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1613 DeclContext*,
1614 ASTContext&);
1616 /// Filters out lookup results that don't fall within the given scope
1617 /// as determined by isDeclInScope.
1618 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1619 bool ConsiderLinkage,
1620 bool AllowInlineNamespace) {
1621 LookupResult::Filter F = R.makeFilter();
1622 while (F.hasNext()) {
1623 NamedDecl *D = F.next();
1625 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1626 continue;
1628 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1629 continue;
1631 F.erase();
1634 F.done();
1637 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1638 /// have compatible owning modules.
1639 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1640 // [module.interface]p7:
1641 // A declaration is attached to a module as follows:
1642 // - If the declaration is a non-dependent friend declaration that nominates a
1643 // function with a declarator-id that is a qualified-id or template-id or that
1644 // nominates a class other than with an elaborated-type-specifier with neither
1645 // a nested-name-specifier nor a simple-template-id, it is attached to the
1646 // module to which the friend is attached ([basic.link]).
1647 if (New->getFriendObjectKind() &&
1648 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1649 New->setLocalOwningModule(Old->getOwningModule());
1650 makeMergedDefinitionVisible(New);
1651 return false;
1654 Module *NewM = New->getOwningModule();
1655 Module *OldM = Old->getOwningModule();
1657 if (NewM && NewM->isPrivateModule())
1658 NewM = NewM->Parent;
1659 if (OldM && OldM->isPrivateModule())
1660 OldM = OldM->Parent;
1662 if (NewM == OldM)
1663 return false;
1665 if (NewM && OldM) {
1666 // A module implementation unit has visibility of the decls in its
1667 // implicitly imported interface.
1668 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1669 return false;
1671 // Partitions are part of the module, but a partition could import another
1672 // module, so verify that the PMIs agree.
1673 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1674 NewM->getPrimaryModuleInterfaceName() ==
1675 OldM->getPrimaryModuleInterfaceName())
1676 return false;
1679 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1680 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1681 if (NewIsModuleInterface || OldIsModuleInterface) {
1682 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1683 // if a declaration of D [...] appears in the purview of a module, all
1684 // other such declarations shall appear in the purview of the same module
1685 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1686 << New
1687 << NewIsModuleInterface
1688 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1689 << OldIsModuleInterface
1690 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1691 Diag(Old->getLocation(), diag::note_previous_declaration);
1692 New->setInvalidDecl();
1693 return true;
1696 return false;
1699 // [module.interface]p6:
1700 // A redeclaration of an entity X is implicitly exported if X was introduced by
1701 // an exported declaration; otherwise it shall not be exported.
1702 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1703 // [module.interface]p1:
1704 // An export-declaration shall inhabit a namespace scope.
1706 // So it is meaningless to talk about redeclaration which is not at namespace
1707 // scope.
1708 if (!New->getLexicalDeclContext()
1709 ->getNonTransparentContext()
1710 ->isFileContext() ||
1711 !Old->getLexicalDeclContext()
1712 ->getNonTransparentContext()
1713 ->isFileContext())
1714 return false;
1716 bool IsNewExported = New->isInExportDeclContext();
1717 bool IsOldExported = Old->isInExportDeclContext();
1719 // It should be irrevelant if both of them are not exported.
1720 if (!IsNewExported && !IsOldExported)
1721 return false;
1723 if (IsOldExported)
1724 return false;
1726 assert(IsNewExported);
1728 auto Lk = Old->getFormalLinkage();
1729 int S = 0;
1730 if (Lk == Linkage::InternalLinkage)
1731 S = 1;
1732 else if (Lk == Linkage::ModuleLinkage)
1733 S = 2;
1734 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1735 Diag(Old->getLocation(), diag::note_previous_declaration);
1736 return true;
1739 // A wrapper function for checking the semantic restrictions of
1740 // a redeclaration within a module.
1741 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1742 if (CheckRedeclarationModuleOwnership(New, Old))
1743 return true;
1745 if (CheckRedeclarationExported(New, Old))
1746 return true;
1748 return false;
1751 // Check the redefinition in C++20 Modules.
1753 // [basic.def.odr]p14:
1754 // For any definable item D with definitions in multiple translation units,
1755 // - if D is a non-inline non-templated function or variable, or
1756 // - if the definitions in different translation units do not satisfy the
1757 // following requirements,
1758 // the program is ill-formed; a diagnostic is required only if the definable
1759 // item is attached to a named module and a prior definition is reachable at
1760 // the point where a later definition occurs.
1761 // - Each such definition shall not be attached to a named module
1762 // ([module.unit]).
1763 // - Each such definition shall consist of the same sequence of tokens, ...
1764 // ...
1766 // Return true if the redefinition is not allowed. Return false otherwise.
1767 bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1768 const NamedDecl *Old) const {
1769 assert(getASTContext().isSameEntity(New, Old) &&
1770 "New and Old are not the same definition, we should diagnostic it "
1771 "immediately instead of checking it.");
1772 assert(const_cast<Sema *>(this)->isReachable(New) &&
1773 const_cast<Sema *>(this)->isReachable(Old) &&
1774 "We shouldn't see unreachable definitions here.");
1776 Module *NewM = New->getOwningModule();
1777 Module *OldM = Old->getOwningModule();
1779 // We only checks for named modules here. The header like modules is skipped.
1780 // FIXME: This is not right if we import the header like modules in the module
1781 // purview.
1783 // For example, assuming "header.h" provides definition for `D`.
1784 // ```C++
1785 // //--- M.cppm
1786 // export module M;
1787 // import "header.h"; // or #include "header.h" but import it by clang modules
1788 // actually.
1790 // //--- Use.cpp
1791 // import M;
1792 // import "header.h"; // or uses clang modules.
1793 // ```
1795 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1796 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1797 // reject it. But the current implementation couldn't detect the case since we
1798 // don't record the information about the importee modules.
1800 // But this might not be painful in practice. Since the design of C++20 Named
1801 // Modules suggests us to use headers in global module fragment instead of
1802 // module purview.
1803 if (NewM && NewM->isHeaderLikeModule())
1804 NewM = nullptr;
1805 if (OldM && OldM->isHeaderLikeModule())
1806 OldM = nullptr;
1808 if (!NewM && !OldM)
1809 return true;
1811 // [basic.def.odr]p14.3
1812 // Each such definition shall not be attached to a named module
1813 // ([module.unit]).
1814 if ((NewM && NewM->isModulePurview()) || (OldM && OldM->isModulePurview()))
1815 return true;
1817 // Then New and Old lives in the same TU if their share one same module unit.
1818 if (NewM)
1819 NewM = NewM->getTopLevelModule();
1820 if (OldM)
1821 OldM = OldM->getTopLevelModule();
1822 return OldM == NewM;
1825 static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1826 if (D->getDeclContext()->isFileContext())
1827 return false;
1829 return isa<UsingShadowDecl>(D) ||
1830 isa<UnresolvedUsingTypenameDecl>(D) ||
1831 isa<UnresolvedUsingValueDecl>(D);
1834 /// Removes using shadow declarations not at class scope from the lookup
1835 /// results.
1836 static void RemoveUsingDecls(LookupResult &R) {
1837 LookupResult::Filter F = R.makeFilter();
1838 while (F.hasNext())
1839 if (isUsingDeclNotAtClassScope(F.next()))
1840 F.erase();
1842 F.done();
1845 /// Check for this common pattern:
1846 /// @code
1847 /// class S {
1848 /// S(const S&); // DO NOT IMPLEMENT
1849 /// void operator=(const S&); // DO NOT IMPLEMENT
1850 /// };
1851 /// @endcode
1852 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1853 // FIXME: Should check for private access too but access is set after we get
1854 // the decl here.
1855 if (D->doesThisDeclarationHaveABody())
1856 return false;
1858 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1859 return CD->isCopyConstructor();
1860 return D->isCopyAssignmentOperator();
1863 // We need this to handle
1865 // typedef struct {
1866 // void *foo() { return 0; }
1867 // } A;
1869 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1870 // for example. If 'A', foo will have external linkage. If we have '*A',
1871 // foo will have no linkage. Since we can't know until we get to the end
1872 // of the typedef, this function finds out if D might have non-external linkage.
1873 // Callers should verify at the end of the TU if it D has external linkage or
1874 // not.
1875 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1876 const DeclContext *DC = D->getDeclContext();
1877 while (!DC->isTranslationUnit()) {
1878 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1879 if (!RD->hasNameForLinkage())
1880 return true;
1882 DC = DC->getParent();
1885 return !D->isExternallyVisible();
1888 // FIXME: This needs to be refactored; some other isInMainFile users want
1889 // these semantics.
1890 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1891 if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1892 return false;
1893 return S.SourceMgr.isInMainFile(Loc);
1896 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1897 assert(D);
1899 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1900 return false;
1902 // Ignore all entities declared within templates, and out-of-line definitions
1903 // of members of class templates.
1904 if (D->getDeclContext()->isDependentContext() ||
1905 D->getLexicalDeclContext()->isDependentContext())
1906 return false;
1908 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1909 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1910 return false;
1911 // A non-out-of-line declaration of a member specialization was implicitly
1912 // instantiated; it's the out-of-line declaration that we're interested in.
1913 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1914 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1915 return false;
1917 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1918 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1919 return false;
1920 } else {
1921 // 'static inline' functions are defined in headers; don't warn.
1922 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1923 return false;
1926 if (FD->doesThisDeclarationHaveABody() &&
1927 Context.DeclMustBeEmitted(FD))
1928 return false;
1929 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1930 // Constants and utility variables are defined in headers with internal
1931 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1932 // like "inline".)
1933 if (!isMainFileLoc(*this, VD->getLocation()))
1934 return false;
1936 if (Context.DeclMustBeEmitted(VD))
1937 return false;
1939 if (VD->isStaticDataMember() &&
1940 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1941 return false;
1942 if (VD->isStaticDataMember() &&
1943 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1944 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1945 return false;
1947 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1948 return false;
1949 } else {
1950 return false;
1953 // Only warn for unused decls internal to the translation unit.
1954 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1955 // for inline functions defined in the main source file, for instance.
1956 return mightHaveNonExternalLinkage(D);
1959 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1960 if (!D)
1961 return;
1963 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1964 const FunctionDecl *First = FD->getFirstDecl();
1965 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1966 return; // First should already be in the vector.
1969 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1970 const VarDecl *First = VD->getFirstDecl();
1971 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1972 return; // First should already be in the vector.
1975 if (ShouldWarnIfUnusedFileScopedDecl(D))
1976 UnusedFileScopedDecls.push_back(D);
1979 static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1980 const NamedDecl *D) {
1981 if (D->isInvalidDecl())
1982 return false;
1984 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1985 // For a decomposition declaration, warn if none of the bindings are
1986 // referenced, instead of if the variable itself is referenced (which
1987 // it is, by the bindings' expressions).
1988 bool IsAllPlaceholders = true;
1989 for (auto *BD : DD->bindings()) {
1990 if (BD->isReferenced())
1991 return false;
1992 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
1994 if (IsAllPlaceholders)
1995 return false;
1996 } else if (!D->getDeclName()) {
1997 return false;
1998 } else if (D->isReferenced() || D->isUsed()) {
1999 return false;
2002 if (D->isPlaceholderVar(LangOpts))
2003 return false;
2005 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2006 D->hasAttr<CleanupAttr>())
2007 return false;
2009 if (isa<LabelDecl>(D))
2010 return true;
2012 // Except for labels, we only care about unused decls that are local to
2013 // functions.
2014 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2015 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2016 // For dependent types, the diagnostic is deferred.
2017 WithinFunction =
2018 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2019 if (!WithinFunction)
2020 return false;
2022 if (isa<TypedefNameDecl>(D))
2023 return true;
2025 // White-list anything that isn't a local variable.
2026 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
2027 return false;
2029 // Types of valid local variables should be complete, so this should succeed.
2030 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2032 const Expr *Init = VD->getInit();
2033 if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
2034 Init = Cleanups->getSubExpr();
2036 const auto *Ty = VD->getType().getTypePtr();
2038 // Only look at the outermost level of typedef.
2039 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2040 // Allow anything marked with __attribute__((unused)).
2041 if (TT->getDecl()->hasAttr<UnusedAttr>())
2042 return false;
2045 // Warn for reference variables whose initializtion performs lifetime
2046 // extension.
2047 if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
2048 if (MTE->getExtendingDecl()) {
2049 Ty = VD->getType().getNonReferenceType().getTypePtr();
2050 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2054 // If we failed to complete the type for some reason, or if the type is
2055 // dependent, don't diagnose the variable.
2056 if (Ty->isIncompleteType() || Ty->isDependentType())
2057 return false;
2059 // Look at the element type to ensure that the warning behaviour is
2060 // consistent for both scalars and arrays.
2061 Ty = Ty->getBaseElementTypeUnsafe();
2063 if (const TagType *TT = Ty->getAs<TagType>()) {
2064 const TagDecl *Tag = TT->getDecl();
2065 if (Tag->hasAttr<UnusedAttr>())
2066 return false;
2068 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2069 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2070 return false;
2072 if (Init) {
2073 const CXXConstructExpr *Construct =
2074 dyn_cast<CXXConstructExpr>(Init);
2075 if (Construct && !Construct->isElidable()) {
2076 CXXConstructorDecl *CD = Construct->getConstructor();
2077 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2078 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2079 return false;
2082 // Suppress the warning if we don't know how this is constructed, and
2083 // it could possibly be non-trivial constructor.
2084 if (Init->isTypeDependent()) {
2085 for (const CXXConstructorDecl *Ctor : RD->ctors())
2086 if (!Ctor->isTrivial())
2087 return false;
2090 // Suppress the warning if the constructor is unresolved because
2091 // its arguments are dependent.
2092 if (isa<CXXUnresolvedConstructExpr>(Init))
2093 return false;
2098 // TODO: __attribute__((unused)) templates?
2101 return true;
2104 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2105 FixItHint &Hint) {
2106 if (isa<LabelDecl>(D)) {
2107 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2108 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2109 /*SkipTrailingWhitespaceAndNewline=*/false);
2110 if (AfterColon.isInvalid())
2111 return;
2112 Hint = FixItHint::CreateRemoval(
2113 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2117 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2118 DiagnoseUnusedNestedTypedefs(
2119 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2122 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2123 DiagReceiverTy DiagReceiver) {
2124 if (D->getTypeForDecl()->isDependentType())
2125 return;
2127 for (auto *TmpD : D->decls()) {
2128 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2129 DiagnoseUnusedDecl(T, DiagReceiver);
2130 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2131 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2135 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2136 DiagnoseUnusedDecl(
2137 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2140 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2141 /// unless they are marked attr(unused).
2142 void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2143 if (!ShouldDiagnoseUnusedDecl(getLangOpts(), D))
2144 return;
2146 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2147 // typedefs can be referenced later on, so the diagnostics are emitted
2148 // at end-of-translation-unit.
2149 UnusedLocalTypedefNameCandidates.insert(TD);
2150 return;
2153 FixItHint Hint;
2154 GenerateFixForUnusedDecl(D, Context, Hint);
2156 unsigned DiagID;
2157 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2158 DiagID = diag::warn_unused_exception_param;
2159 else if (isa<LabelDecl>(D))
2160 DiagID = diag::warn_unused_label;
2161 else
2162 DiagID = diag::warn_unused_variable;
2164 SourceLocation DiagLoc = D->getLocation();
2165 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2168 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2169 DiagReceiverTy DiagReceiver) {
2170 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2171 // it's not really unused.
2172 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2173 return;
2175 // In C++, `_` variables behave as if they were maybe_unused
2176 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2177 return;
2179 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2181 if (Ty->isReferenceType() || Ty->isDependentType())
2182 return;
2184 if (const TagType *TT = Ty->getAs<TagType>()) {
2185 const TagDecl *Tag = TT->getDecl();
2186 if (Tag->hasAttr<UnusedAttr>())
2187 return;
2188 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2189 // mimic gcc's behavior.
2190 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2191 if (!RD->hasAttr<WarnUnusedAttr>())
2192 return;
2196 // Don't warn about __block Objective-C pointer variables, as they might
2197 // be assigned in the block but not used elsewhere for the purpose of lifetime
2198 // extension.
2199 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2200 return;
2202 // Don't warn about Objective-C pointer variables with precise lifetime
2203 // semantics; they can be used to ensure ARC releases the object at a known
2204 // time, which may mean assignment but no other references.
2205 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2206 return;
2208 auto iter = RefsMinusAssignments.find(VD);
2209 if (iter == RefsMinusAssignments.end())
2210 return;
2212 assert(iter->getSecond() >= 0 &&
2213 "Found a negative number of references to a VarDecl");
2214 if (iter->getSecond() != 0)
2215 return;
2216 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2217 : diag::warn_unused_but_set_variable;
2218 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2221 static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2222 Sema::DiagReceiverTy DiagReceiver) {
2223 // Verify that we have no forward references left. If so, there was a goto
2224 // or address of a label taken, but no definition of it. Label fwd
2225 // definitions are indicated with a null substmt which is also not a resolved
2226 // MS inline assembly label name.
2227 bool Diagnose = false;
2228 if (L->isMSAsmLabel())
2229 Diagnose = !L->isResolvedMSAsmLabel();
2230 else
2231 Diagnose = L->getStmt() == nullptr;
2232 if (Diagnose)
2233 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2234 << L);
2237 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2238 S->applyNRVO();
2240 if (S->decl_empty()) return;
2241 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2242 "Scope shouldn't contain decls!");
2244 /// We visit the decls in non-deterministic order, but we want diagnostics
2245 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2246 /// and sort the diagnostics before emitting them, after we visited all decls.
2247 struct LocAndDiag {
2248 SourceLocation Loc;
2249 std::optional<SourceLocation> PreviousDeclLoc;
2250 PartialDiagnostic PD;
2252 SmallVector<LocAndDiag, 16> DeclDiags;
2253 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2254 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2256 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2257 SourceLocation PreviousDeclLoc,
2258 PartialDiagnostic PD) {
2259 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2262 for (auto *TmpD : S->decls()) {
2263 assert(TmpD && "This decl didn't get pushed??");
2265 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2266 NamedDecl *D = cast<NamedDecl>(TmpD);
2268 // Diagnose unused variables in this scope.
2269 if (!S->hasUnrecoverableErrorOccurred()) {
2270 DiagnoseUnusedDecl(D, addDiag);
2271 if (const auto *RD = dyn_cast<RecordDecl>(D))
2272 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2273 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2274 DiagnoseUnusedButSetDecl(VD, addDiag);
2275 RefsMinusAssignments.erase(VD);
2279 if (!D->getDeclName()) continue;
2281 // If this was a forward reference to a label, verify it was defined.
2282 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2283 CheckPoppedLabel(LD, *this, addDiag);
2285 // Remove this name from our lexical scope, and warn on it if we haven't
2286 // already.
2287 IdResolver.RemoveDecl(D);
2288 auto ShadowI = ShadowingDecls.find(D);
2289 if (ShadowI != ShadowingDecls.end()) {
2290 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2291 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2292 PDiag(diag::warn_ctor_parm_shadows_field)
2293 << D << FD << FD->getParent());
2295 ShadowingDecls.erase(ShadowI);
2299 llvm::sort(DeclDiags,
2300 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2301 // The particular order for diagnostics is not important, as long
2302 // as the order is deterministic. Using the raw location is going
2303 // to generally be in source order unless there are macro
2304 // expansions involved.
2305 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2307 for (const LocAndDiag &D : DeclDiags) {
2308 Diag(D.Loc, D.PD);
2309 if (D.PreviousDeclLoc)
2310 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2314 /// Look for an Objective-C class in the translation unit.
2316 /// \param Id The name of the Objective-C class we're looking for. If
2317 /// typo-correction fixes this name, the Id will be updated
2318 /// to the fixed name.
2320 /// \param IdLoc The location of the name in the translation unit.
2322 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2323 /// if there is no class with the given name.
2325 /// \returns The declaration of the named Objective-C class, or NULL if the
2326 /// class could not be found.
2327 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2328 SourceLocation IdLoc,
2329 bool DoTypoCorrection) {
2330 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2331 // creation from this context.
2332 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2334 if (!IDecl && DoTypoCorrection) {
2335 // Perform typo correction at the given location, but only if we
2336 // find an Objective-C class name.
2337 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2338 if (TypoCorrection C =
2339 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2340 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2341 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2342 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2343 Id = IDecl->getIdentifier();
2346 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2347 // This routine must always return a class definition, if any.
2348 if (Def && Def->getDefinition())
2349 Def = Def->getDefinition();
2350 return Def;
2353 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2354 /// from S, where a non-field would be declared. This routine copes
2355 /// with the difference between C and C++ scoping rules in structs and
2356 /// unions. For example, the following code is well-formed in C but
2357 /// ill-formed in C++:
2358 /// @code
2359 /// struct S6 {
2360 /// enum { BAR } e;
2361 /// };
2363 /// void test_S6() {
2364 /// struct S6 a;
2365 /// a.e = BAR;
2366 /// }
2367 /// @endcode
2368 /// For the declaration of BAR, this routine will return a different
2369 /// scope. The scope S will be the scope of the unnamed enumeration
2370 /// within S6. In C++, this routine will return the scope associated
2371 /// with S6, because the enumeration's scope is a transparent
2372 /// context but structures can contain non-field names. In C, this
2373 /// routine will return the translation unit scope, since the
2374 /// enumeration's scope is a transparent context and structures cannot
2375 /// contain non-field names.
2376 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2377 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2378 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2379 (S->isClassScope() && !getLangOpts().CPlusPlus))
2380 S = S->getParent();
2381 return S;
2384 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2385 ASTContext::GetBuiltinTypeError Error) {
2386 switch (Error) {
2387 case ASTContext::GE_None:
2388 return "";
2389 case ASTContext::GE_Missing_type:
2390 return BuiltinInfo.getHeaderName(ID);
2391 case ASTContext::GE_Missing_stdio:
2392 return "stdio.h";
2393 case ASTContext::GE_Missing_setjmp:
2394 return "setjmp.h";
2395 case ASTContext::GE_Missing_ucontext:
2396 return "ucontext.h";
2398 llvm_unreachable("unhandled error kind");
2401 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2402 unsigned ID, SourceLocation Loc) {
2403 DeclContext *Parent = Context.getTranslationUnitDecl();
2405 if (getLangOpts().CPlusPlus) {
2406 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2407 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2408 CLinkageDecl->setImplicit();
2409 Parent->addDecl(CLinkageDecl);
2410 Parent = CLinkageDecl;
2413 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2414 /*TInfo=*/nullptr, SC_Extern,
2415 getCurFPFeatures().isFPConstrained(),
2416 false, Type->isFunctionProtoType());
2417 New->setImplicit();
2418 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2420 // Create Decl objects for each parameter, adding them to the
2421 // FunctionDecl.
2422 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2423 SmallVector<ParmVarDecl *, 16> Params;
2424 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2425 ParmVarDecl *parm = ParmVarDecl::Create(
2426 Context, New, SourceLocation(), SourceLocation(), nullptr,
2427 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2428 parm->setScopeInfo(0, i);
2429 Params.push_back(parm);
2431 New->setParams(Params);
2434 AddKnownFunctionAttributes(New);
2435 return New;
2438 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2439 /// file scope. lazily create a decl for it. ForRedeclaration is true
2440 /// if we're creating this built-in in anticipation of redeclaring the
2441 /// built-in.
2442 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2443 Scope *S, bool ForRedeclaration,
2444 SourceLocation Loc) {
2445 LookupNecessaryTypesForBuiltin(S, ID);
2447 ASTContext::GetBuiltinTypeError Error;
2448 QualType R = Context.GetBuiltinType(ID, Error);
2449 if (Error) {
2450 if (!ForRedeclaration)
2451 return nullptr;
2453 // If we have a builtin without an associated type we should not emit a
2454 // warning when we were not able to find a type for it.
2455 if (Error == ASTContext::GE_Missing_type ||
2456 Context.BuiltinInfo.allowTypeMismatch(ID))
2457 return nullptr;
2459 // If we could not find a type for setjmp it is because the jmp_buf type was
2460 // not defined prior to the setjmp declaration.
2461 if (Error == ASTContext::GE_Missing_setjmp) {
2462 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2463 << Context.BuiltinInfo.getName(ID);
2464 return nullptr;
2467 // Generally, we emit a warning that the declaration requires the
2468 // appropriate header.
2469 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2470 << getHeaderName(Context.BuiltinInfo, ID, Error)
2471 << Context.BuiltinInfo.getName(ID);
2472 return nullptr;
2475 if (!ForRedeclaration &&
2476 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2477 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2478 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2479 : diag::ext_implicit_lib_function_decl)
2480 << Context.BuiltinInfo.getName(ID) << R;
2481 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2482 Diag(Loc, diag::note_include_header_or_declare)
2483 << Header << Context.BuiltinInfo.getName(ID);
2486 if (R.isNull())
2487 return nullptr;
2489 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2490 RegisterLocallyScopedExternCDecl(New, S);
2492 // TUScope is the translation-unit scope to insert this function into.
2493 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2494 // relate Scopes to DeclContexts, and probably eliminate CurContext
2495 // entirely, but we're not there yet.
2496 DeclContext *SavedContext = CurContext;
2497 CurContext = New->getDeclContext();
2498 PushOnScopeChains(New, TUScope);
2499 CurContext = SavedContext;
2500 return New;
2503 /// Typedef declarations don't have linkage, but they still denote the same
2504 /// entity if their types are the same.
2505 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2506 /// isSameEntity.
2507 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2508 TypedefNameDecl *Decl,
2509 LookupResult &Previous) {
2510 // This is only interesting when modules are enabled.
2511 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2512 return;
2514 // Empty sets are uninteresting.
2515 if (Previous.empty())
2516 return;
2518 LookupResult::Filter Filter = Previous.makeFilter();
2519 while (Filter.hasNext()) {
2520 NamedDecl *Old = Filter.next();
2522 // Non-hidden declarations are never ignored.
2523 if (S.isVisible(Old))
2524 continue;
2526 // Declarations of the same entity are not ignored, even if they have
2527 // different linkages.
2528 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2529 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2530 Decl->getUnderlyingType()))
2531 continue;
2533 // If both declarations give a tag declaration a typedef name for linkage
2534 // purposes, then they declare the same entity.
2535 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2536 Decl->getAnonDeclWithTypedefName())
2537 continue;
2540 Filter.erase();
2543 Filter.done();
2546 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2547 QualType OldType;
2548 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2549 OldType = OldTypedef->getUnderlyingType();
2550 else
2551 OldType = Context.getTypeDeclType(Old);
2552 QualType NewType = New->getUnderlyingType();
2554 if (NewType->isVariablyModifiedType()) {
2555 // Must not redefine a typedef with a variably-modified type.
2556 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2557 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2558 << Kind << NewType;
2559 if (Old->getLocation().isValid())
2560 notePreviousDefinition(Old, New->getLocation());
2561 New->setInvalidDecl();
2562 return true;
2565 if (OldType != NewType &&
2566 !OldType->isDependentType() &&
2567 !NewType->isDependentType() &&
2568 !Context.hasSameType(OldType, NewType)) {
2569 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2570 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2571 << Kind << NewType << OldType;
2572 if (Old->getLocation().isValid())
2573 notePreviousDefinition(Old, New->getLocation());
2574 New->setInvalidDecl();
2575 return true;
2577 return false;
2580 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2581 /// same name and scope as a previous declaration 'Old'. Figure out
2582 /// how to resolve this situation, merging decls or emitting
2583 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2585 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2586 LookupResult &OldDecls) {
2587 // If the new decl is known invalid already, don't bother doing any
2588 // merging checks.
2589 if (New->isInvalidDecl()) return;
2591 // Allow multiple definitions for ObjC built-in typedefs.
2592 // FIXME: Verify the underlying types are equivalent!
2593 if (getLangOpts().ObjC) {
2594 const IdentifierInfo *TypeID = New->getIdentifier();
2595 switch (TypeID->getLength()) {
2596 default: break;
2597 case 2:
2599 if (!TypeID->isStr("id"))
2600 break;
2601 QualType T = New->getUnderlyingType();
2602 if (!T->isPointerType())
2603 break;
2604 if (!T->isVoidPointerType()) {
2605 QualType PT = T->castAs<PointerType>()->getPointeeType();
2606 if (!PT->isStructureType())
2607 break;
2609 Context.setObjCIdRedefinitionType(T);
2610 // Install the built-in type for 'id', ignoring the current definition.
2611 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2612 return;
2614 case 5:
2615 if (!TypeID->isStr("Class"))
2616 break;
2617 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2618 // Install the built-in type for 'Class', ignoring the current definition.
2619 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2620 return;
2621 case 3:
2622 if (!TypeID->isStr("SEL"))
2623 break;
2624 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2625 // Install the built-in type for 'SEL', ignoring the current definition.
2626 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2627 return;
2629 // Fall through - the typedef name was not a builtin type.
2632 // Verify the old decl was also a type.
2633 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2634 if (!Old) {
2635 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2636 << New->getDeclName();
2638 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2639 if (OldD->getLocation().isValid())
2640 notePreviousDefinition(OldD, New->getLocation());
2642 return New->setInvalidDecl();
2645 // If the old declaration is invalid, just give up here.
2646 if (Old->isInvalidDecl())
2647 return New->setInvalidDecl();
2649 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2650 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2651 auto *NewTag = New->getAnonDeclWithTypedefName();
2652 NamedDecl *Hidden = nullptr;
2653 if (OldTag && NewTag &&
2654 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2655 !hasVisibleDefinition(OldTag, &Hidden)) {
2656 // There is a definition of this tag, but it is not visible. Use it
2657 // instead of our tag.
2658 New->setTypeForDecl(OldTD->getTypeForDecl());
2659 if (OldTD->isModed())
2660 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2661 OldTD->getUnderlyingType());
2662 else
2663 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2665 // Make the old tag definition visible.
2666 makeMergedDefinitionVisible(Hidden);
2668 // If this was an unscoped enumeration, yank all of its enumerators
2669 // out of the scope.
2670 if (isa<EnumDecl>(NewTag)) {
2671 Scope *EnumScope = getNonFieldDeclScope(S);
2672 for (auto *D : NewTag->decls()) {
2673 auto *ED = cast<EnumConstantDecl>(D);
2674 assert(EnumScope->isDeclScope(ED));
2675 EnumScope->RemoveDecl(ED);
2676 IdResolver.RemoveDecl(ED);
2677 ED->getLexicalDeclContext()->removeDecl(ED);
2683 // If the typedef types are not identical, reject them in all languages and
2684 // with any extensions enabled.
2685 if (isIncompatibleTypedef(Old, New))
2686 return;
2688 // The types match. Link up the redeclaration chain and merge attributes if
2689 // the old declaration was a typedef.
2690 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2691 New->setPreviousDecl(Typedef);
2692 mergeDeclAttributes(New, Old);
2695 if (getLangOpts().MicrosoftExt)
2696 return;
2698 if (getLangOpts().CPlusPlus) {
2699 // C++ [dcl.typedef]p2:
2700 // In a given non-class scope, a typedef specifier can be used to
2701 // redefine the name of any type declared in that scope to refer
2702 // to the type to which it already refers.
2703 if (!isa<CXXRecordDecl>(CurContext))
2704 return;
2706 // C++0x [dcl.typedef]p4:
2707 // In a given class scope, a typedef specifier can be used to redefine
2708 // any class-name declared in that scope that is not also a typedef-name
2709 // to refer to the type to which it already refers.
2711 // This wording came in via DR424, which was a correction to the
2712 // wording in DR56, which accidentally banned code like:
2714 // struct S {
2715 // typedef struct A { } A;
2716 // };
2718 // in the C++03 standard. We implement the C++0x semantics, which
2719 // allow the above but disallow
2721 // struct S {
2722 // typedef int I;
2723 // typedef int I;
2724 // };
2726 // since that was the intent of DR56.
2727 if (!isa<TypedefNameDecl>(Old))
2728 return;
2730 Diag(New->getLocation(), diag::err_redefinition)
2731 << New->getDeclName();
2732 notePreviousDefinition(Old, New->getLocation());
2733 return New->setInvalidDecl();
2736 // Modules always permit redefinition of typedefs, as does C11.
2737 if (getLangOpts().Modules || getLangOpts().C11)
2738 return;
2740 // If we have a redefinition of a typedef in C, emit a warning. This warning
2741 // is normally mapped to an error, but can be controlled with
2742 // -Wtypedef-redefinition. If either the original or the redefinition is
2743 // in a system header, don't emit this for compatibility with GCC.
2744 if (getDiagnostics().getSuppressSystemWarnings() &&
2745 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2746 (Old->isImplicit() ||
2747 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2748 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2749 return;
2751 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2752 << New->getDeclName();
2753 notePreviousDefinition(Old, New->getLocation());
2756 /// DeclhasAttr - returns true if decl Declaration already has the target
2757 /// attribute.
2758 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2759 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2760 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2761 for (const auto *i : D->attrs())
2762 if (i->getKind() == A->getKind()) {
2763 if (Ann) {
2764 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2765 return true;
2766 continue;
2768 // FIXME: Don't hardcode this check
2769 if (OA && isa<OwnershipAttr>(i))
2770 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2771 return true;
2774 return false;
2777 static bool isAttributeTargetADefinition(Decl *D) {
2778 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2779 return VD->isThisDeclarationADefinition();
2780 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2781 return TD->isCompleteDefinition() || TD->isBeingDefined();
2782 return true;
2785 /// Merge alignment attributes from \p Old to \p New, taking into account the
2786 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2788 /// \return \c true if any attributes were added to \p New.
2789 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2790 // Look for alignas attributes on Old, and pick out whichever attribute
2791 // specifies the strictest alignment requirement.
2792 AlignedAttr *OldAlignasAttr = nullptr;
2793 AlignedAttr *OldStrictestAlignAttr = nullptr;
2794 unsigned OldAlign = 0;
2795 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2796 // FIXME: We have no way of representing inherited dependent alignments
2797 // in a case like:
2798 // template<int A, int B> struct alignas(A) X;
2799 // template<int A, int B> struct alignas(B) X {};
2800 // For now, we just ignore any alignas attributes which are not on the
2801 // definition in such a case.
2802 if (I->isAlignmentDependent())
2803 return false;
2805 if (I->isAlignas())
2806 OldAlignasAttr = I;
2808 unsigned Align = I->getAlignment(S.Context);
2809 if (Align > OldAlign) {
2810 OldAlign = Align;
2811 OldStrictestAlignAttr = I;
2815 // Look for alignas attributes on New.
2816 AlignedAttr *NewAlignasAttr = nullptr;
2817 unsigned NewAlign = 0;
2818 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2819 if (I->isAlignmentDependent())
2820 return false;
2822 if (I->isAlignas())
2823 NewAlignasAttr = I;
2825 unsigned Align = I->getAlignment(S.Context);
2826 if (Align > NewAlign)
2827 NewAlign = Align;
2830 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2831 // Both declarations have 'alignas' attributes. We require them to match.
2832 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2833 // fall short. (If two declarations both have alignas, they must both match
2834 // every definition, and so must match each other if there is a definition.)
2836 // If either declaration only contains 'alignas(0)' specifiers, then it
2837 // specifies the natural alignment for the type.
2838 if (OldAlign == 0 || NewAlign == 0) {
2839 QualType Ty;
2840 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2841 Ty = VD->getType();
2842 else
2843 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2845 if (OldAlign == 0)
2846 OldAlign = S.Context.getTypeAlign(Ty);
2847 if (NewAlign == 0)
2848 NewAlign = S.Context.getTypeAlign(Ty);
2851 if (OldAlign != NewAlign) {
2852 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2853 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2854 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2855 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2859 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2860 // C++11 [dcl.align]p6:
2861 // if any declaration of an entity has an alignment-specifier,
2862 // every defining declaration of that entity shall specify an
2863 // equivalent alignment.
2864 // C11 6.7.5/7:
2865 // If the definition of an object does not have an alignment
2866 // specifier, any other declaration of that object shall also
2867 // have no alignment specifier.
2868 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2869 << OldAlignasAttr;
2870 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2871 << OldAlignasAttr;
2874 bool AnyAdded = false;
2876 // Ensure we have an attribute representing the strictest alignment.
2877 if (OldAlign > NewAlign) {
2878 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2879 Clone->setInherited(true);
2880 New->addAttr(Clone);
2881 AnyAdded = true;
2884 // Ensure we have an alignas attribute if the old declaration had one.
2885 if (OldAlignasAttr && !NewAlignasAttr &&
2886 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2887 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2888 Clone->setInherited(true);
2889 New->addAttr(Clone);
2890 AnyAdded = true;
2893 return AnyAdded;
2896 #define WANT_DECL_MERGE_LOGIC
2897 #include "clang/Sema/AttrParsedAttrImpl.inc"
2898 #undef WANT_DECL_MERGE_LOGIC
2900 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2901 const InheritableAttr *Attr,
2902 Sema::AvailabilityMergeKind AMK) {
2903 // Diagnose any mutual exclusions between the attribute that we want to add
2904 // and attributes that already exist on the declaration.
2905 if (!DiagnoseMutualExclusions(S, D, Attr))
2906 return false;
2908 // This function copies an attribute Attr from a previous declaration to the
2909 // new declaration D if the new declaration doesn't itself have that attribute
2910 // yet or if that attribute allows duplicates.
2911 // If you're adding a new attribute that requires logic different from
2912 // "use explicit attribute on decl if present, else use attribute from
2913 // previous decl", for example if the attribute needs to be consistent
2914 // between redeclarations, you need to call a custom merge function here.
2915 InheritableAttr *NewAttr = nullptr;
2916 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2917 NewAttr = S.mergeAvailabilityAttr(
2918 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2919 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2920 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2921 AA->getPriority());
2922 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2923 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2924 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2925 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2926 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2927 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2928 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2929 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2930 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2931 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2932 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2933 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2934 FA->getFirstArg());
2935 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2936 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2937 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2938 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2939 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2940 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2941 IA->getInheritanceModel());
2942 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2943 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2944 &S.Context.Idents.get(AA->getSpelling()));
2945 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2946 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2947 isa<CUDAGlobalAttr>(Attr))) {
2948 // CUDA target attributes are part of function signature for
2949 // overloading purposes and must not be merged.
2950 return false;
2951 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2952 NewAttr = S.mergeMinSizeAttr(D, *MA);
2953 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2954 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2955 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2956 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2957 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2958 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2959 else if (isa<AlignedAttr>(Attr))
2960 // AlignedAttrs are handled separately, because we need to handle all
2961 // such attributes on a declaration at the same time.
2962 NewAttr = nullptr;
2963 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2964 (AMK == Sema::AMK_Override ||
2965 AMK == Sema::AMK_ProtocolImplementation ||
2966 AMK == Sema::AMK_OptionalProtocolImplementation))
2967 NewAttr = nullptr;
2968 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2969 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2970 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2971 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2972 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2973 NewAttr = S.mergeImportNameAttr(D, *INA);
2974 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2975 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2976 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2977 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2978 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2979 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2980 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2981 NewAttr =
2982 S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2983 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2984 NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2985 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2986 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2988 if (NewAttr) {
2989 NewAttr->setInherited(true);
2990 D->addAttr(NewAttr);
2991 if (isa<MSInheritanceAttr>(NewAttr))
2992 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2993 return true;
2996 return false;
2999 static const NamedDecl *getDefinition(const Decl *D) {
3000 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
3001 return TD->getDefinition();
3002 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3003 const VarDecl *Def = VD->getDefinition();
3004 if (Def)
3005 return Def;
3006 return VD->getActingDefinition();
3008 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3009 const FunctionDecl *Def = nullptr;
3010 if (FD->isDefined(Def, true))
3011 return Def;
3013 return nullptr;
3016 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3017 for (const auto *Attribute : D->attrs())
3018 if (Attribute->getKind() == Kind)
3019 return true;
3020 return false;
3023 /// checkNewAttributesAfterDef - If we already have a definition, check that
3024 /// there are no new attributes in this declaration.
3025 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3026 if (!New->hasAttrs())
3027 return;
3029 const NamedDecl *Def = getDefinition(Old);
3030 if (!Def || Def == New)
3031 return;
3033 AttrVec &NewAttributes = New->getAttrs();
3034 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3035 const Attr *NewAttribute = NewAttributes[I];
3037 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3038 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3039 Sema::SkipBodyInfo SkipBody;
3040 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3042 // If we're skipping this definition, drop the "alias" attribute.
3043 if (SkipBody.ShouldSkip) {
3044 NewAttributes.erase(NewAttributes.begin() + I);
3045 --E;
3046 continue;
3048 } else {
3049 VarDecl *VD = cast<VarDecl>(New);
3050 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3051 VarDecl::TentativeDefinition
3052 ? diag::err_alias_after_tentative
3053 : diag::err_redefinition;
3054 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3055 if (Diag == diag::err_redefinition)
3056 S.notePreviousDefinition(Def, VD->getLocation());
3057 else
3058 S.Diag(Def->getLocation(), diag::note_previous_definition);
3059 VD->setInvalidDecl();
3061 ++I;
3062 continue;
3065 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3066 // Tentative definitions are only interesting for the alias check above.
3067 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3068 ++I;
3069 continue;
3073 if (hasAttribute(Def, NewAttribute->getKind())) {
3074 ++I;
3075 continue; // regular attr merging will take care of validating this.
3078 if (isa<C11NoReturnAttr>(NewAttribute)) {
3079 // C's _Noreturn is allowed to be added to a function after it is defined.
3080 ++I;
3081 continue;
3082 } else if (isa<UuidAttr>(NewAttribute)) {
3083 // msvc will allow a subsequent definition to add an uuid to a class
3084 ++I;
3085 continue;
3086 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3087 if (AA->isAlignas()) {
3088 // C++11 [dcl.align]p6:
3089 // if any declaration of an entity has an alignment-specifier,
3090 // every defining declaration of that entity shall specify an
3091 // equivalent alignment.
3092 // C11 6.7.5/7:
3093 // If the definition of an object does not have an alignment
3094 // specifier, any other declaration of that object shall also
3095 // have no alignment specifier.
3096 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3097 << AA;
3098 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3099 << AA;
3100 NewAttributes.erase(NewAttributes.begin() + I);
3101 --E;
3102 continue;
3104 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3105 // If there is a C definition followed by a redeclaration with this
3106 // attribute then there are two different definitions. In C++, prefer the
3107 // standard diagnostics.
3108 if (!S.getLangOpts().CPlusPlus) {
3109 S.Diag(NewAttribute->getLocation(),
3110 diag::err_loader_uninitialized_redeclaration);
3111 S.Diag(Def->getLocation(), diag::note_previous_definition);
3112 NewAttributes.erase(NewAttributes.begin() + I);
3113 --E;
3114 continue;
3116 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3117 cast<VarDecl>(New)->isInline() &&
3118 !cast<VarDecl>(New)->isInlineSpecified()) {
3119 // Don't warn about applying selectany to implicitly inline variables.
3120 // Older compilers and language modes would require the use of selectany
3121 // to make such variables inline, and it would have no effect if we
3122 // honored it.
3123 ++I;
3124 continue;
3125 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3126 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3127 // declarations after definitions.
3128 ++I;
3129 continue;
3132 S.Diag(NewAttribute->getLocation(),
3133 diag::warn_attribute_precede_definition);
3134 S.Diag(Def->getLocation(), diag::note_previous_definition);
3135 NewAttributes.erase(NewAttributes.begin() + I);
3136 --E;
3140 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3141 const ConstInitAttr *CIAttr,
3142 bool AttrBeforeInit) {
3143 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3145 // Figure out a good way to write this specifier on the old declaration.
3146 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3147 // enough of the attribute list spelling information to extract that without
3148 // heroics.
3149 std::string SuitableSpelling;
3150 if (S.getLangOpts().CPlusPlus20)
3151 SuitableSpelling = std::string(
3152 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3153 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3154 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3155 InsertLoc, {tok::l_square, tok::l_square,
3156 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3157 S.PP.getIdentifierInfo("require_constant_initialization"),
3158 tok::r_square, tok::r_square}));
3159 if (SuitableSpelling.empty())
3160 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3161 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3162 S.PP.getIdentifierInfo("require_constant_initialization"),
3163 tok::r_paren, tok::r_paren}));
3164 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3165 SuitableSpelling = "constinit";
3166 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3167 SuitableSpelling = "[[clang::require_constant_initialization]]";
3168 if (SuitableSpelling.empty())
3169 SuitableSpelling = "__attribute__((require_constant_initialization))";
3170 SuitableSpelling += " ";
3172 if (AttrBeforeInit) {
3173 // extern constinit int a;
3174 // int a = 0; // error (missing 'constinit'), accepted as extension
3175 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3176 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3177 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3178 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3179 } else {
3180 // int a = 0;
3181 // constinit extern int a; // error (missing 'constinit')
3182 S.Diag(CIAttr->getLocation(),
3183 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3184 : diag::warn_require_const_init_added_too_late)
3185 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3186 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3187 << CIAttr->isConstinit()
3188 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3192 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3193 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3194 AvailabilityMergeKind AMK) {
3195 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3196 UsedAttr *NewAttr = OldAttr->clone(Context);
3197 NewAttr->setInherited(true);
3198 New->addAttr(NewAttr);
3200 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3201 RetainAttr *NewAttr = OldAttr->clone(Context);
3202 NewAttr->setInherited(true);
3203 New->addAttr(NewAttr);
3206 if (!Old->hasAttrs() && !New->hasAttrs())
3207 return;
3209 // [dcl.constinit]p1:
3210 // If the [constinit] specifier is applied to any declaration of a
3211 // variable, it shall be applied to the initializing declaration.
3212 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3213 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3214 if (bool(OldConstInit) != bool(NewConstInit)) {
3215 const auto *OldVD = cast<VarDecl>(Old);
3216 auto *NewVD = cast<VarDecl>(New);
3218 // Find the initializing declaration. Note that we might not have linked
3219 // the new declaration into the redeclaration chain yet.
3220 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3221 if (!InitDecl &&
3222 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3223 InitDecl = NewVD;
3225 if (InitDecl == NewVD) {
3226 // This is the initializing declaration. If it would inherit 'constinit',
3227 // that's ill-formed. (Note that we do not apply this to the attribute
3228 // form).
3229 if (OldConstInit && OldConstInit->isConstinit())
3230 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3231 /*AttrBeforeInit=*/true);
3232 } else if (NewConstInit) {
3233 // This is the first time we've been told that this declaration should
3234 // have a constant initializer. If we already saw the initializing
3235 // declaration, this is too late.
3236 if (InitDecl && InitDecl != NewVD) {
3237 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3238 /*AttrBeforeInit=*/false);
3239 NewVD->dropAttr<ConstInitAttr>();
3244 // Attributes declared post-definition are currently ignored.
3245 checkNewAttributesAfterDef(*this, New, Old);
3247 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3248 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3249 if (!OldA->isEquivalent(NewA)) {
3250 // This redeclaration changes __asm__ label.
3251 Diag(New->getLocation(), diag::err_different_asm_label);
3252 Diag(OldA->getLocation(), diag::note_previous_declaration);
3254 } else if (Old->isUsed()) {
3255 // This redeclaration adds an __asm__ label to a declaration that has
3256 // already been ODR-used.
3257 Diag(New->getLocation(), diag::err_late_asm_label_name)
3258 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3262 // Re-declaration cannot add abi_tag's.
3263 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3264 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3265 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3266 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3267 Diag(NewAbiTagAttr->getLocation(),
3268 diag::err_new_abi_tag_on_redeclaration)
3269 << NewTag;
3270 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3273 } else {
3274 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3275 Diag(Old->getLocation(), diag::note_previous_declaration);
3279 // This redeclaration adds a section attribute.
3280 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3281 if (auto *VD = dyn_cast<VarDecl>(New)) {
3282 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3283 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3284 Diag(Old->getLocation(), diag::note_previous_declaration);
3289 // Redeclaration adds code-seg attribute.
3290 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3291 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3292 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3293 Diag(New->getLocation(), diag::warn_mismatched_section)
3294 << 0 /*codeseg*/;
3295 Diag(Old->getLocation(), diag::note_previous_declaration);
3298 if (!Old->hasAttrs())
3299 return;
3301 bool foundAny = New->hasAttrs();
3303 // Ensure that any moving of objects within the allocated map is done before
3304 // we process them.
3305 if (!foundAny) New->setAttrs(AttrVec());
3307 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3308 // Ignore deprecated/unavailable/availability attributes if requested.
3309 AvailabilityMergeKind LocalAMK = AMK_None;
3310 if (isa<DeprecatedAttr>(I) ||
3311 isa<UnavailableAttr>(I) ||
3312 isa<AvailabilityAttr>(I)) {
3313 switch (AMK) {
3314 case AMK_None:
3315 continue;
3317 case AMK_Redeclaration:
3318 case AMK_Override:
3319 case AMK_ProtocolImplementation:
3320 case AMK_OptionalProtocolImplementation:
3321 LocalAMK = AMK;
3322 break;
3326 // Already handled.
3327 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3328 continue;
3330 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3331 foundAny = true;
3334 if (mergeAlignedAttrs(*this, New, Old))
3335 foundAny = true;
3337 if (!foundAny) New->dropAttrs();
3340 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3341 /// to the new one.
3342 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3343 const ParmVarDecl *oldDecl,
3344 Sema &S) {
3345 // C++11 [dcl.attr.depend]p2:
3346 // The first declaration of a function shall specify the
3347 // carries_dependency attribute for its declarator-id if any declaration
3348 // of the function specifies the carries_dependency attribute.
3349 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3350 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3351 S.Diag(CDA->getLocation(),
3352 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3353 // Find the first declaration of the parameter.
3354 // FIXME: Should we build redeclaration chains for function parameters?
3355 const FunctionDecl *FirstFD =
3356 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3357 const ParmVarDecl *FirstVD =
3358 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3359 S.Diag(FirstVD->getLocation(),
3360 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3363 if (!oldDecl->hasAttrs())
3364 return;
3366 bool foundAny = newDecl->hasAttrs();
3368 // Ensure that any moving of objects within the allocated map is
3369 // done before we process them.
3370 if (!foundAny) newDecl->setAttrs(AttrVec());
3372 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3373 if (!DeclHasAttr(newDecl, I)) {
3374 InheritableAttr *newAttr =
3375 cast<InheritableParamAttr>(I->clone(S.Context));
3376 newAttr->setInherited(true);
3377 newDecl->addAttr(newAttr);
3378 foundAny = true;
3382 if (!foundAny) newDecl->dropAttrs();
3385 static bool EquivalentArrayTypes(QualType Old, QualType New,
3386 const ASTContext &Ctx) {
3388 auto NoSizeInfo = [&Ctx](QualType Ty) {
3389 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3390 return true;
3391 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3392 return VAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star;
3393 return false;
3396 // `type[]` is equivalent to `type *` and `type[*]`.
3397 if (NoSizeInfo(Old) && NoSizeInfo(New))
3398 return true;
3400 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3401 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3402 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3403 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3404 if ((OldVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star) ^
3405 (NewVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star))
3406 return false;
3407 return true;
3410 // Only compare size, ignore Size modifiers and CVR.
3411 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3412 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3413 Ctx.getAsConstantArrayType(New)->getSize();
3416 // Don't try to compare dependent sized array
3417 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3418 return true;
3421 return Old == New;
3424 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3425 const ParmVarDecl *OldParam,
3426 Sema &S) {
3427 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3428 if (auto Newnullability = NewParam->getType()->getNullability()) {
3429 if (*Oldnullability != *Newnullability) {
3430 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3431 << DiagNullabilityKind(
3432 *Newnullability,
3433 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3434 != 0))
3435 << DiagNullabilityKind(
3436 *Oldnullability,
3437 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3438 != 0));
3439 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3441 } else {
3442 QualType NewT = NewParam->getType();
3443 NewT = S.Context.getAttributedType(
3444 AttributedType::getNullabilityAttrKind(*Oldnullability),
3445 NewT, NewT);
3446 NewParam->setType(NewT);
3449 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3450 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3451 if (OldParamDT && NewParamDT &&
3452 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3453 QualType OldParamOT = OldParamDT->getOriginalType();
3454 QualType NewParamOT = NewParamDT->getOriginalType();
3455 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3456 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3457 << NewParam << NewParamOT;
3458 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3459 << OldParamOT;
3464 namespace {
3466 /// Used in MergeFunctionDecl to keep track of function parameters in
3467 /// C.
3468 struct GNUCompatibleParamWarning {
3469 ParmVarDecl *OldParm;
3470 ParmVarDecl *NewParm;
3471 QualType PromotedType;
3474 } // end anonymous namespace
3476 // Determine whether the previous declaration was a definition, implicit
3477 // declaration, or a declaration.
3478 template <typename T>
3479 static std::pair<diag::kind, SourceLocation>
3480 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3481 diag::kind PrevDiag;
3482 SourceLocation OldLocation = Old->getLocation();
3483 if (Old->isThisDeclarationADefinition())
3484 PrevDiag = diag::note_previous_definition;
3485 else if (Old->isImplicit()) {
3486 PrevDiag = diag::note_previous_implicit_declaration;
3487 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3488 if (FD->getBuiltinID())
3489 PrevDiag = diag::note_previous_builtin_declaration;
3491 if (OldLocation.isInvalid())
3492 OldLocation = New->getLocation();
3493 } else
3494 PrevDiag = diag::note_previous_declaration;
3495 return std::make_pair(PrevDiag, OldLocation);
3498 /// canRedefineFunction - checks if a function can be redefined. Currently,
3499 /// only extern inline functions can be redefined, and even then only in
3500 /// GNU89 mode.
3501 static bool canRedefineFunction(const FunctionDecl *FD,
3502 const LangOptions& LangOpts) {
3503 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3504 !LangOpts.CPlusPlus &&
3505 FD->isInlineSpecified() &&
3506 FD->getStorageClass() == SC_Extern);
3509 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3510 const AttributedType *AT = T->getAs<AttributedType>();
3511 while (AT && !AT->isCallingConv())
3512 AT = AT->getModifiedType()->getAs<AttributedType>();
3513 return AT;
3516 template <typename T>
3517 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3518 const DeclContext *DC = Old->getDeclContext();
3519 if (DC->isRecord())
3520 return false;
3522 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3523 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3524 return true;
3525 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3526 return true;
3527 return false;
3530 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3531 static bool isExternC(VarTemplateDecl *) { return false; }
3532 static bool isExternC(FunctionTemplateDecl *) { return false; }
3534 /// Check whether a redeclaration of an entity introduced by a
3535 /// using-declaration is valid, given that we know it's not an overload
3536 /// (nor a hidden tag declaration).
3537 template<typename ExpectedDecl>
3538 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3539 ExpectedDecl *New) {
3540 // C++11 [basic.scope.declarative]p4:
3541 // Given a set of declarations in a single declarative region, each of
3542 // which specifies the same unqualified name,
3543 // -- they shall all refer to the same entity, or all refer to functions
3544 // and function templates; or
3545 // -- exactly one declaration shall declare a class name or enumeration
3546 // name that is not a typedef name and the other declarations shall all
3547 // refer to the same variable or enumerator, or all refer to functions
3548 // and function templates; in this case the class name or enumeration
3549 // name is hidden (3.3.10).
3551 // C++11 [namespace.udecl]p14:
3552 // If a function declaration in namespace scope or block scope has the
3553 // same name and the same parameter-type-list as a function introduced
3554 // by a using-declaration, and the declarations do not declare the same
3555 // function, the program is ill-formed.
3557 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3558 if (Old &&
3559 !Old->getDeclContext()->getRedeclContext()->Equals(
3560 New->getDeclContext()->getRedeclContext()) &&
3561 !(isExternC(Old) && isExternC(New)))
3562 Old = nullptr;
3564 if (!Old) {
3565 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3566 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3567 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3568 return true;
3570 return false;
3573 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3574 const FunctionDecl *B) {
3575 assert(A->getNumParams() == B->getNumParams());
3577 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3578 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3579 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3580 if (AttrA == AttrB)
3581 return true;
3582 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3583 AttrA->isDynamic() == AttrB->isDynamic();
3586 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3589 /// If necessary, adjust the semantic declaration context for a qualified
3590 /// declaration to name the correct inline namespace within the qualifier.
3591 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3592 DeclaratorDecl *OldD) {
3593 // The only case where we need to update the DeclContext is when
3594 // redeclaration lookup for a qualified name finds a declaration
3595 // in an inline namespace within the context named by the qualifier:
3597 // inline namespace N { int f(); }
3598 // int ::f(); // Sema DC needs adjusting from :: to N::.
3600 // For unqualified declarations, the semantic context *can* change
3601 // along the redeclaration chain (for local extern declarations,
3602 // extern "C" declarations, and friend declarations in particular).
3603 if (!NewD->getQualifier())
3604 return;
3606 // NewD is probably already in the right context.
3607 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3608 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3609 if (NamedDC->Equals(SemaDC))
3610 return;
3612 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3613 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3614 "unexpected context for redeclaration");
3616 auto *LexDC = NewD->getLexicalDeclContext();
3617 auto FixSemaDC = [=](NamedDecl *D) {
3618 if (!D)
3619 return;
3620 D->setDeclContext(SemaDC);
3621 D->setLexicalDeclContext(LexDC);
3624 FixSemaDC(NewD);
3625 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3626 FixSemaDC(FD->getDescribedFunctionTemplate());
3627 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3628 FixSemaDC(VD->getDescribedVarTemplate());
3631 /// MergeFunctionDecl - We just parsed a function 'New' from
3632 /// declarator D which has the same name and scope as a previous
3633 /// declaration 'Old'. Figure out how to resolve this situation,
3634 /// merging decls or emitting diagnostics as appropriate.
3636 /// In C++, New and Old must be declarations that are not
3637 /// overloaded. Use IsOverload to determine whether New and Old are
3638 /// overloaded, and to select the Old declaration that New should be
3639 /// merged with.
3641 /// Returns true if there was an error, false otherwise.
3642 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3643 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3644 // Verify the old decl was also a function.
3645 FunctionDecl *Old = OldD->getAsFunction();
3646 if (!Old) {
3647 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3648 if (New->getFriendObjectKind()) {
3649 Diag(New->getLocation(), diag::err_using_decl_friend);
3650 Diag(Shadow->getTargetDecl()->getLocation(),
3651 diag::note_using_decl_target);
3652 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3653 << 0;
3654 return true;
3657 // Check whether the two declarations might declare the same function or
3658 // function template.
3659 if (FunctionTemplateDecl *NewTemplate =
3660 New->getDescribedFunctionTemplate()) {
3661 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3662 NewTemplate))
3663 return true;
3664 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3665 ->getAsFunction();
3666 } else {
3667 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3668 return true;
3669 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3671 } else {
3672 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3673 << New->getDeclName();
3674 notePreviousDefinition(OldD, New->getLocation());
3675 return true;
3679 // If the old declaration was found in an inline namespace and the new
3680 // declaration was qualified, update the DeclContext to match.
3681 adjustDeclContextForDeclaratorDecl(New, Old);
3683 // If the old declaration is invalid, just give up here.
3684 if (Old->isInvalidDecl())
3685 return true;
3687 // Disallow redeclaration of some builtins.
3688 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3689 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3690 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3691 << Old << Old->getType();
3692 return true;
3695 diag::kind PrevDiag;
3696 SourceLocation OldLocation;
3697 std::tie(PrevDiag, OldLocation) =
3698 getNoteDiagForInvalidRedeclaration(Old, New);
3700 // Don't complain about this if we're in GNU89 mode and the old function
3701 // is an extern inline function.
3702 // Don't complain about specializations. They are not supposed to have
3703 // storage classes.
3704 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3705 New->getStorageClass() == SC_Static &&
3706 Old->hasExternalFormalLinkage() &&
3707 !New->getTemplateSpecializationInfo() &&
3708 !canRedefineFunction(Old, getLangOpts())) {
3709 if (getLangOpts().MicrosoftExt) {
3710 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3711 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3712 } else {
3713 Diag(New->getLocation(), diag::err_static_non_static) << New;
3714 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3715 return true;
3719 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3720 if (!Old->hasAttr<InternalLinkageAttr>()) {
3721 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3722 << ILA;
3723 Diag(Old->getLocation(), diag::note_previous_declaration);
3724 New->dropAttr<InternalLinkageAttr>();
3727 if (auto *EA = New->getAttr<ErrorAttr>()) {
3728 if (!Old->hasAttr<ErrorAttr>()) {
3729 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3730 Diag(Old->getLocation(), diag::note_previous_declaration);
3731 New->dropAttr<ErrorAttr>();
3735 if (CheckRedeclarationInModule(New, Old))
3736 return true;
3738 if (!getLangOpts().CPlusPlus) {
3739 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3740 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3741 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3742 << New << OldOvl;
3744 // Try our best to find a decl that actually has the overloadable
3745 // attribute for the note. In most cases (e.g. programs with only one
3746 // broken declaration/definition), this won't matter.
3748 // FIXME: We could do this if we juggled some extra state in
3749 // OverloadableAttr, rather than just removing it.
3750 const Decl *DiagOld = Old;
3751 if (OldOvl) {
3752 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3753 const auto *A = D->getAttr<OverloadableAttr>();
3754 return A && !A->isImplicit();
3756 // If we've implicitly added *all* of the overloadable attrs to this
3757 // chain, emitting a "previous redecl" note is pointless.
3758 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3761 if (DiagOld)
3762 Diag(DiagOld->getLocation(),
3763 diag::note_attribute_overloadable_prev_overload)
3764 << OldOvl;
3766 if (OldOvl)
3767 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3768 else
3769 New->dropAttr<OverloadableAttr>();
3773 // It is not permitted to redeclare an SME function with different SME
3774 // attributes.
3775 if (IsInvalidSMECallConversion(Old->getType(), New->getType(),
3776 AArch64SMECallConversionKind::MatchExactly)) {
3777 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3778 << New->getType() << Old->getType();
3779 Diag(OldLocation, diag::note_previous_declaration);
3780 return true;
3783 // If a function is first declared with a calling convention, but is later
3784 // declared or defined without one, all following decls assume the calling
3785 // convention of the first.
3787 // It's OK if a function is first declared without a calling convention,
3788 // but is later declared or defined with the default calling convention.
3790 // To test if either decl has an explicit calling convention, we look for
3791 // AttributedType sugar nodes on the type as written. If they are missing or
3792 // were canonicalized away, we assume the calling convention was implicit.
3794 // Note also that we DO NOT return at this point, because we still have
3795 // other tests to run.
3796 QualType OldQType = Context.getCanonicalType(Old->getType());
3797 QualType NewQType = Context.getCanonicalType(New->getType());
3798 const FunctionType *OldType = cast<FunctionType>(OldQType);
3799 const FunctionType *NewType = cast<FunctionType>(NewQType);
3800 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3801 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3802 bool RequiresAdjustment = false;
3804 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3805 FunctionDecl *First = Old->getFirstDecl();
3806 const FunctionType *FT =
3807 First->getType().getCanonicalType()->castAs<FunctionType>();
3808 FunctionType::ExtInfo FI = FT->getExtInfo();
3809 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3810 if (!NewCCExplicit) {
3811 // Inherit the CC from the previous declaration if it was specified
3812 // there but not here.
3813 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3814 RequiresAdjustment = true;
3815 } else if (Old->getBuiltinID()) {
3816 // Builtin attribute isn't propagated to the new one yet at this point,
3817 // so we check if the old one is a builtin.
3819 // Calling Conventions on a Builtin aren't really useful and setting a
3820 // default calling convention and cdecl'ing some builtin redeclarations is
3821 // common, so warn and ignore the calling convention on the redeclaration.
3822 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3823 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3824 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3825 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3826 RequiresAdjustment = true;
3827 } else {
3828 // Calling conventions aren't compatible, so complain.
3829 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3830 Diag(New->getLocation(), diag::err_cconv_change)
3831 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3832 << !FirstCCExplicit
3833 << (!FirstCCExplicit ? "" :
3834 FunctionType::getNameForCallConv(FI.getCC()));
3836 // Put the note on the first decl, since it is the one that matters.
3837 Diag(First->getLocation(), diag::note_previous_declaration);
3838 return true;
3842 // FIXME: diagnose the other way around?
3843 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3844 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3845 RequiresAdjustment = true;
3848 // Merge regparm attribute.
3849 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3850 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3851 if (NewTypeInfo.getHasRegParm()) {
3852 Diag(New->getLocation(), diag::err_regparm_mismatch)
3853 << NewType->getRegParmType()
3854 << OldType->getRegParmType();
3855 Diag(OldLocation, diag::note_previous_declaration);
3856 return true;
3859 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3860 RequiresAdjustment = true;
3863 // Merge ns_returns_retained attribute.
3864 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3865 if (NewTypeInfo.getProducesResult()) {
3866 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3867 << "'ns_returns_retained'";
3868 Diag(OldLocation, diag::note_previous_declaration);
3869 return true;
3872 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3873 RequiresAdjustment = true;
3876 if (OldTypeInfo.getNoCallerSavedRegs() !=
3877 NewTypeInfo.getNoCallerSavedRegs()) {
3878 if (NewTypeInfo.getNoCallerSavedRegs()) {
3879 AnyX86NoCallerSavedRegistersAttr *Attr =
3880 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3881 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3882 Diag(OldLocation, diag::note_previous_declaration);
3883 return true;
3886 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3887 RequiresAdjustment = true;
3890 if (RequiresAdjustment) {
3891 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3892 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3893 New->setType(QualType(AdjustedType, 0));
3894 NewQType = Context.getCanonicalType(New->getType());
3897 // If this redeclaration makes the function inline, we may need to add it to
3898 // UndefinedButUsed.
3899 if (!Old->isInlined() && New->isInlined() &&
3900 !New->hasAttr<GNUInlineAttr>() &&
3901 !getLangOpts().GNUInline &&
3902 Old->isUsed(false) &&
3903 !Old->isDefined() && !New->isThisDeclarationADefinition())
3904 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3905 SourceLocation()));
3907 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3908 // about it.
3909 if (New->hasAttr<GNUInlineAttr>() &&
3910 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3911 UndefinedButUsed.erase(Old->getCanonicalDecl());
3914 // If pass_object_size params don't match up perfectly, this isn't a valid
3915 // redeclaration.
3916 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3917 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3918 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3919 << New->getDeclName();
3920 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3921 return true;
3924 if (getLangOpts().CPlusPlus) {
3925 // C++1z [over.load]p2
3926 // Certain function declarations cannot be overloaded:
3927 // -- Function declarations that differ only in the return type,
3928 // the exception specification, or both cannot be overloaded.
3930 // Check the exception specifications match. This may recompute the type of
3931 // both Old and New if it resolved exception specifications, so grab the
3932 // types again after this. Because this updates the type, we do this before
3933 // any of the other checks below, which may update the "de facto" NewQType
3934 // but do not necessarily update the type of New.
3935 if (CheckEquivalentExceptionSpec(Old, New))
3936 return true;
3937 OldQType = Context.getCanonicalType(Old->getType());
3938 NewQType = Context.getCanonicalType(New->getType());
3940 // Go back to the type source info to compare the declared return types,
3941 // per C++1y [dcl.type.auto]p13:
3942 // Redeclarations or specializations of a function or function template
3943 // with a declared return type that uses a placeholder type shall also
3944 // use that placeholder, not a deduced type.
3945 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3946 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3947 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3948 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3949 OldDeclaredReturnType)) {
3950 QualType ResQT;
3951 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3952 OldDeclaredReturnType->isObjCObjectPointerType())
3953 // FIXME: This does the wrong thing for a deduced return type.
3954 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3955 if (ResQT.isNull()) {
3956 if (New->isCXXClassMember() && New->isOutOfLine())
3957 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3958 << New << New->getReturnTypeSourceRange();
3959 else
3960 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3961 << New->getReturnTypeSourceRange();
3962 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3963 << Old->getReturnTypeSourceRange();
3964 return true;
3966 else
3967 NewQType = ResQT;
3970 QualType OldReturnType = OldType->getReturnType();
3971 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3972 if (OldReturnType != NewReturnType) {
3973 // If this function has a deduced return type and has already been
3974 // defined, copy the deduced value from the old declaration.
3975 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3976 if (OldAT && OldAT->isDeduced()) {
3977 QualType DT = OldAT->getDeducedType();
3978 if (DT.isNull()) {
3979 New->setType(SubstAutoTypeDependent(New->getType()));
3980 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3981 } else {
3982 New->setType(SubstAutoType(New->getType(), DT));
3983 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3988 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3989 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3990 if (OldMethod && NewMethod) {
3991 // Preserve triviality.
3992 NewMethod->setTrivial(OldMethod->isTrivial());
3994 // MSVC allows explicit template specialization at class scope:
3995 // 2 CXXMethodDecls referring to the same function will be injected.
3996 // We don't want a redeclaration error.
3997 bool IsClassScopeExplicitSpecialization =
3998 OldMethod->isFunctionTemplateSpecialization() &&
3999 NewMethod->isFunctionTemplateSpecialization();
4000 bool isFriend = NewMethod->getFriendObjectKind();
4002 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4003 !IsClassScopeExplicitSpecialization) {
4004 // -- Member function declarations with the same name and the
4005 // same parameter types cannot be overloaded if any of them
4006 // is a static member function declaration.
4007 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4008 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4009 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4010 return true;
4013 // C++ [class.mem]p1:
4014 // [...] A member shall not be declared twice in the
4015 // member-specification, except that a nested class or member
4016 // class template can be declared and then later defined.
4017 if (!inTemplateInstantiation()) {
4018 unsigned NewDiag;
4019 if (isa<CXXConstructorDecl>(OldMethod))
4020 NewDiag = diag::err_constructor_redeclared;
4021 else if (isa<CXXDestructorDecl>(NewMethod))
4022 NewDiag = diag::err_destructor_redeclared;
4023 else if (isa<CXXConversionDecl>(NewMethod))
4024 NewDiag = diag::err_conv_function_redeclared;
4025 else
4026 NewDiag = diag::err_member_redeclared;
4028 Diag(New->getLocation(), NewDiag);
4029 } else {
4030 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4031 << New << New->getType();
4033 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4034 return true;
4036 // Complain if this is an explicit declaration of a special
4037 // member that was initially declared implicitly.
4039 // As an exception, it's okay to befriend such methods in order
4040 // to permit the implicit constructor/destructor/operator calls.
4041 } else if (OldMethod->isImplicit()) {
4042 if (isFriend) {
4043 NewMethod->setImplicit();
4044 } else {
4045 Diag(NewMethod->getLocation(),
4046 diag::err_definition_of_implicitly_declared_member)
4047 << New << getSpecialMember(OldMethod);
4048 return true;
4050 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4051 Diag(NewMethod->getLocation(),
4052 diag::err_definition_of_explicitly_defaulted_member)
4053 << getSpecialMember(OldMethod);
4054 return true;
4058 // C++11 [dcl.attr.noreturn]p1:
4059 // The first declaration of a function shall specify the noreturn
4060 // attribute if any declaration of that function specifies the noreturn
4061 // attribute.
4062 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4063 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4064 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4065 << NRA;
4066 Diag(Old->getLocation(), diag::note_previous_declaration);
4069 // C++11 [dcl.attr.depend]p2:
4070 // The first declaration of a function shall specify the
4071 // carries_dependency attribute for its declarator-id if any declaration
4072 // of the function specifies the carries_dependency attribute.
4073 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4074 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4075 Diag(CDA->getLocation(),
4076 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4077 Diag(Old->getFirstDecl()->getLocation(),
4078 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4081 // (C++98 8.3.5p3):
4082 // All declarations for a function shall agree exactly in both the
4083 // return type and the parameter-type-list.
4084 // We also want to respect all the extended bits except noreturn.
4086 // noreturn should now match unless the old type info didn't have it.
4087 QualType OldQTypeForComparison = OldQType;
4088 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4089 auto *OldType = OldQType->castAs<FunctionProtoType>();
4090 const FunctionType *OldTypeForComparison
4091 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4092 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4093 assert(OldQTypeForComparison.isCanonical());
4096 if (haveIncompatibleLanguageLinkages(Old, New)) {
4097 // As a special case, retain the language linkage from previous
4098 // declarations of a friend function as an extension.
4100 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4101 // and is useful because there's otherwise no way to specify language
4102 // linkage within class scope.
4104 // Check cautiously as the friend object kind isn't yet complete.
4105 if (New->getFriendObjectKind() != Decl::FOK_None) {
4106 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4107 Diag(OldLocation, PrevDiag);
4108 } else {
4109 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4110 Diag(OldLocation, PrevDiag);
4111 return true;
4115 // If the function types are compatible, merge the declarations. Ignore the
4116 // exception specifier because it was already checked above in
4117 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4118 // about incompatible types under -fms-compatibility.
4119 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4120 NewQType))
4121 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4123 // If the types are imprecise (due to dependent constructs in friends or
4124 // local extern declarations), it's OK if they differ. We'll check again
4125 // during instantiation.
4126 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4127 return false;
4129 // Fall through for conflicting redeclarations and redefinitions.
4132 // C: Function types need to be compatible, not identical. This handles
4133 // duplicate function decls like "void f(int); void f(enum X);" properly.
4134 if (!getLangOpts().CPlusPlus) {
4135 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4136 // type is specified by a function definition that contains a (possibly
4137 // empty) identifier list, both shall agree in the number of parameters
4138 // and the type of each parameter shall be compatible with the type that
4139 // results from the application of default argument promotions to the
4140 // type of the corresponding identifier. ...
4141 // This cannot be handled by ASTContext::typesAreCompatible() because that
4142 // doesn't know whether the function type is for a definition or not when
4143 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4144 // we need to cover here is that the number of arguments agree as the
4145 // default argument promotion rules were already checked by
4146 // ASTContext::typesAreCompatible().
4147 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4148 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4149 if (Old->hasInheritedPrototype())
4150 Old = Old->getCanonicalDecl();
4151 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4152 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4153 return true;
4156 // If we are merging two functions where only one of them has a prototype,
4157 // we may have enough information to decide to issue a diagnostic that the
4158 // function without a protoype will change behavior in C23. This handles
4159 // cases like:
4160 // void i(); void i(int j);
4161 // void i(int j); void i();
4162 // void i(); void i(int j) {}
4163 // See ActOnFinishFunctionBody() for other cases of the behavior change
4164 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4165 // type without a prototype.
4166 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4167 !New->isImplicit() && !Old->isImplicit()) {
4168 const FunctionDecl *WithProto, *WithoutProto;
4169 if (New->hasWrittenPrototype()) {
4170 WithProto = New;
4171 WithoutProto = Old;
4172 } else {
4173 WithProto = Old;
4174 WithoutProto = New;
4177 if (WithProto->getNumParams() != 0) {
4178 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4179 // The one without the prototype will be changing behavior in C23, so
4180 // warn about that one so long as it's a user-visible declaration.
4181 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4182 if (WithoutProto == New)
4183 IsWithoutProtoADef = NewDeclIsDefn;
4184 else
4185 IsWithProtoADef = NewDeclIsDefn;
4186 Diag(WithoutProto->getLocation(),
4187 diag::warn_non_prototype_changes_behavior)
4188 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4189 << (WithoutProto == Old) << IsWithProtoADef;
4191 // The reason the one without the prototype will be changing behavior
4192 // is because of the one with the prototype, so note that so long as
4193 // it's a user-visible declaration. There is one exception to this:
4194 // when the new declaration is a definition without a prototype, the
4195 // old declaration with a prototype is not the cause of the issue,
4196 // and that does not need to be noted because the one with a
4197 // prototype will not change behavior in C23.
4198 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4199 !IsWithoutProtoADef)
4200 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4205 if (Context.typesAreCompatible(OldQType, NewQType)) {
4206 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4207 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4208 const FunctionProtoType *OldProto = nullptr;
4209 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4210 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4211 // The old declaration provided a function prototype, but the
4212 // new declaration does not. Merge in the prototype.
4213 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4214 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4215 OldProto->getParamTypes(),
4216 OldProto->getExtProtoInfo());
4217 New->setType(NewQType);
4218 New->setHasInheritedPrototype();
4220 // Synthesize parameters with the same types.
4221 SmallVector<ParmVarDecl *, 16> Params;
4222 for (const auto &ParamType : OldProto->param_types()) {
4223 ParmVarDecl *Param = ParmVarDecl::Create(
4224 Context, New, SourceLocation(), SourceLocation(), nullptr,
4225 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4226 Param->setScopeInfo(0, Params.size());
4227 Param->setImplicit();
4228 Params.push_back(Param);
4231 New->setParams(Params);
4234 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4238 // Check if the function types are compatible when pointer size address
4239 // spaces are ignored.
4240 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4241 return false;
4243 // GNU C permits a K&R definition to follow a prototype declaration
4244 // if the declared types of the parameters in the K&R definition
4245 // match the types in the prototype declaration, even when the
4246 // promoted types of the parameters from the K&R definition differ
4247 // from the types in the prototype. GCC then keeps the types from
4248 // the prototype.
4250 // If a variadic prototype is followed by a non-variadic K&R definition,
4251 // the K&R definition becomes variadic. This is sort of an edge case, but
4252 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4253 // C99 6.9.1p8.
4254 if (!getLangOpts().CPlusPlus &&
4255 Old->hasPrototype() && !New->hasPrototype() &&
4256 New->getType()->getAs<FunctionProtoType>() &&
4257 Old->getNumParams() == New->getNumParams()) {
4258 SmallVector<QualType, 16> ArgTypes;
4259 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4260 const FunctionProtoType *OldProto
4261 = Old->getType()->getAs<FunctionProtoType>();
4262 const FunctionProtoType *NewProto
4263 = New->getType()->getAs<FunctionProtoType>();
4265 // Determine whether this is the GNU C extension.
4266 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4267 NewProto->getReturnType());
4268 bool LooseCompatible = !MergedReturn.isNull();
4269 for (unsigned Idx = 0, End = Old->getNumParams();
4270 LooseCompatible && Idx != End; ++Idx) {
4271 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4272 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4273 if (Context.typesAreCompatible(OldParm->getType(),
4274 NewProto->getParamType(Idx))) {
4275 ArgTypes.push_back(NewParm->getType());
4276 } else if (Context.typesAreCompatible(OldParm->getType(),
4277 NewParm->getType(),
4278 /*CompareUnqualified=*/true)) {
4279 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4280 NewProto->getParamType(Idx) };
4281 Warnings.push_back(Warn);
4282 ArgTypes.push_back(NewParm->getType());
4283 } else
4284 LooseCompatible = false;
4287 if (LooseCompatible) {
4288 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4289 Diag(Warnings[Warn].NewParm->getLocation(),
4290 diag::ext_param_promoted_not_compatible_with_prototype)
4291 << Warnings[Warn].PromotedType
4292 << Warnings[Warn].OldParm->getType();
4293 if (Warnings[Warn].OldParm->getLocation().isValid())
4294 Diag(Warnings[Warn].OldParm->getLocation(),
4295 diag::note_previous_declaration);
4298 if (MergeTypeWithOld)
4299 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4300 OldProto->getExtProtoInfo()));
4301 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4304 // Fall through to diagnose conflicting types.
4307 // A function that has already been declared has been redeclared or
4308 // defined with a different type; show an appropriate diagnostic.
4310 // If the previous declaration was an implicitly-generated builtin
4311 // declaration, then at the very least we should use a specialized note.
4312 unsigned BuiltinID;
4313 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4314 // If it's actually a library-defined builtin function like 'malloc'
4315 // or 'printf', just warn about the incompatible redeclaration.
4316 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4317 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4318 Diag(OldLocation, diag::note_previous_builtin_declaration)
4319 << Old << Old->getType();
4320 return false;
4323 PrevDiag = diag::note_previous_builtin_declaration;
4326 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4327 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4328 return true;
4331 /// Completes the merge of two function declarations that are
4332 /// known to be compatible.
4334 /// This routine handles the merging of attributes and other
4335 /// properties of function declarations from the old declaration to
4336 /// the new declaration, once we know that New is in fact a
4337 /// redeclaration of Old.
4339 /// \returns false
4340 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4341 Scope *S, bool MergeTypeWithOld) {
4342 // Merge the attributes
4343 mergeDeclAttributes(New, Old);
4345 // Merge "pure" flag.
4346 if (Old->isPure())
4347 New->setPure();
4349 // Merge "used" flag.
4350 if (Old->getMostRecentDecl()->isUsed(false))
4351 New->setIsUsed();
4353 // Merge attributes from the parameters. These can mismatch with K&R
4354 // declarations.
4355 if (New->getNumParams() == Old->getNumParams())
4356 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4357 ParmVarDecl *NewParam = New->getParamDecl(i);
4358 ParmVarDecl *OldParam = Old->getParamDecl(i);
4359 mergeParamDeclAttributes(NewParam, OldParam, *this);
4360 mergeParamDeclTypes(NewParam, OldParam, *this);
4363 if (getLangOpts().CPlusPlus)
4364 return MergeCXXFunctionDecl(New, Old, S);
4366 // Merge the function types so the we get the composite types for the return
4367 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4368 // was visible.
4369 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4370 if (!Merged.isNull() && MergeTypeWithOld)
4371 New->setType(Merged);
4373 return false;
4376 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4377 ObjCMethodDecl *oldMethod) {
4378 // Merge the attributes, including deprecated/unavailable
4379 AvailabilityMergeKind MergeKind =
4380 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4381 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4382 : AMK_ProtocolImplementation)
4383 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4384 : AMK_Override;
4386 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4388 // Merge attributes from the parameters.
4389 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4390 oe = oldMethod->param_end();
4391 for (ObjCMethodDecl::param_iterator
4392 ni = newMethod->param_begin(), ne = newMethod->param_end();
4393 ni != ne && oi != oe; ++ni, ++oi)
4394 mergeParamDeclAttributes(*ni, *oi, *this);
4396 CheckObjCMethodOverride(newMethod, oldMethod);
4399 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4400 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4402 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4403 ? diag::err_redefinition_different_type
4404 : diag::err_redeclaration_different_type)
4405 << New->getDeclName() << New->getType() << Old->getType();
4407 diag::kind PrevDiag;
4408 SourceLocation OldLocation;
4409 std::tie(PrevDiag, OldLocation)
4410 = getNoteDiagForInvalidRedeclaration(Old, New);
4411 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4412 New->setInvalidDecl();
4415 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4416 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
4417 /// emitting diagnostics as appropriate.
4419 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4420 /// to here in AddInitializerToDecl. We can't check them before the initializer
4421 /// is attached.
4422 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4423 bool MergeTypeWithOld) {
4424 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4425 return;
4427 QualType MergedT;
4428 if (getLangOpts().CPlusPlus) {
4429 if (New->getType()->isUndeducedType()) {
4430 // We don't know what the new type is until the initializer is attached.
4431 return;
4432 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4433 // These could still be something that needs exception specs checked.
4434 return MergeVarDeclExceptionSpecs(New, Old);
4436 // C++ [basic.link]p10:
4437 // [...] the types specified by all declarations referring to a given
4438 // object or function shall be identical, except that declarations for an
4439 // array object can specify array types that differ by the presence or
4440 // absence of a major array bound (8.3.4).
4441 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4442 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4443 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4445 // We are merging a variable declaration New into Old. If it has an array
4446 // bound, and that bound differs from Old's bound, we should diagnose the
4447 // mismatch.
4448 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4449 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4450 PrevVD = PrevVD->getPreviousDecl()) {
4451 QualType PrevVDTy = PrevVD->getType();
4452 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4453 continue;
4455 if (!Context.hasSameType(New->getType(), PrevVDTy))
4456 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4460 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4461 if (Context.hasSameType(OldArray->getElementType(),
4462 NewArray->getElementType()))
4463 MergedT = New->getType();
4465 // FIXME: Check visibility. New is hidden but has a complete type. If New
4466 // has no array bound, it should not inherit one from Old, if Old is not
4467 // visible.
4468 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4469 if (Context.hasSameType(OldArray->getElementType(),
4470 NewArray->getElementType()))
4471 MergedT = Old->getType();
4474 else if (New->getType()->isObjCObjectPointerType() &&
4475 Old->getType()->isObjCObjectPointerType()) {
4476 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4477 Old->getType());
4479 } else {
4480 // C 6.2.7p2:
4481 // All declarations that refer to the same object or function shall have
4482 // compatible type.
4483 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4485 if (MergedT.isNull()) {
4486 // It's OK if we couldn't merge types if either type is dependent, for a
4487 // block-scope variable. In other cases (static data members of class
4488 // templates, variable templates, ...), we require the types to be
4489 // equivalent.
4490 // FIXME: The C++ standard doesn't say anything about this.
4491 if ((New->getType()->isDependentType() ||
4492 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4493 // If the old type was dependent, we can't merge with it, so the new type
4494 // becomes dependent for now. We'll reproduce the original type when we
4495 // instantiate the TypeSourceInfo for the variable.
4496 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4497 New->setType(Context.DependentTy);
4498 return;
4500 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4503 // Don't actually update the type on the new declaration if the old
4504 // declaration was an extern declaration in a different scope.
4505 if (MergeTypeWithOld)
4506 New->setType(MergedT);
4509 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4510 LookupResult &Previous) {
4511 // C11 6.2.7p4:
4512 // For an identifier with internal or external linkage declared
4513 // in a scope in which a prior declaration of that identifier is
4514 // visible, if the prior declaration specifies internal or
4515 // external linkage, the type of the identifier at the later
4516 // declaration becomes the composite type.
4518 // If the variable isn't visible, we do not merge with its type.
4519 if (Previous.isShadowed())
4520 return false;
4522 if (S.getLangOpts().CPlusPlus) {
4523 // C++11 [dcl.array]p3:
4524 // If there is a preceding declaration of the entity in the same
4525 // scope in which the bound was specified, an omitted array bound
4526 // is taken to be the same as in that earlier declaration.
4527 return NewVD->isPreviousDeclInSameBlockScope() ||
4528 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4529 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4530 } else {
4531 // If the old declaration was function-local, don't merge with its
4532 // type unless we're in the same function.
4533 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4534 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4538 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4539 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4540 /// situation, merging decls or emitting diagnostics as appropriate.
4542 /// Tentative definition rules (C99 6.9.2p2) are checked by
4543 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4544 /// definitions here, since the initializer hasn't been attached.
4546 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4547 // If the new decl is already invalid, don't do any other checking.
4548 if (New->isInvalidDecl())
4549 return;
4551 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4552 return;
4554 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4556 // Verify the old decl was also a variable or variable template.
4557 VarDecl *Old = nullptr;
4558 VarTemplateDecl *OldTemplate = nullptr;
4559 if (Previous.isSingleResult()) {
4560 if (NewTemplate) {
4561 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4562 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4564 if (auto *Shadow =
4565 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4566 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4567 return New->setInvalidDecl();
4568 } else {
4569 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4571 if (auto *Shadow =
4572 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4573 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4574 return New->setInvalidDecl();
4577 if (!Old) {
4578 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4579 << New->getDeclName();
4580 notePreviousDefinition(Previous.getRepresentativeDecl(),
4581 New->getLocation());
4582 return New->setInvalidDecl();
4585 // If the old declaration was found in an inline namespace and the new
4586 // declaration was qualified, update the DeclContext to match.
4587 adjustDeclContextForDeclaratorDecl(New, Old);
4589 // Ensure the template parameters are compatible.
4590 if (NewTemplate &&
4591 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4592 OldTemplate->getTemplateParameters(),
4593 /*Complain=*/true, TPL_TemplateMatch))
4594 return New->setInvalidDecl();
4596 // C++ [class.mem]p1:
4597 // A member shall not be declared twice in the member-specification [...]
4599 // Here, we need only consider static data members.
4600 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4601 Diag(New->getLocation(), diag::err_duplicate_member)
4602 << New->getIdentifier();
4603 Diag(Old->getLocation(), diag::note_previous_declaration);
4604 New->setInvalidDecl();
4607 mergeDeclAttributes(New, Old);
4608 // Warn if an already-declared variable is made a weak_import in a subsequent
4609 // declaration
4610 if (New->hasAttr<WeakImportAttr>() &&
4611 Old->getStorageClass() == SC_None &&
4612 !Old->hasAttr<WeakImportAttr>()) {
4613 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4614 Diag(Old->getLocation(), diag::note_previous_declaration);
4615 // Remove weak_import attribute on new declaration.
4616 New->dropAttr<WeakImportAttr>();
4619 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4620 if (!Old->hasAttr<InternalLinkageAttr>()) {
4621 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4622 << ILA;
4623 Diag(Old->getLocation(), diag::note_previous_declaration);
4624 New->dropAttr<InternalLinkageAttr>();
4627 // Merge the types.
4628 VarDecl *MostRecent = Old->getMostRecentDecl();
4629 if (MostRecent != Old) {
4630 MergeVarDeclTypes(New, MostRecent,
4631 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4632 if (New->isInvalidDecl())
4633 return;
4636 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4637 if (New->isInvalidDecl())
4638 return;
4640 diag::kind PrevDiag;
4641 SourceLocation OldLocation;
4642 std::tie(PrevDiag, OldLocation) =
4643 getNoteDiagForInvalidRedeclaration(Old, New);
4645 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4646 if (New->getStorageClass() == SC_Static &&
4647 !New->isStaticDataMember() &&
4648 Old->hasExternalFormalLinkage()) {
4649 if (getLangOpts().MicrosoftExt) {
4650 Diag(New->getLocation(), diag::ext_static_non_static)
4651 << New->getDeclName();
4652 Diag(OldLocation, PrevDiag);
4653 } else {
4654 Diag(New->getLocation(), diag::err_static_non_static)
4655 << New->getDeclName();
4656 Diag(OldLocation, PrevDiag);
4657 return New->setInvalidDecl();
4660 // C99 6.2.2p4:
4661 // For an identifier declared with the storage-class specifier
4662 // extern in a scope in which a prior declaration of that
4663 // identifier is visible,23) if the prior declaration specifies
4664 // internal or external linkage, the linkage of the identifier at
4665 // the later declaration is the same as the linkage specified at
4666 // the prior declaration. If no prior declaration is visible, or
4667 // if the prior declaration specifies no linkage, then the
4668 // identifier has external linkage.
4669 if (New->hasExternalStorage() && Old->hasLinkage())
4670 /* Okay */;
4671 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4672 !New->isStaticDataMember() &&
4673 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4674 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4675 Diag(OldLocation, PrevDiag);
4676 return New->setInvalidDecl();
4679 // Check if extern is followed by non-extern and vice-versa.
4680 if (New->hasExternalStorage() &&
4681 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4682 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4683 Diag(OldLocation, PrevDiag);
4684 return New->setInvalidDecl();
4686 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4687 !New->hasExternalStorage()) {
4688 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4689 Diag(OldLocation, PrevDiag);
4690 return New->setInvalidDecl();
4693 if (CheckRedeclarationInModule(New, Old))
4694 return;
4696 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4698 // FIXME: The test for external storage here seems wrong? We still
4699 // need to check for mismatches.
4700 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4701 // Don't complain about out-of-line definitions of static members.
4702 !(Old->getLexicalDeclContext()->isRecord() &&
4703 !New->getLexicalDeclContext()->isRecord())) {
4704 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4705 Diag(OldLocation, PrevDiag);
4706 return New->setInvalidDecl();
4709 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4710 if (VarDecl *Def = Old->getDefinition()) {
4711 // C++1z [dcl.fcn.spec]p4:
4712 // If the definition of a variable appears in a translation unit before
4713 // its first declaration as inline, the program is ill-formed.
4714 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4715 Diag(Def->getLocation(), diag::note_previous_definition);
4719 // If this redeclaration makes the variable inline, we may need to add it to
4720 // UndefinedButUsed.
4721 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4722 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4723 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4724 SourceLocation()));
4726 if (New->getTLSKind() != Old->getTLSKind()) {
4727 if (!Old->getTLSKind()) {
4728 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4729 Diag(OldLocation, PrevDiag);
4730 } else if (!New->getTLSKind()) {
4731 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4732 Diag(OldLocation, PrevDiag);
4733 } else {
4734 // Do not allow redeclaration to change the variable between requiring
4735 // static and dynamic initialization.
4736 // FIXME: GCC allows this, but uses the TLS keyword on the first
4737 // declaration to determine the kind. Do we need to be compatible here?
4738 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4739 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4740 Diag(OldLocation, PrevDiag);
4744 // C++ doesn't have tentative definitions, so go right ahead and check here.
4745 if (getLangOpts().CPlusPlus) {
4746 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4747 Old->getCanonicalDecl()->isConstexpr()) {
4748 // This definition won't be a definition any more once it's been merged.
4749 Diag(New->getLocation(),
4750 diag::warn_deprecated_redundant_constexpr_static_def);
4751 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4752 VarDecl *Def = Old->getDefinition();
4753 if (Def && checkVarDeclRedefinition(Def, New))
4754 return;
4758 if (haveIncompatibleLanguageLinkages(Old, New)) {
4759 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4760 Diag(OldLocation, PrevDiag);
4761 New->setInvalidDecl();
4762 return;
4765 // Merge "used" flag.
4766 if (Old->getMostRecentDecl()->isUsed(false))
4767 New->setIsUsed();
4769 // Keep a chain of previous declarations.
4770 New->setPreviousDecl(Old);
4771 if (NewTemplate)
4772 NewTemplate->setPreviousDecl(OldTemplate);
4774 // Inherit access appropriately.
4775 New->setAccess(Old->getAccess());
4776 if (NewTemplate)
4777 NewTemplate->setAccess(New->getAccess());
4779 if (Old->isInline())
4780 New->setImplicitlyInline();
4783 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4784 SourceManager &SrcMgr = getSourceManager();
4785 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4786 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4787 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4788 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4789 auto &HSI = PP.getHeaderSearchInfo();
4790 StringRef HdrFilename =
4791 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4793 auto noteFromModuleOrInclude = [&](Module *Mod,
4794 SourceLocation IncLoc) -> bool {
4795 // Redefinition errors with modules are common with non modular mapped
4796 // headers, example: a non-modular header H in module A that also gets
4797 // included directly in a TU. Pointing twice to the same header/definition
4798 // is confusing, try to get better diagnostics when modules is on.
4799 if (IncLoc.isValid()) {
4800 if (Mod) {
4801 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4802 << HdrFilename.str() << Mod->getFullModuleName();
4803 if (!Mod->DefinitionLoc.isInvalid())
4804 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4805 << Mod->getFullModuleName();
4806 } else {
4807 Diag(IncLoc, diag::note_redefinition_include_same_file)
4808 << HdrFilename.str();
4810 return true;
4813 return false;
4816 // Is it the same file and same offset? Provide more information on why
4817 // this leads to a redefinition error.
4818 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4819 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4820 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4821 bool EmittedDiag =
4822 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4823 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4825 // If the header has no guards, emit a note suggesting one.
4826 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4827 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4829 if (EmittedDiag)
4830 return;
4833 // Redefinition coming from different files or couldn't do better above.
4834 if (Old->getLocation().isValid())
4835 Diag(Old->getLocation(), diag::note_previous_definition);
4838 /// We've just determined that \p Old and \p New both appear to be definitions
4839 /// of the same variable. Either diagnose or fix the problem.
4840 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4841 if (!hasVisibleDefinition(Old) &&
4842 (New->getFormalLinkage() == InternalLinkage ||
4843 New->isInline() ||
4844 isa<VarTemplateSpecializationDecl>(New) ||
4845 New->getDescribedVarTemplate() ||
4846 New->getNumTemplateParameterLists() ||
4847 New->getDeclContext()->isDependentContext())) {
4848 // The previous definition is hidden, and multiple definitions are
4849 // permitted (in separate TUs). Demote this to a declaration.
4850 New->demoteThisDefinitionToDeclaration();
4852 // Make the canonical definition visible.
4853 if (auto *OldTD = Old->getDescribedVarTemplate())
4854 makeMergedDefinitionVisible(OldTD);
4855 makeMergedDefinitionVisible(Old);
4856 return false;
4857 } else {
4858 Diag(New->getLocation(), diag::err_redefinition) << New;
4859 notePreviousDefinition(Old, New->getLocation());
4860 New->setInvalidDecl();
4861 return true;
4865 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4866 /// no declarator (e.g. "struct foo;") is parsed.
4867 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4868 DeclSpec &DS,
4869 const ParsedAttributesView &DeclAttrs,
4870 RecordDecl *&AnonRecord) {
4871 return ParsedFreeStandingDeclSpec(
4872 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4875 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4876 // disambiguate entities defined in different scopes.
4877 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4878 // compatibility.
4879 // We will pick our mangling number depending on which version of MSVC is being
4880 // targeted.
4881 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4882 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4883 ? S->getMSCurManglingNumber()
4884 : S->getMSLastManglingNumber();
4887 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4888 if (!Context.getLangOpts().CPlusPlus)
4889 return;
4891 if (isa<CXXRecordDecl>(Tag->getParent())) {
4892 // If this tag is the direct child of a class, number it if
4893 // it is anonymous.
4894 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4895 return;
4896 MangleNumberingContext &MCtx =
4897 Context.getManglingNumberContext(Tag->getParent());
4898 Context.setManglingNumber(
4899 Tag, MCtx.getManglingNumber(
4900 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4901 return;
4904 // If this tag isn't a direct child of a class, number it if it is local.
4905 MangleNumberingContext *MCtx;
4906 Decl *ManglingContextDecl;
4907 std::tie(MCtx, ManglingContextDecl) =
4908 getCurrentMangleNumberContext(Tag->getDeclContext());
4909 if (MCtx) {
4910 Context.setManglingNumber(
4911 Tag, MCtx->getManglingNumber(
4912 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4916 namespace {
4917 struct NonCLikeKind {
4918 enum {
4919 None,
4920 BaseClass,
4921 DefaultMemberInit,
4922 Lambda,
4923 Friend,
4924 OtherMember,
4925 Invalid,
4926 } Kind = None;
4927 SourceRange Range;
4929 explicit operator bool() { return Kind != None; }
4933 /// Determine whether a class is C-like, according to the rules of C++
4934 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4935 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4936 if (RD->isInvalidDecl())
4937 return {NonCLikeKind::Invalid, {}};
4939 // C++ [dcl.typedef]p9: [P1766R1]
4940 // An unnamed class with a typedef name for linkage purposes shall not
4942 // -- have any base classes
4943 if (RD->getNumBases())
4944 return {NonCLikeKind::BaseClass,
4945 SourceRange(RD->bases_begin()->getBeginLoc(),
4946 RD->bases_end()[-1].getEndLoc())};
4947 bool Invalid = false;
4948 for (Decl *D : RD->decls()) {
4949 // Don't complain about things we already diagnosed.
4950 if (D->isInvalidDecl()) {
4951 Invalid = true;
4952 continue;
4955 // -- have any [...] default member initializers
4956 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4957 if (FD->hasInClassInitializer()) {
4958 auto *Init = FD->getInClassInitializer();
4959 return {NonCLikeKind::DefaultMemberInit,
4960 Init ? Init->getSourceRange() : D->getSourceRange()};
4962 continue;
4965 // FIXME: We don't allow friend declarations. This violates the wording of
4966 // P1766, but not the intent.
4967 if (isa<FriendDecl>(D))
4968 return {NonCLikeKind::Friend, D->getSourceRange()};
4970 // -- declare any members other than non-static data members, member
4971 // enumerations, or member classes,
4972 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4973 isa<EnumDecl>(D))
4974 continue;
4975 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4976 if (!MemberRD) {
4977 if (D->isImplicit())
4978 continue;
4979 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4982 // -- contain a lambda-expression,
4983 if (MemberRD->isLambda())
4984 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4986 // and all member classes shall also satisfy these requirements
4987 // (recursively).
4988 if (MemberRD->isThisDeclarationADefinition()) {
4989 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4990 return Kind;
4994 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4997 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4998 TypedefNameDecl *NewTD) {
4999 if (TagFromDeclSpec->isInvalidDecl())
5000 return;
5002 // Do nothing if the tag already has a name for linkage purposes.
5003 if (TagFromDeclSpec->hasNameForLinkage())
5004 return;
5006 // A well-formed anonymous tag must always be a TUK_Definition.
5007 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5009 // The type must match the tag exactly; no qualifiers allowed.
5010 if (!Context.hasSameType(NewTD->getUnderlyingType(),
5011 Context.getTagDeclType(TagFromDeclSpec))) {
5012 if (getLangOpts().CPlusPlus)
5013 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5014 return;
5017 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5018 // An unnamed class with a typedef name for linkage purposes shall [be
5019 // C-like].
5021 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5022 // shouldn't happen, but there are constructs that the language rule doesn't
5023 // disallow for which we can't reasonably avoid computing linkage early.
5024 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5025 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5026 : NonCLikeKind();
5027 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5028 if (NonCLike || ChangesLinkage) {
5029 if (NonCLike.Kind == NonCLikeKind::Invalid)
5030 return;
5032 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5033 if (ChangesLinkage) {
5034 // If the linkage changes, we can't accept this as an extension.
5035 if (NonCLike.Kind == NonCLikeKind::None)
5036 DiagID = diag::err_typedef_changes_linkage;
5037 else
5038 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5041 SourceLocation FixitLoc =
5042 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5043 llvm::SmallString<40> TextToInsert;
5044 TextToInsert += ' ';
5045 TextToInsert += NewTD->getIdentifier()->getName();
5047 Diag(FixitLoc, DiagID)
5048 << isa<TypeAliasDecl>(NewTD)
5049 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5050 if (NonCLike.Kind != NonCLikeKind::None) {
5051 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5052 << NonCLike.Kind - 1 << NonCLike.Range;
5054 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5055 << NewTD << isa<TypeAliasDecl>(NewTD);
5057 if (ChangesLinkage)
5058 return;
5061 // Otherwise, set this as the anon-decl typedef for the tag.
5062 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5065 static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5066 DeclSpec::TST T = DS.getTypeSpecType();
5067 switch (T) {
5068 case DeclSpec::TST_class:
5069 return 0;
5070 case DeclSpec::TST_struct:
5071 return 1;
5072 case DeclSpec::TST_interface:
5073 return 2;
5074 case DeclSpec::TST_union:
5075 return 3;
5076 case DeclSpec::TST_enum:
5077 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5078 if (ED->isScopedUsingClassTag())
5079 return 5;
5080 if (ED->isScoped())
5081 return 6;
5083 return 4;
5084 default:
5085 llvm_unreachable("unexpected type specifier");
5088 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5089 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5090 /// parameters to cope with template friend declarations.
5091 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5092 DeclSpec &DS,
5093 const ParsedAttributesView &DeclAttrs,
5094 MultiTemplateParamsArg TemplateParams,
5095 bool IsExplicitInstantiation,
5096 RecordDecl *&AnonRecord) {
5097 Decl *TagD = nullptr;
5098 TagDecl *Tag = nullptr;
5099 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5100 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5101 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5102 DS.getTypeSpecType() == DeclSpec::TST_union ||
5103 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5104 TagD = DS.getRepAsDecl();
5106 if (!TagD) // We probably had an error
5107 return nullptr;
5109 // Note that the above type specs guarantee that the
5110 // type rep is a Decl, whereas in many of the others
5111 // it's a Type.
5112 if (isa<TagDecl>(TagD))
5113 Tag = cast<TagDecl>(TagD);
5114 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5115 Tag = CTD->getTemplatedDecl();
5118 if (Tag) {
5119 handleTagNumbering(Tag, S);
5120 Tag->setFreeStanding();
5121 if (Tag->isInvalidDecl())
5122 return Tag;
5125 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5126 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5127 // or incomplete types shall not be restrict-qualified."
5128 if (TypeQuals & DeclSpec::TQ_restrict)
5129 Diag(DS.getRestrictSpecLoc(),
5130 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5131 << DS.getSourceRange();
5134 if (DS.isInlineSpecified())
5135 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5136 << getLangOpts().CPlusPlus17;
5138 if (DS.hasConstexprSpecifier()) {
5139 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5140 // and definitions of functions and variables.
5141 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5142 // the declaration of a function or function template
5143 if (Tag)
5144 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5145 << GetDiagnosticTypeSpecifierID(DS)
5146 << static_cast<int>(DS.getConstexprSpecifier());
5147 else
5148 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5149 << static_cast<int>(DS.getConstexprSpecifier());
5150 // Don't emit warnings after this error.
5151 return TagD;
5154 DiagnoseFunctionSpecifiers(DS);
5156 if (DS.isFriendSpecified()) {
5157 // If we're dealing with a decl but not a TagDecl, assume that
5158 // whatever routines created it handled the friendship aspect.
5159 if (TagD && !Tag)
5160 return nullptr;
5161 return ActOnFriendTypeDecl(S, DS, TemplateParams);
5164 const CXXScopeSpec &SS = DS.getTypeSpecScope();
5165 bool IsExplicitSpecialization =
5166 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
5167 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
5168 !IsExplicitInstantiation && !IsExplicitSpecialization &&
5169 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
5170 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
5171 // nested-name-specifier unless it is an explicit instantiation
5172 // or an explicit specialization.
5174 // FIXME: We allow class template partial specializations here too, per the
5175 // obvious intent of DR1819.
5177 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
5178 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
5179 << GetDiagnosticTypeSpecifierID(DS) << SS.getRange();
5180 return nullptr;
5183 // Track whether this decl-specifier declares anything.
5184 bool DeclaresAnything = true;
5186 // Handle anonymous struct definitions.
5187 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5188 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5189 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5190 if (getLangOpts().CPlusPlus ||
5191 Record->getDeclContext()->isRecord()) {
5192 // If CurContext is a DeclContext that can contain statements,
5193 // RecursiveASTVisitor won't visit the decls that
5194 // BuildAnonymousStructOrUnion() will put into CurContext.
5195 // Also store them here so that they can be part of the
5196 // DeclStmt that gets created in this case.
5197 // FIXME: Also return the IndirectFieldDecls created by
5198 // BuildAnonymousStructOr union, for the same reason?
5199 if (CurContext->isFunctionOrMethod())
5200 AnonRecord = Record;
5201 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5202 Context.getPrintingPolicy());
5205 DeclaresAnything = false;
5209 // C11 6.7.2.1p2:
5210 // A struct-declaration that does not declare an anonymous structure or
5211 // anonymous union shall contain a struct-declarator-list.
5213 // This rule also existed in C89 and C99; the grammar for struct-declaration
5214 // did not permit a struct-declaration without a struct-declarator-list.
5215 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5216 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5217 // Check for Microsoft C extension: anonymous struct/union member.
5218 // Handle 2 kinds of anonymous struct/union:
5219 // struct STRUCT;
5220 // union UNION;
5221 // and
5222 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5223 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5224 if ((Tag && Tag->getDeclName()) ||
5225 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5226 RecordDecl *Record = nullptr;
5227 if (Tag)
5228 Record = dyn_cast<RecordDecl>(Tag);
5229 else if (const RecordType *RT =
5230 DS.getRepAsType().get()->getAsStructureType())
5231 Record = RT->getDecl();
5232 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5233 Record = UT->getDecl();
5235 if (Record && getLangOpts().MicrosoftExt) {
5236 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5237 << Record->isUnion() << DS.getSourceRange();
5238 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5241 DeclaresAnything = false;
5245 // Skip all the checks below if we have a type error.
5246 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5247 (TagD && TagD->isInvalidDecl()))
5248 return TagD;
5250 if (getLangOpts().CPlusPlus &&
5251 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5252 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5253 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5254 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5255 DeclaresAnything = false;
5257 if (!DS.isMissingDeclaratorOk()) {
5258 // Customize diagnostic for a typedef missing a name.
5259 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5260 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5261 << DS.getSourceRange();
5262 else
5263 DeclaresAnything = false;
5266 if (DS.isModulePrivateSpecified() &&
5267 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5268 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5269 << Tag->getTagKind()
5270 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5272 ActOnDocumentableDecl(TagD);
5274 // C 6.7/2:
5275 // A declaration [...] shall declare at least a declarator [...], a tag,
5276 // or the members of an enumeration.
5277 // C++ [dcl.dcl]p3:
5278 // [If there are no declarators], and except for the declaration of an
5279 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5280 // names into the program, or shall redeclare a name introduced by a
5281 // previous declaration.
5282 if (!DeclaresAnything) {
5283 // In C, we allow this as a (popular) extension / bug. Don't bother
5284 // producing further diagnostics for redundant qualifiers after this.
5285 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5286 ? diag::err_no_declarators
5287 : diag::ext_no_declarators)
5288 << DS.getSourceRange();
5289 return TagD;
5292 // C++ [dcl.stc]p1:
5293 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5294 // init-declarator-list of the declaration shall not be empty.
5295 // C++ [dcl.fct.spec]p1:
5296 // If a cv-qualifier appears in a decl-specifier-seq, the
5297 // init-declarator-list of the declaration shall not be empty.
5299 // Spurious qualifiers here appear to be valid in C.
5300 unsigned DiagID = diag::warn_standalone_specifier;
5301 if (getLangOpts().CPlusPlus)
5302 DiagID = diag::ext_standalone_specifier;
5304 // Note that a linkage-specification sets a storage class, but
5305 // 'extern "C" struct foo;' is actually valid and not theoretically
5306 // useless.
5307 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5308 if (SCS == DeclSpec::SCS_mutable)
5309 // Since mutable is not a viable storage class specifier in C, there is
5310 // no reason to treat it as an extension. Instead, diagnose as an error.
5311 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5312 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5313 Diag(DS.getStorageClassSpecLoc(), DiagID)
5314 << DeclSpec::getSpecifierName(SCS);
5317 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5318 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5319 << DeclSpec::getSpecifierName(TSCS);
5320 if (DS.getTypeQualifiers()) {
5321 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5322 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5323 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5324 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5325 // Restrict is covered above.
5326 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5327 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5328 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5329 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5332 // Warn about ignored type attributes, for example:
5333 // __attribute__((aligned)) struct A;
5334 // Attributes should be placed after tag to apply to type declaration.
5335 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5336 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5337 if (TypeSpecType == DeclSpec::TST_class ||
5338 TypeSpecType == DeclSpec::TST_struct ||
5339 TypeSpecType == DeclSpec::TST_interface ||
5340 TypeSpecType == DeclSpec::TST_union ||
5341 TypeSpecType == DeclSpec::TST_enum) {
5342 for (const ParsedAttr &AL : DS.getAttributes())
5343 Diag(AL.getLoc(), AL.isRegularKeywordAttribute()
5344 ? diag::err_declspec_keyword_has_no_effect
5345 : diag::warn_declspec_attribute_ignored)
5346 << AL << GetDiagnosticTypeSpecifierID(DS);
5347 for (const ParsedAttr &AL : DeclAttrs)
5348 Diag(AL.getLoc(), AL.isRegularKeywordAttribute()
5349 ? diag::err_declspec_keyword_has_no_effect
5350 : diag::warn_declspec_attribute_ignored)
5351 << AL << GetDiagnosticTypeSpecifierID(DS);
5355 return TagD;
5358 /// We are trying to inject an anonymous member into the given scope;
5359 /// check if there's an existing declaration that can't be overloaded.
5361 /// \return true if this is a forbidden redeclaration
5362 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5363 DeclContext *Owner,
5364 DeclarationName Name,
5365 SourceLocation NameLoc, bool IsUnion,
5366 StorageClass SC) {
5367 LookupResult R(SemaRef, Name, NameLoc,
5368 Owner->isRecord() ? Sema::LookupMemberName
5369 : Sema::LookupOrdinaryName,
5370 Sema::ForVisibleRedeclaration);
5371 if (!SemaRef.LookupName(R, S)) return false;
5373 // Pick a representative declaration.
5374 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5375 assert(PrevDecl && "Expected a non-null Decl");
5377 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5378 return false;
5380 if (SC == StorageClass::SC_None &&
5381 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5382 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5383 if (!Owner->isRecord())
5384 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5385 return false;
5388 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5389 << IsUnion << Name;
5390 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5392 return true;
5395 void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5396 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5397 DiagPlaceholderFieldDeclDefinitions(RD);
5400 /// Emit diagnostic warnings for placeholder members.
5401 /// We can only do that after the class is fully constructed,
5402 /// as anonymous union/structs can insert placeholders
5403 /// in their parent scope (which might be a Record).
5404 void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5405 if (!getLangOpts().CPlusPlus)
5406 return;
5408 // This function can be parsed before we have validated the
5409 // structure as an anonymous struct
5410 if (Record->isAnonymousStructOrUnion())
5411 return;
5413 const NamedDecl *First = 0;
5414 for (const Decl *D : Record->decls()) {
5415 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5416 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5417 continue;
5418 if (!First)
5419 First = ND;
5420 else
5421 DiagPlaceholderVariableDefinition(ND->getLocation());
5425 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5426 /// anonymous struct or union AnonRecord into the owning context Owner
5427 /// and scope S. This routine will be invoked just after we realize
5428 /// that an unnamed union or struct is actually an anonymous union or
5429 /// struct, e.g.,
5431 /// @code
5432 /// union {
5433 /// int i;
5434 /// float f;
5435 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5436 /// // f into the surrounding scope.x
5437 /// @endcode
5439 /// This routine is recursive, injecting the names of nested anonymous
5440 /// structs/unions into the owning context and scope as well.
5441 static bool
5442 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5443 RecordDecl *AnonRecord, AccessSpecifier AS,
5444 StorageClass SC,
5445 SmallVectorImpl<NamedDecl *> &Chaining) {
5446 bool Invalid = false;
5448 // Look every FieldDecl and IndirectFieldDecl with a name.
5449 for (auto *D : AnonRecord->decls()) {
5450 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5451 cast<NamedDecl>(D)->getDeclName()) {
5452 ValueDecl *VD = cast<ValueDecl>(D);
5453 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5454 VD->getLocation(), AnonRecord->isUnion(),
5455 SC)) {
5456 // C++ [class.union]p2:
5457 // The names of the members of an anonymous union shall be
5458 // distinct from the names of any other entity in the
5459 // scope in which the anonymous union is declared.
5460 Invalid = true;
5461 } else {
5462 // C++ [class.union]p2:
5463 // For the purpose of name lookup, after the anonymous union
5464 // definition, the members of the anonymous union are
5465 // considered to have been defined in the scope in which the
5466 // anonymous union is declared.
5467 unsigned OldChainingSize = Chaining.size();
5468 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5469 Chaining.append(IF->chain_begin(), IF->chain_end());
5470 else
5471 Chaining.push_back(VD);
5473 assert(Chaining.size() >= 2);
5474 NamedDecl **NamedChain =
5475 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5476 for (unsigned i = 0; i < Chaining.size(); i++)
5477 NamedChain[i] = Chaining[i];
5479 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5480 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5481 VD->getType(), {NamedChain, Chaining.size()});
5483 for (const auto *Attr : VD->attrs())
5484 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5486 IndirectField->setAccess(AS);
5487 IndirectField->setImplicit();
5488 SemaRef.PushOnScopeChains(IndirectField, S);
5490 // That includes picking up the appropriate access specifier.
5491 if (AS != AS_none) IndirectField->setAccess(AS);
5493 Chaining.resize(OldChainingSize);
5498 return Invalid;
5501 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5502 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5503 /// illegal input values are mapped to SC_None.
5504 static StorageClass
5505 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5506 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5507 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5508 "Parser allowed 'typedef' as storage class VarDecl.");
5509 switch (StorageClassSpec) {
5510 case DeclSpec::SCS_unspecified: return SC_None;
5511 case DeclSpec::SCS_extern:
5512 if (DS.isExternInLinkageSpec())
5513 return SC_None;
5514 return SC_Extern;
5515 case DeclSpec::SCS_static: return SC_Static;
5516 case DeclSpec::SCS_auto: return SC_Auto;
5517 case DeclSpec::SCS_register: return SC_Register;
5518 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5519 // Illegal SCSs map to None: error reporting is up to the caller.
5520 case DeclSpec::SCS_mutable: // Fall through.
5521 case DeclSpec::SCS_typedef: return SC_None;
5523 llvm_unreachable("unknown storage class specifier");
5526 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5527 assert(Record->hasInClassInitializer());
5529 for (const auto *I : Record->decls()) {
5530 const auto *FD = dyn_cast<FieldDecl>(I);
5531 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5532 FD = IFD->getAnonField();
5533 if (FD && FD->hasInClassInitializer())
5534 return FD->getLocation();
5537 llvm_unreachable("couldn't find in-class initializer");
5540 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5541 SourceLocation DefaultInitLoc) {
5542 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5543 return;
5545 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5546 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5549 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5550 CXXRecordDecl *AnonUnion) {
5551 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5552 return;
5554 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5557 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5558 /// anonymous structure or union. Anonymous unions are a C++ feature
5559 /// (C++ [class.union]) and a C11 feature; anonymous structures
5560 /// are a C11 feature and GNU C++ extension.
5561 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5562 AccessSpecifier AS,
5563 RecordDecl *Record,
5564 const PrintingPolicy &Policy) {
5565 DeclContext *Owner = Record->getDeclContext();
5567 // Diagnose whether this anonymous struct/union is an extension.
5568 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5569 Diag(Record->getLocation(), diag::ext_anonymous_union);
5570 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5571 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5572 else if (!Record->isUnion() && !getLangOpts().C11)
5573 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5575 // C and C++ require different kinds of checks for anonymous
5576 // structs/unions.
5577 bool Invalid = false;
5578 if (getLangOpts().CPlusPlus) {
5579 const char *PrevSpec = nullptr;
5580 if (Record->isUnion()) {
5581 // C++ [class.union]p6:
5582 // C++17 [class.union.anon]p2:
5583 // Anonymous unions declared in a named namespace or in the
5584 // global namespace shall be declared static.
5585 unsigned DiagID;
5586 DeclContext *OwnerScope = Owner->getRedeclContext();
5587 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5588 (OwnerScope->isTranslationUnit() ||
5589 (OwnerScope->isNamespace() &&
5590 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5591 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5592 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5594 // Recover by adding 'static'.
5595 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5596 PrevSpec, DiagID, Policy);
5598 // C++ [class.union]p6:
5599 // A storage class is not allowed in a declaration of an
5600 // anonymous union in a class scope.
5601 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5602 isa<RecordDecl>(Owner)) {
5603 Diag(DS.getStorageClassSpecLoc(),
5604 diag::err_anonymous_union_with_storage_spec)
5605 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5607 // Recover by removing the storage specifier.
5608 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5609 SourceLocation(),
5610 PrevSpec, DiagID, Context.getPrintingPolicy());
5614 // Ignore const/volatile/restrict qualifiers.
5615 if (DS.getTypeQualifiers()) {
5616 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5617 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5618 << Record->isUnion() << "const"
5619 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5620 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5621 Diag(DS.getVolatileSpecLoc(),
5622 diag::ext_anonymous_struct_union_qualified)
5623 << Record->isUnion() << "volatile"
5624 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5625 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5626 Diag(DS.getRestrictSpecLoc(),
5627 diag::ext_anonymous_struct_union_qualified)
5628 << Record->isUnion() << "restrict"
5629 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5630 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5631 Diag(DS.getAtomicSpecLoc(),
5632 diag::ext_anonymous_struct_union_qualified)
5633 << Record->isUnion() << "_Atomic"
5634 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5635 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5636 Diag(DS.getUnalignedSpecLoc(),
5637 diag::ext_anonymous_struct_union_qualified)
5638 << Record->isUnion() << "__unaligned"
5639 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5641 DS.ClearTypeQualifiers();
5644 // C++ [class.union]p2:
5645 // The member-specification of an anonymous union shall only
5646 // define non-static data members. [Note: nested types and
5647 // functions cannot be declared within an anonymous union. ]
5648 for (auto *Mem : Record->decls()) {
5649 // Ignore invalid declarations; we already diagnosed them.
5650 if (Mem->isInvalidDecl())
5651 continue;
5653 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5654 // C++ [class.union]p3:
5655 // An anonymous union shall not have private or protected
5656 // members (clause 11).
5657 assert(FD->getAccess() != AS_none);
5658 if (FD->getAccess() != AS_public) {
5659 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5660 << Record->isUnion() << (FD->getAccess() == AS_protected);
5661 Invalid = true;
5664 // C++ [class.union]p1
5665 // An object of a class with a non-trivial constructor, a non-trivial
5666 // copy constructor, a non-trivial destructor, or a non-trivial copy
5667 // assignment operator cannot be a member of a union, nor can an
5668 // array of such objects.
5669 if (CheckNontrivialField(FD))
5670 Invalid = true;
5671 } else if (Mem->isImplicit()) {
5672 // Any implicit members are fine.
5673 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5674 // This is a type that showed up in an
5675 // elaborated-type-specifier inside the anonymous struct or
5676 // union, but which actually declares a type outside of the
5677 // anonymous struct or union. It's okay.
5678 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5679 if (!MemRecord->isAnonymousStructOrUnion() &&
5680 MemRecord->getDeclName()) {
5681 // Visual C++ allows type definition in anonymous struct or union.
5682 if (getLangOpts().MicrosoftExt)
5683 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5684 << Record->isUnion();
5685 else {
5686 // This is a nested type declaration.
5687 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5688 << Record->isUnion();
5689 Invalid = true;
5691 } else {
5692 // This is an anonymous type definition within another anonymous type.
5693 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5694 // not part of standard C++.
5695 Diag(MemRecord->getLocation(),
5696 diag::ext_anonymous_record_with_anonymous_type)
5697 << Record->isUnion();
5699 } else if (isa<AccessSpecDecl>(Mem)) {
5700 // Any access specifier is fine.
5701 } else if (isa<StaticAssertDecl>(Mem)) {
5702 // In C++1z, static_assert declarations are also fine.
5703 } else {
5704 // We have something that isn't a non-static data
5705 // member. Complain about it.
5706 unsigned DK = diag::err_anonymous_record_bad_member;
5707 if (isa<TypeDecl>(Mem))
5708 DK = diag::err_anonymous_record_with_type;
5709 else if (isa<FunctionDecl>(Mem))
5710 DK = diag::err_anonymous_record_with_function;
5711 else if (isa<VarDecl>(Mem))
5712 DK = diag::err_anonymous_record_with_static;
5714 // Visual C++ allows type definition in anonymous struct or union.
5715 if (getLangOpts().MicrosoftExt &&
5716 DK == diag::err_anonymous_record_with_type)
5717 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5718 << Record->isUnion();
5719 else {
5720 Diag(Mem->getLocation(), DK) << Record->isUnion();
5721 Invalid = true;
5726 // C++11 [class.union]p8 (DR1460):
5727 // At most one variant member of a union may have a
5728 // brace-or-equal-initializer.
5729 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5730 Owner->isRecord())
5731 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5732 cast<CXXRecordDecl>(Record));
5735 if (!Record->isUnion() && !Owner->isRecord()) {
5736 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5737 << getLangOpts().CPlusPlus;
5738 Invalid = true;
5741 // C++ [dcl.dcl]p3:
5742 // [If there are no declarators], and except for the declaration of an
5743 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5744 // names into the program
5745 // C++ [class.mem]p2:
5746 // each such member-declaration shall either declare at least one member
5747 // name of the class or declare at least one unnamed bit-field
5749 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5750 if (getLangOpts().CPlusPlus && Record->field_empty())
5751 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5753 // Mock up a declarator.
5754 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5755 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5756 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5757 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5759 // Create a declaration for this anonymous struct/union.
5760 NamedDecl *Anon = nullptr;
5761 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5762 Anon = FieldDecl::Create(
5763 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5764 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5765 /*BitWidth=*/nullptr, /*Mutable=*/false,
5766 /*InitStyle=*/ICIS_NoInit);
5767 Anon->setAccess(AS);
5768 ProcessDeclAttributes(S, Anon, Dc);
5770 if (getLangOpts().CPlusPlus)
5771 FieldCollector->Add(cast<FieldDecl>(Anon));
5772 } else {
5773 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5774 if (SCSpec == DeclSpec::SCS_mutable) {
5775 // mutable can only appear on non-static class members, so it's always
5776 // an error here
5777 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5778 Invalid = true;
5779 SC = SC_None;
5782 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5783 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5784 Context.getTypeDeclType(Record), TInfo, SC);
5785 ProcessDeclAttributes(S, Anon, Dc);
5787 // Default-initialize the implicit variable. This initialization will be
5788 // trivial in almost all cases, except if a union member has an in-class
5789 // initializer:
5790 // union { int n = 0; };
5791 ActOnUninitializedDecl(Anon);
5793 Anon->setImplicit();
5795 // Mark this as an anonymous struct/union type.
5796 Record->setAnonymousStructOrUnion(true);
5798 // Add the anonymous struct/union object to the current
5799 // context. We'll be referencing this object when we refer to one of
5800 // its members.
5801 Owner->addDecl(Anon);
5803 // Inject the members of the anonymous struct/union into the owning
5804 // context and into the identifier resolver chain for name lookup
5805 // purposes.
5806 SmallVector<NamedDecl*, 2> Chain;
5807 Chain.push_back(Anon);
5809 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5810 Chain))
5811 Invalid = true;
5813 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5814 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5815 MangleNumberingContext *MCtx;
5816 Decl *ManglingContextDecl;
5817 std::tie(MCtx, ManglingContextDecl) =
5818 getCurrentMangleNumberContext(NewVD->getDeclContext());
5819 if (MCtx) {
5820 Context.setManglingNumber(
5821 NewVD, MCtx->getManglingNumber(
5822 NewVD, getMSManglingNumber(getLangOpts(), S)));
5823 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5828 if (Invalid)
5829 Anon->setInvalidDecl();
5831 return Anon;
5834 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5835 /// Microsoft C anonymous structure.
5836 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5837 /// Example:
5839 /// struct A { int a; };
5840 /// struct B { struct A; int b; };
5842 /// void foo() {
5843 /// B var;
5844 /// var.a = 3;
5845 /// }
5847 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5848 RecordDecl *Record) {
5849 assert(Record && "expected a record!");
5851 // Mock up a declarator.
5852 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5853 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5854 assert(TInfo && "couldn't build declarator info for anonymous struct");
5856 auto *ParentDecl = cast<RecordDecl>(CurContext);
5857 QualType RecTy = Context.getTypeDeclType(Record);
5859 // Create a declaration for this anonymous struct.
5860 NamedDecl *Anon =
5861 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5862 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5863 /*BitWidth=*/nullptr, /*Mutable=*/false,
5864 /*InitStyle=*/ICIS_NoInit);
5865 Anon->setImplicit();
5867 // Add the anonymous struct object to the current context.
5868 CurContext->addDecl(Anon);
5870 // Inject the members of the anonymous struct into the current
5871 // context and into the identifier resolver chain for name lookup
5872 // purposes.
5873 SmallVector<NamedDecl*, 2> Chain;
5874 Chain.push_back(Anon);
5876 RecordDecl *RecordDef = Record->getDefinition();
5877 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5878 diag::err_field_incomplete_or_sizeless) ||
5879 InjectAnonymousStructOrUnionMembers(
5880 *this, S, CurContext, RecordDef, AS_none,
5881 StorageClassSpecToVarDeclStorageClass(DS), Chain)) {
5882 Anon->setInvalidDecl();
5883 ParentDecl->setInvalidDecl();
5886 return Anon;
5889 /// GetNameForDeclarator - Determine the full declaration name for the
5890 /// given Declarator.
5891 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5892 return GetNameFromUnqualifiedId(D.getName());
5895 /// Retrieves the declaration name from a parsed unqualified-id.
5896 DeclarationNameInfo
5897 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5898 DeclarationNameInfo NameInfo;
5899 NameInfo.setLoc(Name.StartLocation);
5901 switch (Name.getKind()) {
5903 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5904 case UnqualifiedIdKind::IK_Identifier:
5905 NameInfo.setName(Name.Identifier);
5906 return NameInfo;
5908 case UnqualifiedIdKind::IK_DeductionGuideName: {
5909 // C++ [temp.deduct.guide]p3:
5910 // The simple-template-id shall name a class template specialization.
5911 // The template-name shall be the same identifier as the template-name
5912 // of the simple-template-id.
5913 // These together intend to imply that the template-name shall name a
5914 // class template.
5915 // FIXME: template<typename T> struct X {};
5916 // template<typename T> using Y = X<T>;
5917 // Y(int) -> Y<int>;
5918 // satisfies these rules but does not name a class template.
5919 TemplateName TN = Name.TemplateName.get().get();
5920 auto *Template = TN.getAsTemplateDecl();
5921 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5922 Diag(Name.StartLocation,
5923 diag::err_deduction_guide_name_not_class_template)
5924 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5925 if (Template)
5926 Diag(Template->getLocation(), diag::note_template_decl_here);
5927 return DeclarationNameInfo();
5930 NameInfo.setName(
5931 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5932 return NameInfo;
5935 case UnqualifiedIdKind::IK_OperatorFunctionId:
5936 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5937 Name.OperatorFunctionId.Operator));
5938 NameInfo.setCXXOperatorNameRange(SourceRange(
5939 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5940 return NameInfo;
5942 case UnqualifiedIdKind::IK_LiteralOperatorId:
5943 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5944 Name.Identifier));
5945 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5946 return NameInfo;
5948 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5949 TypeSourceInfo *TInfo;
5950 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5951 if (Ty.isNull())
5952 return DeclarationNameInfo();
5953 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5954 Context.getCanonicalType(Ty)));
5955 NameInfo.setNamedTypeInfo(TInfo);
5956 return NameInfo;
5959 case UnqualifiedIdKind::IK_ConstructorName: {
5960 TypeSourceInfo *TInfo;
5961 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5962 if (Ty.isNull())
5963 return DeclarationNameInfo();
5964 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5965 Context.getCanonicalType(Ty)));
5966 NameInfo.setNamedTypeInfo(TInfo);
5967 return NameInfo;
5970 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5971 // In well-formed code, we can only have a constructor
5972 // template-id that refers to the current context, so go there
5973 // to find the actual type being constructed.
5974 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5975 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5976 return DeclarationNameInfo();
5978 // Determine the type of the class being constructed.
5979 QualType CurClassType = Context.getTypeDeclType(CurClass);
5981 // FIXME: Check two things: that the template-id names the same type as
5982 // CurClassType, and that the template-id does not occur when the name
5983 // was qualified.
5985 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5986 Context.getCanonicalType(CurClassType)));
5987 // FIXME: should we retrieve TypeSourceInfo?
5988 NameInfo.setNamedTypeInfo(nullptr);
5989 return NameInfo;
5992 case UnqualifiedIdKind::IK_DestructorName: {
5993 TypeSourceInfo *TInfo;
5994 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5995 if (Ty.isNull())
5996 return DeclarationNameInfo();
5997 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5998 Context.getCanonicalType(Ty)));
5999 NameInfo.setNamedTypeInfo(TInfo);
6000 return NameInfo;
6003 case UnqualifiedIdKind::IK_TemplateId: {
6004 TemplateName TName = Name.TemplateId->Template.get();
6005 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6006 return Context.getNameForTemplate(TName, TNameLoc);
6009 } // switch (Name.getKind())
6011 llvm_unreachable("Unknown name kind");
6014 static QualType getCoreType(QualType Ty) {
6015 do {
6016 if (Ty->isPointerType() || Ty->isReferenceType())
6017 Ty = Ty->getPointeeType();
6018 else if (Ty->isArrayType())
6019 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6020 else
6021 return Ty.withoutLocalFastQualifiers();
6022 } while (true);
6025 /// hasSimilarParameters - Determine whether the C++ functions Declaration
6026 /// and Definition have "nearly" matching parameters. This heuristic is
6027 /// used to improve diagnostics in the case where an out-of-line function
6028 /// definition doesn't match any declaration within the class or namespace.
6029 /// Also sets Params to the list of indices to the parameters that differ
6030 /// between the declaration and the definition. If hasSimilarParameters
6031 /// returns true and Params is empty, then all of the parameters match.
6032 static bool hasSimilarParameters(ASTContext &Context,
6033 FunctionDecl *Declaration,
6034 FunctionDecl *Definition,
6035 SmallVectorImpl<unsigned> &Params) {
6036 Params.clear();
6037 if (Declaration->param_size() != Definition->param_size())
6038 return false;
6039 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6040 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6041 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6043 // The parameter types are identical
6044 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6045 continue;
6047 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6048 QualType DefParamBaseTy = getCoreType(DefParamTy);
6049 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6050 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6052 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6053 (DeclTyName && DeclTyName == DefTyName))
6054 Params.push_back(Idx);
6055 else // The two parameters aren't even close
6056 return false;
6059 return true;
6062 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6063 /// declarator needs to be rebuilt in the current instantiation.
6064 /// Any bits of declarator which appear before the name are valid for
6065 /// consideration here. That's specifically the type in the decl spec
6066 /// and the base type in any member-pointer chunks.
6067 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6068 DeclarationName Name) {
6069 // The types we specifically need to rebuild are:
6070 // - typenames, typeofs, and decltypes
6071 // - types which will become injected class names
6072 // Of course, we also need to rebuild any type referencing such a
6073 // type. It's safest to just say "dependent", but we call out a
6074 // few cases here.
6076 DeclSpec &DS = D.getMutableDeclSpec();
6077 switch (DS.getTypeSpecType()) {
6078 case DeclSpec::TST_typename:
6079 case DeclSpec::TST_typeofType:
6080 case DeclSpec::TST_typeof_unqualType:
6081 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6082 #include "clang/Basic/TransformTypeTraits.def"
6083 case DeclSpec::TST_atomic: {
6084 // Grab the type from the parser.
6085 TypeSourceInfo *TSI = nullptr;
6086 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6087 if (T.isNull() || !T->isInstantiationDependentType()) break;
6089 // Make sure there's a type source info. This isn't really much
6090 // of a waste; most dependent types should have type source info
6091 // attached already.
6092 if (!TSI)
6093 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
6095 // Rebuild the type in the current instantiation.
6096 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
6097 if (!TSI) return true;
6099 // Store the new type back in the decl spec.
6100 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6101 DS.UpdateTypeRep(LocType);
6102 break;
6105 case DeclSpec::TST_decltype:
6106 case DeclSpec::TST_typeof_unqualExpr:
6107 case DeclSpec::TST_typeofExpr: {
6108 Expr *E = DS.getRepAsExpr();
6109 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6110 if (Result.isInvalid()) return true;
6111 DS.UpdateExprRep(Result.get());
6112 break;
6115 default:
6116 // Nothing to do for these decl specs.
6117 break;
6120 // It doesn't matter what order we do this in.
6121 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6122 DeclaratorChunk &Chunk = D.getTypeObject(I);
6124 // The only type information in the declarator which can come
6125 // before the declaration name is the base type of a member
6126 // pointer.
6127 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6128 continue;
6130 // Rebuild the scope specifier in-place.
6131 CXXScopeSpec &SS = Chunk.Mem.Scope();
6132 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6133 return true;
6136 return false;
6139 /// Returns true if the declaration is declared in a system header or from a
6140 /// system macro.
6141 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6142 return SM.isInSystemHeader(D->getLocation()) ||
6143 SM.isInSystemMacro(D->getLocation());
6146 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6147 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6148 // of system decl.
6149 if (D->getPreviousDecl() || D->isImplicit())
6150 return;
6151 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6152 if (Status != ReservedIdentifierStatus::NotReserved &&
6153 !isFromSystemHeader(Context.getSourceManager(), D)) {
6154 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6155 << D << static_cast<int>(Status);
6159 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6160 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6162 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6163 // declaration only if the `bind_to_declaration` extension is set.
6164 SmallVector<FunctionDecl *, 4> Bases;
6165 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
6166 if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
6167 implementation_extension_bind_to_declaration))
6168 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6169 S, D, MultiTemplateParamsArg(), Bases);
6171 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
6173 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6174 Dcl && Dcl->getDeclContext()->isFileContext())
6175 Dcl->setTopLevelDeclInObjCContainer();
6177 if (!Bases.empty())
6178 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
6180 return Dcl;
6183 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6184 /// If T is the name of a class, then each of the following shall have a
6185 /// name different from T:
6186 /// - every static data member of class T;
6187 /// - every member function of class T
6188 /// - every member of class T that is itself a type;
6189 /// \returns true if the declaration name violates these rules.
6190 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6191 DeclarationNameInfo NameInfo) {
6192 DeclarationName Name = NameInfo.getName();
6194 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6195 while (Record && Record->isAnonymousStructOrUnion())
6196 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6197 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6198 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6199 return true;
6202 return false;
6205 /// Diagnose a declaration whose declarator-id has the given
6206 /// nested-name-specifier.
6208 /// \param SS The nested-name-specifier of the declarator-id.
6210 /// \param DC The declaration context to which the nested-name-specifier
6211 /// resolves.
6213 /// \param Name The name of the entity being declared.
6215 /// \param Loc The location of the name of the entity being declared.
6217 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
6218 /// we're declaring an explicit / partial specialization / instantiation.
6220 /// \returns true if we cannot safely recover from this error, false otherwise.
6221 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6222 DeclarationName Name,
6223 SourceLocation Loc, bool IsTemplateId) {
6224 DeclContext *Cur = CurContext;
6225 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6226 Cur = Cur->getParent();
6228 // If the user provided a superfluous scope specifier that refers back to the
6229 // class in which the entity is already declared, diagnose and ignore it.
6231 // class X {
6232 // void X::f();
6233 // };
6235 // Note, it was once ill-formed to give redundant qualification in all
6236 // contexts, but that rule was removed by DR482.
6237 if (Cur->Equals(DC)) {
6238 if (Cur->isRecord()) {
6239 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6240 : diag::err_member_extra_qualification)
6241 << Name << FixItHint::CreateRemoval(SS.getRange());
6242 SS.clear();
6243 } else {
6244 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6246 return false;
6249 // Check whether the qualifying scope encloses the scope of the original
6250 // declaration. For a template-id, we perform the checks in
6251 // CheckTemplateSpecializationScope.
6252 if (!Cur->Encloses(DC) && !IsTemplateId) {
6253 if (Cur->isRecord())
6254 Diag(Loc, diag::err_member_qualification)
6255 << Name << SS.getRange();
6256 else if (isa<TranslationUnitDecl>(DC))
6257 Diag(Loc, diag::err_invalid_declarator_global_scope)
6258 << Name << SS.getRange();
6259 else if (isa<FunctionDecl>(Cur))
6260 Diag(Loc, diag::err_invalid_declarator_in_function)
6261 << Name << SS.getRange();
6262 else if (isa<BlockDecl>(Cur))
6263 Diag(Loc, diag::err_invalid_declarator_in_block)
6264 << Name << SS.getRange();
6265 else if (isa<ExportDecl>(Cur)) {
6266 if (!isa<NamespaceDecl>(DC))
6267 Diag(Loc, diag::err_export_non_namespace_scope_name)
6268 << Name << SS.getRange();
6269 else
6270 // The cases that DC is not NamespaceDecl should be handled in
6271 // CheckRedeclarationExported.
6272 return false;
6273 } else
6274 Diag(Loc, diag::err_invalid_declarator_scope)
6275 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6277 return true;
6280 if (Cur->isRecord()) {
6281 // Cannot qualify members within a class.
6282 Diag(Loc, diag::err_member_qualification)
6283 << Name << SS.getRange();
6284 SS.clear();
6286 // C++ constructors and destructors with incorrect scopes can break
6287 // our AST invariants by having the wrong underlying types. If
6288 // that's the case, then drop this declaration entirely.
6289 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6290 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6291 !Context.hasSameType(Name.getCXXNameType(),
6292 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6293 return true;
6295 return false;
6298 // C++11 [dcl.meaning]p1:
6299 // [...] "The nested-name-specifier of the qualified declarator-id shall
6300 // not begin with a decltype-specifer"
6301 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6302 while (SpecLoc.getPrefix())
6303 SpecLoc = SpecLoc.getPrefix();
6304 if (isa_and_nonnull<DecltypeType>(
6305 SpecLoc.getNestedNameSpecifier()->getAsType()))
6306 Diag(Loc, diag::err_decltype_in_declarator)
6307 << SpecLoc.getTypeLoc().getSourceRange();
6309 return false;
6312 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6313 MultiTemplateParamsArg TemplateParamLists) {
6314 // TODO: consider using NameInfo for diagnostic.
6315 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6316 DeclarationName Name = NameInfo.getName();
6318 // All of these full declarators require an identifier. If it doesn't have
6319 // one, the ParsedFreeStandingDeclSpec action should be used.
6320 if (D.isDecompositionDeclarator()) {
6321 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6322 } else if (!Name) {
6323 if (!D.isInvalidType()) // Reject this if we think it is valid.
6324 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6325 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6326 return nullptr;
6327 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6328 return nullptr;
6330 // The scope passed in may not be a decl scope. Zip up the scope tree until
6331 // we find one that is.
6332 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6333 (S->getFlags() & Scope::TemplateParamScope) != 0)
6334 S = S->getParent();
6336 DeclContext *DC = CurContext;
6337 if (D.getCXXScopeSpec().isInvalid())
6338 D.setInvalidType();
6339 else if (D.getCXXScopeSpec().isSet()) {
6340 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6341 UPPC_DeclarationQualifier))
6342 return nullptr;
6344 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6345 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6346 if (!DC || isa<EnumDecl>(DC)) {
6347 // If we could not compute the declaration context, it's because the
6348 // declaration context is dependent but does not refer to a class,
6349 // class template, or class template partial specialization. Complain
6350 // and return early, to avoid the coming semantic disaster.
6351 Diag(D.getIdentifierLoc(),
6352 diag::err_template_qualified_declarator_no_match)
6353 << D.getCXXScopeSpec().getScopeRep()
6354 << D.getCXXScopeSpec().getRange();
6355 return nullptr;
6357 bool IsDependentContext = DC->isDependentContext();
6359 if (!IsDependentContext &&
6360 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6361 return nullptr;
6363 // If a class is incomplete, do not parse entities inside it.
6364 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6365 Diag(D.getIdentifierLoc(),
6366 diag::err_member_def_undefined_record)
6367 << Name << DC << D.getCXXScopeSpec().getRange();
6368 return nullptr;
6370 if (!D.getDeclSpec().isFriendSpecified()) {
6371 if (diagnoseQualifiedDeclaration(
6372 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6373 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6374 if (DC->isRecord())
6375 return nullptr;
6377 D.setInvalidType();
6381 // Check whether we need to rebuild the type of the given
6382 // declaration in the current instantiation.
6383 if (EnteringContext && IsDependentContext &&
6384 TemplateParamLists.size() != 0) {
6385 ContextRAII SavedContext(*this, DC);
6386 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6387 D.setInvalidType();
6391 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6392 QualType R = TInfo->getType();
6394 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6395 UPPC_DeclarationType))
6396 D.setInvalidType();
6398 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6399 forRedeclarationInCurContext());
6401 // See if this is a redefinition of a variable in the same scope.
6402 if (!D.getCXXScopeSpec().isSet()) {
6403 bool IsLinkageLookup = false;
6404 bool CreateBuiltins = false;
6406 // If the declaration we're planning to build will be a function
6407 // or object with linkage, then look for another declaration with
6408 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6410 // If the declaration we're planning to build will be declared with
6411 // external linkage in the translation unit, create any builtin with
6412 // the same name.
6413 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6414 /* Do nothing*/;
6415 else if (CurContext->isFunctionOrMethod() &&
6416 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6417 R->isFunctionType())) {
6418 IsLinkageLookup = true;
6419 CreateBuiltins =
6420 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6421 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6422 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6423 CreateBuiltins = true;
6425 if (IsLinkageLookup) {
6426 Previous.clear(LookupRedeclarationWithLinkage);
6427 Previous.setRedeclarationKind(ForExternalRedeclaration);
6430 LookupName(Previous, S, CreateBuiltins);
6431 } else { // Something like "int foo::x;"
6432 LookupQualifiedName(Previous, DC);
6434 // C++ [dcl.meaning]p1:
6435 // When the declarator-id is qualified, the declaration shall refer to a
6436 // previously declared member of the class or namespace to which the
6437 // qualifier refers (or, in the case of a namespace, of an element of the
6438 // inline namespace set of that namespace (7.3.1)) or to a specialization
6439 // thereof; [...]
6441 // Note that we already checked the context above, and that we do not have
6442 // enough information to make sure that Previous contains the declaration
6443 // we want to match. For example, given:
6445 // class X {
6446 // void f();
6447 // void f(float);
6448 // };
6450 // void X::f(int) { } // ill-formed
6452 // In this case, Previous will point to the overload set
6453 // containing the two f's declared in X, but neither of them
6454 // matches.
6456 RemoveUsingDecls(Previous);
6459 if (Previous.isSingleResult() &&
6460 Previous.getFoundDecl()->isTemplateParameter()) {
6461 // Maybe we will complain about the shadowed template parameter.
6462 if (!D.isInvalidType())
6463 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6464 Previous.getFoundDecl());
6466 // Just pretend that we didn't see the previous declaration.
6467 Previous.clear();
6470 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6471 // Forget that the previous declaration is the injected-class-name.
6472 Previous.clear();
6474 // In C++, the previous declaration we find might be a tag type
6475 // (class or enum). In this case, the new declaration will hide the
6476 // tag type. Note that this applies to functions, function templates, and
6477 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6478 if (Previous.isSingleTagDecl() &&
6479 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6480 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6481 Previous.clear();
6483 // Check that there are no default arguments other than in the parameters
6484 // of a function declaration (C++ only).
6485 if (getLangOpts().CPlusPlus)
6486 CheckExtraCXXDefaultArguments(D);
6488 NamedDecl *New;
6490 bool AddToScope = true;
6491 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6492 if (TemplateParamLists.size()) {
6493 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6494 return nullptr;
6497 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6498 } else if (R->isFunctionType()) {
6499 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6500 TemplateParamLists,
6501 AddToScope);
6502 } else {
6503 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6504 AddToScope);
6507 if (!New)
6508 return nullptr;
6510 // If this has an identifier and is not a function template specialization,
6511 // add it to the scope stack.
6512 if (New->getDeclName() && AddToScope)
6513 PushOnScopeChains(New, S);
6515 if (isInOpenMPDeclareTargetContext())
6516 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6518 return New;
6521 /// Helper method to turn variable array types into constant array
6522 /// types in certain situations which would otherwise be errors (for
6523 /// GCC compatibility).
6524 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6525 ASTContext &Context,
6526 bool &SizeIsNegative,
6527 llvm::APSInt &Oversized) {
6528 // This method tries to turn a variable array into a constant
6529 // array even when the size isn't an ICE. This is necessary
6530 // for compatibility with code that depends on gcc's buggy
6531 // constant expression folding, like struct {char x[(int)(char*)2];}
6532 SizeIsNegative = false;
6533 Oversized = 0;
6535 if (T->isDependentType())
6536 return QualType();
6538 QualifierCollector Qs;
6539 const Type *Ty = Qs.strip(T);
6541 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6542 QualType Pointee = PTy->getPointeeType();
6543 QualType FixedType =
6544 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6545 Oversized);
6546 if (FixedType.isNull()) return FixedType;
6547 FixedType = Context.getPointerType(FixedType);
6548 return Qs.apply(Context, FixedType);
6550 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6551 QualType Inner = PTy->getInnerType();
6552 QualType FixedType =
6553 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6554 Oversized);
6555 if (FixedType.isNull()) return FixedType;
6556 FixedType = Context.getParenType(FixedType);
6557 return Qs.apply(Context, FixedType);
6560 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6561 if (!VLATy)
6562 return QualType();
6564 QualType ElemTy = VLATy->getElementType();
6565 if (ElemTy->isVariablyModifiedType()) {
6566 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6567 SizeIsNegative, Oversized);
6568 if (ElemTy.isNull())
6569 return QualType();
6572 Expr::EvalResult Result;
6573 if (!VLATy->getSizeExpr() ||
6574 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6575 return QualType();
6577 llvm::APSInt Res = Result.Val.getInt();
6579 // Check whether the array size is negative.
6580 if (Res.isSigned() && Res.isNegative()) {
6581 SizeIsNegative = true;
6582 return QualType();
6585 // Check whether the array is too large to be addressed.
6586 unsigned ActiveSizeBits =
6587 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6588 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6589 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6590 : Res.getActiveBits();
6591 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6592 Oversized = Res;
6593 return QualType();
6596 QualType FoldedArrayType = Context.getConstantArrayType(
6597 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6598 return Qs.apply(Context, FoldedArrayType);
6601 static void
6602 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6603 SrcTL = SrcTL.getUnqualifiedLoc();
6604 DstTL = DstTL.getUnqualifiedLoc();
6605 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6606 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6607 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6608 DstPTL.getPointeeLoc());
6609 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6610 return;
6612 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6613 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6614 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6615 DstPTL.getInnerLoc());
6616 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6617 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6618 return;
6620 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6621 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6622 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6623 TypeLoc DstElemTL = DstATL.getElementLoc();
6624 if (VariableArrayTypeLoc SrcElemATL =
6625 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6626 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6627 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6628 } else {
6629 DstElemTL.initializeFullCopy(SrcElemTL);
6631 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6632 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6633 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6636 /// Helper method to turn variable array types into constant array
6637 /// types in certain situations which would otherwise be errors (for
6638 /// GCC compatibility).
6639 static TypeSourceInfo*
6640 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6641 ASTContext &Context,
6642 bool &SizeIsNegative,
6643 llvm::APSInt &Oversized) {
6644 QualType FixedTy
6645 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6646 SizeIsNegative, Oversized);
6647 if (FixedTy.isNull())
6648 return nullptr;
6649 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6650 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6651 FixedTInfo->getTypeLoc());
6652 return FixedTInfo;
6655 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6656 /// true if we were successful.
6657 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6658 QualType &T, SourceLocation Loc,
6659 unsigned FailedFoldDiagID) {
6660 bool SizeIsNegative;
6661 llvm::APSInt Oversized;
6662 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6663 TInfo, Context, SizeIsNegative, Oversized);
6664 if (FixedTInfo) {
6665 Diag(Loc, diag::ext_vla_folded_to_constant);
6666 TInfo = FixedTInfo;
6667 T = FixedTInfo->getType();
6668 return true;
6671 if (SizeIsNegative)
6672 Diag(Loc, diag::err_typecheck_negative_array_size);
6673 else if (Oversized.getBoolValue())
6674 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6675 else if (FailedFoldDiagID)
6676 Diag(Loc, FailedFoldDiagID);
6677 return false;
6680 /// Register the given locally-scoped extern "C" declaration so
6681 /// that it can be found later for redeclarations. We include any extern "C"
6682 /// declaration that is not visible in the translation unit here, not just
6683 /// function-scope declarations.
6684 void
6685 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6686 if (!getLangOpts().CPlusPlus &&
6687 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6688 // Don't need to track declarations in the TU in C.
6689 return;
6691 // Note that we have a locally-scoped external with this name.
6692 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6695 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6696 // FIXME: We can have multiple results via __attribute__((overloadable)).
6697 auto Result = Context.getExternCContextDecl()->lookup(Name);
6698 return Result.empty() ? nullptr : *Result.begin();
6701 /// Diagnose function specifiers on a declaration of an identifier that
6702 /// does not identify a function.
6703 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6704 // FIXME: We should probably indicate the identifier in question to avoid
6705 // confusion for constructs like "virtual int a(), b;"
6706 if (DS.isVirtualSpecified())
6707 Diag(DS.getVirtualSpecLoc(),
6708 diag::err_virtual_non_function);
6710 if (DS.hasExplicitSpecifier())
6711 Diag(DS.getExplicitSpecLoc(),
6712 diag::err_explicit_non_function);
6714 if (DS.isNoreturnSpecified())
6715 Diag(DS.getNoreturnSpecLoc(),
6716 diag::err_noreturn_non_function);
6719 NamedDecl*
6720 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6721 TypeSourceInfo *TInfo, LookupResult &Previous) {
6722 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6723 if (D.getCXXScopeSpec().isSet()) {
6724 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6725 << D.getCXXScopeSpec().getRange();
6726 D.setInvalidType();
6727 // Pretend we didn't see the scope specifier.
6728 DC = CurContext;
6729 Previous.clear();
6732 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6734 if (D.getDeclSpec().isInlineSpecified())
6735 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6736 << getLangOpts().CPlusPlus17;
6737 if (D.getDeclSpec().hasConstexprSpecifier())
6738 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6739 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6741 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6742 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6743 Diag(D.getName().StartLocation,
6744 diag::err_deduction_guide_invalid_specifier)
6745 << "typedef";
6746 else
6747 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6748 << D.getName().getSourceRange();
6749 return nullptr;
6752 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6753 if (!NewTD) return nullptr;
6755 // Handle attributes prior to checking for duplicates in MergeVarDecl
6756 ProcessDeclAttributes(S, NewTD, D);
6758 CheckTypedefForVariablyModifiedType(S, NewTD);
6760 bool Redeclaration = D.isRedeclaration();
6761 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6762 D.setRedeclaration(Redeclaration);
6763 return ND;
6766 void
6767 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6768 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6769 // then it shall have block scope.
6770 // Note that variably modified types must be fixed before merging the decl so
6771 // that redeclarations will match.
6772 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6773 QualType T = TInfo->getType();
6774 if (T->isVariablyModifiedType()) {
6775 setFunctionHasBranchProtectedScope();
6777 if (S->getFnParent() == nullptr) {
6778 bool SizeIsNegative;
6779 llvm::APSInt Oversized;
6780 TypeSourceInfo *FixedTInfo =
6781 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6782 SizeIsNegative,
6783 Oversized);
6784 if (FixedTInfo) {
6785 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6786 NewTD->setTypeSourceInfo(FixedTInfo);
6787 } else {
6788 if (SizeIsNegative)
6789 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6790 else if (T->isVariableArrayType())
6791 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6792 else if (Oversized.getBoolValue())
6793 Diag(NewTD->getLocation(), diag::err_array_too_large)
6794 << toString(Oversized, 10);
6795 else
6796 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6797 NewTD->setInvalidDecl();
6803 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6804 /// declares a typedef-name, either using the 'typedef' type specifier or via
6805 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6806 NamedDecl*
6807 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6808 LookupResult &Previous, bool &Redeclaration) {
6810 // Find the shadowed declaration before filtering for scope.
6811 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6813 // Merge the decl with the existing one if appropriate. If the decl is
6814 // in an outer scope, it isn't the same thing.
6815 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6816 /*AllowInlineNamespace*/false);
6817 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6818 if (!Previous.empty()) {
6819 Redeclaration = true;
6820 MergeTypedefNameDecl(S, NewTD, Previous);
6821 } else {
6822 inferGslPointerAttribute(NewTD);
6825 if (ShadowedDecl && !Redeclaration)
6826 CheckShadow(NewTD, ShadowedDecl, Previous);
6828 // If this is the C FILE type, notify the AST context.
6829 if (IdentifierInfo *II = NewTD->getIdentifier())
6830 if (!NewTD->isInvalidDecl() &&
6831 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6832 switch (II->getInterestingIdentifierID()) {
6833 case tok::InterestingIdentifierKind::FILE:
6834 Context.setFILEDecl(NewTD);
6835 break;
6836 case tok::InterestingIdentifierKind::jmp_buf:
6837 Context.setjmp_bufDecl(NewTD);
6838 break;
6839 case tok::InterestingIdentifierKind::sigjmp_buf:
6840 Context.setsigjmp_bufDecl(NewTD);
6841 break;
6842 case tok::InterestingIdentifierKind::ucontext_t:
6843 Context.setucontext_tDecl(NewTD);
6844 break;
6845 case tok::InterestingIdentifierKind::float_t:
6846 case tok::InterestingIdentifierKind::double_t:
6847 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6848 break;
6849 default:
6850 break;
6854 return NewTD;
6857 /// Determines whether the given declaration is an out-of-scope
6858 /// previous declaration.
6860 /// This routine should be invoked when name lookup has found a
6861 /// previous declaration (PrevDecl) that is not in the scope where a
6862 /// new declaration by the same name is being introduced. If the new
6863 /// declaration occurs in a local scope, previous declarations with
6864 /// linkage may still be considered previous declarations (C99
6865 /// 6.2.2p4-5, C++ [basic.link]p6).
6867 /// \param PrevDecl the previous declaration found by name
6868 /// lookup
6870 /// \param DC the context in which the new declaration is being
6871 /// declared.
6873 /// \returns true if PrevDecl is an out-of-scope previous declaration
6874 /// for a new delcaration with the same name.
6875 static bool
6876 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6877 ASTContext &Context) {
6878 if (!PrevDecl)
6879 return false;
6881 if (!PrevDecl->hasLinkage())
6882 return false;
6884 if (Context.getLangOpts().CPlusPlus) {
6885 // C++ [basic.link]p6:
6886 // If there is a visible declaration of an entity with linkage
6887 // having the same name and type, ignoring entities declared
6888 // outside the innermost enclosing namespace scope, the block
6889 // scope declaration declares that same entity and receives the
6890 // linkage of the previous declaration.
6891 DeclContext *OuterContext = DC->getRedeclContext();
6892 if (!OuterContext->isFunctionOrMethod())
6893 // This rule only applies to block-scope declarations.
6894 return false;
6896 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6897 if (PrevOuterContext->isRecord())
6898 // We found a member function: ignore it.
6899 return false;
6901 // Find the innermost enclosing namespace for the new and
6902 // previous declarations.
6903 OuterContext = OuterContext->getEnclosingNamespaceContext();
6904 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6906 // The previous declaration is in a different namespace, so it
6907 // isn't the same function.
6908 if (!OuterContext->Equals(PrevOuterContext))
6909 return false;
6912 return true;
6915 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6916 CXXScopeSpec &SS = D.getCXXScopeSpec();
6917 if (!SS.isSet()) return;
6918 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6921 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6922 QualType type = decl->getType();
6923 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6924 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6925 // Various kinds of declaration aren't allowed to be __autoreleasing.
6926 unsigned kind = -1U;
6927 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6928 if (var->hasAttr<BlocksAttr>())
6929 kind = 0; // __block
6930 else if (!var->hasLocalStorage())
6931 kind = 1; // global
6932 } else if (isa<ObjCIvarDecl>(decl)) {
6933 kind = 3; // ivar
6934 } else if (isa<FieldDecl>(decl)) {
6935 kind = 2; // field
6938 if (kind != -1U) {
6939 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6940 << kind;
6942 } else if (lifetime == Qualifiers::OCL_None) {
6943 // Try to infer lifetime.
6944 if (!type->isObjCLifetimeType())
6945 return false;
6947 lifetime = type->getObjCARCImplicitLifetime();
6948 type = Context.getLifetimeQualifiedType(type, lifetime);
6949 decl->setType(type);
6952 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6953 // Thread-local variables cannot have lifetime.
6954 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6955 var->getTLSKind()) {
6956 Diag(var->getLocation(), diag::err_arc_thread_ownership)
6957 << var->getType();
6958 return true;
6962 return false;
6965 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6966 if (Decl->getType().hasAddressSpace())
6967 return;
6968 if (Decl->getType()->isDependentType())
6969 return;
6970 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6971 QualType Type = Var->getType();
6972 if (Type->isSamplerT() || Type->isVoidType())
6973 return;
6974 LangAS ImplAS = LangAS::opencl_private;
6975 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6976 // __opencl_c_program_scope_global_variables feature, the address space
6977 // for a variable at program scope or a static or extern variable inside
6978 // a function are inferred to be __global.
6979 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6980 Var->hasGlobalStorage())
6981 ImplAS = LangAS::opencl_global;
6982 // If the original type from a decayed type is an array type and that array
6983 // type has no address space yet, deduce it now.
6984 if (auto DT = dyn_cast<DecayedType>(Type)) {
6985 auto OrigTy = DT->getOriginalType();
6986 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6987 // Add the address space to the original array type and then propagate
6988 // that to the element type through `getAsArrayType`.
6989 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6990 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6991 // Re-generate the decayed type.
6992 Type = Context.getDecayedType(OrigTy);
6995 Type = Context.getAddrSpaceQualType(Type, ImplAS);
6996 // Apply any qualifiers (including address space) from the array type to
6997 // the element type. This implements C99 6.7.3p8: "If the specification of
6998 // an array type includes any type qualifiers, the element type is so
6999 // qualified, not the array type."
7000 if (Type->isArrayType())
7001 Type = QualType(Context.getAsArrayType(Type), 0);
7002 Decl->setType(Type);
7006 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7007 // Ensure that an auto decl is deduced otherwise the checks below might cache
7008 // the wrong linkage.
7009 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7011 // 'weak' only applies to declarations with external linkage.
7012 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7013 if (!ND.isExternallyVisible()) {
7014 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7015 ND.dropAttr<WeakAttr>();
7018 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7019 if (ND.isExternallyVisible()) {
7020 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7021 ND.dropAttr<WeakRefAttr>();
7022 ND.dropAttr<AliasAttr>();
7026 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7027 if (VD->hasInit()) {
7028 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7029 assert(VD->isThisDeclarationADefinition() &&
7030 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7031 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7032 VD->dropAttr<AliasAttr>();
7037 // 'selectany' only applies to externally visible variable declarations.
7038 // It does not apply to functions.
7039 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7040 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7041 S.Diag(Attr->getLocation(),
7042 diag::err_attribute_selectany_non_extern_data);
7043 ND.dropAttr<SelectAnyAttr>();
7047 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7048 auto *VD = dyn_cast<VarDecl>(&ND);
7049 bool IsAnonymousNS = false;
7050 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7051 if (VD) {
7052 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7053 while (NS && !IsAnonymousNS) {
7054 IsAnonymousNS = NS->isAnonymousNamespace();
7055 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7058 // dll attributes require external linkage. Static locals may have external
7059 // linkage but still cannot be explicitly imported or exported.
7060 // In Microsoft mode, a variable defined in anonymous namespace must have
7061 // external linkage in order to be exported.
7062 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7063 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7064 (!AnonNSInMicrosoftMode &&
7065 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7066 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7067 << &ND << Attr;
7068 ND.setInvalidDecl();
7072 // Check the attributes on the function type, if any.
7073 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7074 // Don't declare this variable in the second operand of the for-statement;
7075 // GCC miscompiles that by ending its lifetime before evaluating the
7076 // third operand. See gcc.gnu.org/PR86769.
7077 AttributedTypeLoc ATL;
7078 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7079 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7080 TL = ATL.getModifiedLoc()) {
7081 // The [[lifetimebound]] attribute can be applied to the implicit object
7082 // parameter of a non-static member function (other than a ctor or dtor)
7083 // by applying it to the function type.
7084 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7085 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7086 if (!MD || MD->isStatic()) {
7087 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7088 << !MD << A->getRange();
7089 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7090 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7091 << isa<CXXDestructorDecl>(MD) << A->getRange();
7098 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7099 NamedDecl *NewDecl,
7100 bool IsSpecialization,
7101 bool IsDefinition) {
7102 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7103 return;
7105 bool IsTemplate = false;
7106 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7107 OldDecl = OldTD->getTemplatedDecl();
7108 IsTemplate = true;
7109 if (!IsSpecialization)
7110 IsDefinition = false;
7112 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7113 NewDecl = NewTD->getTemplatedDecl();
7114 IsTemplate = true;
7117 if (!OldDecl || !NewDecl)
7118 return;
7120 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7121 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7122 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7123 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7125 // dllimport and dllexport are inheritable attributes so we have to exclude
7126 // inherited attribute instances.
7127 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7128 (NewExportAttr && !NewExportAttr->isInherited());
7130 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7131 // the only exception being explicit specializations.
7132 // Implicitly generated declarations are also excluded for now because there
7133 // is no other way to switch these to use dllimport or dllexport.
7134 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7136 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7137 // Allow with a warning for free functions and global variables.
7138 bool JustWarn = false;
7139 if (!OldDecl->isCXXClassMember()) {
7140 auto *VD = dyn_cast<VarDecl>(OldDecl);
7141 if (VD && !VD->getDescribedVarTemplate())
7142 JustWarn = true;
7143 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7144 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7145 JustWarn = true;
7148 // We cannot change a declaration that's been used because IR has already
7149 // been emitted. Dllimported functions will still work though (modulo
7150 // address equality) as they can use the thunk.
7151 if (OldDecl->isUsed())
7152 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7153 JustWarn = false;
7155 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7156 : diag::err_attribute_dll_redeclaration;
7157 S.Diag(NewDecl->getLocation(), DiagID)
7158 << NewDecl
7159 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7160 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7161 if (!JustWarn) {
7162 NewDecl->setInvalidDecl();
7163 return;
7167 // A redeclaration is not allowed to drop a dllimport attribute, the only
7168 // exceptions being inline function definitions (except for function
7169 // templates), local extern declarations, qualified friend declarations or
7170 // special MSVC extension: in the last case, the declaration is treated as if
7171 // it were marked dllexport.
7172 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7173 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7174 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7175 // Ignore static data because out-of-line definitions are diagnosed
7176 // separately.
7177 IsStaticDataMember = VD->isStaticDataMember();
7178 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7179 VarDecl::DeclarationOnly;
7180 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7181 IsInline = FD->isInlined();
7182 IsQualifiedFriend = FD->getQualifier() &&
7183 FD->getFriendObjectKind() == Decl::FOK_Declared;
7186 if (OldImportAttr && !HasNewAttr &&
7187 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7188 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7189 if (IsMicrosoftABI && IsDefinition) {
7190 if (IsSpecialization) {
7191 S.Diag(
7192 NewDecl->getLocation(),
7193 diag::err_attribute_dllimport_function_specialization_definition);
7194 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7195 NewDecl->dropAttr<DLLImportAttr>();
7196 } else {
7197 S.Diag(NewDecl->getLocation(),
7198 diag::warn_redeclaration_without_import_attribute)
7199 << NewDecl;
7200 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7201 NewDecl->dropAttr<DLLImportAttr>();
7202 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7203 S.Context, NewImportAttr->getRange()));
7205 } else if (IsMicrosoftABI && IsSpecialization) {
7206 assert(!IsDefinition);
7207 // MSVC allows this. Keep the inherited attribute.
7208 } else {
7209 S.Diag(NewDecl->getLocation(),
7210 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7211 << NewDecl << OldImportAttr;
7212 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7213 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7214 OldDecl->dropAttr<DLLImportAttr>();
7215 NewDecl->dropAttr<DLLImportAttr>();
7217 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7218 // In MinGW, seeing a function declared inline drops the dllimport
7219 // attribute.
7220 OldDecl->dropAttr<DLLImportAttr>();
7221 NewDecl->dropAttr<DLLImportAttr>();
7222 S.Diag(NewDecl->getLocation(),
7223 diag::warn_dllimport_dropped_from_inline_function)
7224 << NewDecl << OldImportAttr;
7227 // A specialization of a class template member function is processed here
7228 // since it's a redeclaration. If the parent class is dllexport, the
7229 // specialization inherits that attribute. This doesn't happen automatically
7230 // since the parent class isn't instantiated until later.
7231 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7232 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7233 !NewImportAttr && !NewExportAttr) {
7234 if (const DLLExportAttr *ParentExportAttr =
7235 MD->getParent()->getAttr<DLLExportAttr>()) {
7236 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7237 NewAttr->setInherited(true);
7238 NewDecl->addAttr(NewAttr);
7244 /// Given that we are within the definition of the given function,
7245 /// will that definition behave like C99's 'inline', where the
7246 /// definition is discarded except for optimization purposes?
7247 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7248 // Try to avoid calling GetGVALinkageForFunction.
7250 // All cases of this require the 'inline' keyword.
7251 if (!FD->isInlined()) return false;
7253 // This is only possible in C++ with the gnu_inline attribute.
7254 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7255 return false;
7257 // Okay, go ahead and call the relatively-more-expensive function.
7258 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7261 /// Determine whether a variable is extern "C" prior to attaching
7262 /// an initializer. We can't just call isExternC() here, because that
7263 /// will also compute and cache whether the declaration is externally
7264 /// visible, which might change when we attach the initializer.
7266 /// This can only be used if the declaration is known to not be a
7267 /// redeclaration of an internal linkage declaration.
7269 /// For instance:
7271 /// auto x = []{};
7273 /// Attaching the initializer here makes this declaration not externally
7274 /// visible, because its type has internal linkage.
7276 /// FIXME: This is a hack.
7277 template<typename T>
7278 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7279 if (S.getLangOpts().CPlusPlus) {
7280 // In C++, the overloadable attribute negates the effects of extern "C".
7281 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7282 return false;
7284 // So do CUDA's host/device attributes.
7285 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7286 D->template hasAttr<CUDAHostAttr>()))
7287 return false;
7289 return D->isExternC();
7292 static bool shouldConsiderLinkage(const VarDecl *VD) {
7293 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7294 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7295 isa<OMPDeclareMapperDecl>(DC))
7296 return VD->hasExternalStorage();
7297 if (DC->isFileContext())
7298 return true;
7299 if (DC->isRecord())
7300 return false;
7301 if (DC->getDeclKind() == Decl::HLSLBuffer)
7302 return false;
7304 if (isa<RequiresExprBodyDecl>(DC))
7305 return false;
7306 llvm_unreachable("Unexpected context");
7309 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7310 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7311 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7312 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7313 return true;
7314 if (DC->isRecord())
7315 return false;
7316 llvm_unreachable("Unexpected context");
7319 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7320 ParsedAttr::Kind Kind) {
7321 // Check decl attributes on the DeclSpec.
7322 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7323 return true;
7325 // Walk the declarator structure, checking decl attributes that were in a type
7326 // position to the decl itself.
7327 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7328 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7329 return true;
7332 // Finally, check attributes on the decl itself.
7333 return PD.getAttributes().hasAttribute(Kind) ||
7334 PD.getDeclarationAttributes().hasAttribute(Kind);
7337 /// Adjust the \c DeclContext for a function or variable that might be a
7338 /// function-local external declaration.
7339 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7340 if (!DC->isFunctionOrMethod())
7341 return false;
7343 // If this is a local extern function or variable declared within a function
7344 // template, don't add it into the enclosing namespace scope until it is
7345 // instantiated; it might have a dependent type right now.
7346 if (DC->isDependentContext())
7347 return true;
7349 // C++11 [basic.link]p7:
7350 // When a block scope declaration of an entity with linkage is not found to
7351 // refer to some other declaration, then that entity is a member of the
7352 // innermost enclosing namespace.
7354 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7355 // semantically-enclosing namespace, not a lexically-enclosing one.
7356 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7357 DC = DC->getParent();
7358 return true;
7361 /// Returns true if given declaration has external C language linkage.
7362 static bool isDeclExternC(const Decl *D) {
7363 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7364 return FD->isExternC();
7365 if (const auto *VD = dyn_cast<VarDecl>(D))
7366 return VD->isExternC();
7368 llvm_unreachable("Unknown type of decl!");
7371 /// Returns true if there hasn't been any invalid type diagnosed.
7372 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7373 DeclContext *DC = NewVD->getDeclContext();
7374 QualType R = NewVD->getType();
7376 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7377 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7378 // argument.
7379 if (R->isImageType() || R->isPipeType()) {
7380 Se.Diag(NewVD->getLocation(),
7381 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7382 << R;
7383 NewVD->setInvalidDecl();
7384 return false;
7387 // OpenCL v1.2 s6.9.r:
7388 // The event type cannot be used to declare a program scope variable.
7389 // OpenCL v2.0 s6.9.q:
7390 // The clk_event_t and reserve_id_t types cannot be declared in program
7391 // scope.
7392 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7393 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7394 Se.Diag(NewVD->getLocation(),
7395 diag::err_invalid_type_for_program_scope_var)
7396 << R;
7397 NewVD->setInvalidDecl();
7398 return false;
7402 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7403 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7404 Se.getLangOpts())) {
7405 QualType NR = R.getCanonicalType();
7406 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7407 NR->isReferenceType()) {
7408 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7409 NR->isFunctionReferenceType()) {
7410 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7411 << NR->isReferenceType();
7412 NewVD->setInvalidDecl();
7413 return false;
7415 NR = NR->getPointeeType();
7419 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7420 Se.getLangOpts())) {
7421 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7422 // half array type (unless the cl_khr_fp16 extension is enabled).
7423 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7424 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7425 NewVD->setInvalidDecl();
7426 return false;
7430 // OpenCL v1.2 s6.9.r:
7431 // The event type cannot be used with the __local, __constant and __global
7432 // address space qualifiers.
7433 if (R->isEventT()) {
7434 if (R.getAddressSpace() != LangAS::opencl_private) {
7435 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7436 NewVD->setInvalidDecl();
7437 return false;
7441 if (R->isSamplerT()) {
7442 // OpenCL v1.2 s6.9.b p4:
7443 // The sampler type cannot be used with the __local and __global address
7444 // space qualifiers.
7445 if (R.getAddressSpace() == LangAS::opencl_local ||
7446 R.getAddressSpace() == LangAS::opencl_global) {
7447 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7448 NewVD->setInvalidDecl();
7451 // OpenCL v1.2 s6.12.14.1:
7452 // A global sampler must be declared with either the constant address
7453 // space qualifier or with the const qualifier.
7454 if (DC->isTranslationUnit() &&
7455 !(R.getAddressSpace() == LangAS::opencl_constant ||
7456 R.isConstQualified())) {
7457 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7458 NewVD->setInvalidDecl();
7460 if (NewVD->isInvalidDecl())
7461 return false;
7464 return true;
7467 template <typename AttrTy>
7468 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7469 const TypedefNameDecl *TND = TT->getDecl();
7470 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7471 AttrTy *Clone = Attribute->clone(S.Context);
7472 Clone->setInherited(true);
7473 D->addAttr(Clone);
7477 // This function emits warning and a corresponding note based on the
7478 // ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7479 // declarations of an annotated type must be const qualified.
7480 void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7481 QualType VarType = VD->getType().getCanonicalType();
7483 // Ignore local declarations (for now) and those with const qualification.
7484 // TODO: Local variables should not be allowed if their type declaration has
7485 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7486 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7487 return;
7489 if (VarType->isArrayType()) {
7490 // Retrieve element type for array declarations.
7491 VarType = S.getASTContext().getBaseElementType(VarType);
7494 const RecordDecl *RD = VarType->getAsRecordDecl();
7496 // Check if the record declaration is present and if it has any attributes.
7497 if (RD == nullptr)
7498 return;
7500 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7501 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7502 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7503 return;
7507 NamedDecl *Sema::ActOnVariableDeclarator(
7508 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7509 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7510 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7511 QualType R = TInfo->getType();
7512 DeclarationName Name = GetNameForDeclarator(D).getName();
7514 IdentifierInfo *II = Name.getAsIdentifierInfo();
7515 bool IsPlaceholderVariable = false;
7517 if (D.isDecompositionDeclarator()) {
7518 // Take the name of the first declarator as our name for diagnostic
7519 // purposes.
7520 auto &Decomp = D.getDecompositionDeclarator();
7521 if (!Decomp.bindings().empty()) {
7522 II = Decomp.bindings()[0].Name;
7523 Name = II;
7525 } else if (!II) {
7526 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7527 return nullptr;
7531 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7532 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7534 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7535 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7536 IsPlaceholderVariable = true;
7537 if (!Previous.empty()) {
7538 NamedDecl *PrevDecl = *Previous.begin();
7539 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7540 DC->getRedeclContext());
7541 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false))
7542 DiagPlaceholderVariableDefinition(D.getIdentifierLoc());
7546 // dllimport globals without explicit storage class are treated as extern. We
7547 // have to change the storage class this early to get the right DeclContext.
7548 if (SC == SC_None && !DC->isRecord() &&
7549 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7550 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7551 SC = SC_Extern;
7553 DeclContext *OriginalDC = DC;
7554 bool IsLocalExternDecl = SC == SC_Extern &&
7555 adjustContextForLocalExternDecl(DC);
7557 if (SCSpec == DeclSpec::SCS_mutable) {
7558 // mutable can only appear on non-static class members, so it's always
7559 // an error here
7560 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7561 D.setInvalidType();
7562 SC = SC_None;
7565 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7566 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7567 D.getDeclSpec().getStorageClassSpecLoc())) {
7568 // In C++11, the 'register' storage class specifier is deprecated.
7569 // Suppress the warning in system macros, it's used in macros in some
7570 // popular C system headers, such as in glibc's htonl() macro.
7571 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7572 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7573 : diag::warn_deprecated_register)
7574 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7577 DiagnoseFunctionSpecifiers(D.getDeclSpec());
7579 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7580 // C99 6.9p2: The storage-class specifiers auto and register shall not
7581 // appear in the declaration specifiers in an external declaration.
7582 // Global Register+Asm is a GNU extension we support.
7583 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7584 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7585 D.setInvalidType();
7589 // If this variable has a VLA type and an initializer, try to
7590 // fold to a constant-sized type. This is otherwise invalid.
7591 if (D.hasInitializer() && R->isVariableArrayType())
7592 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7593 /*DiagID=*/0);
7595 bool IsMemberSpecialization = false;
7596 bool IsVariableTemplateSpecialization = false;
7597 bool IsPartialSpecialization = false;
7598 bool IsVariableTemplate = false;
7599 VarDecl *NewVD = nullptr;
7600 VarTemplateDecl *NewTemplate = nullptr;
7601 TemplateParameterList *TemplateParams = nullptr;
7602 if (!getLangOpts().CPlusPlus) {
7603 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7604 II, R, TInfo, SC);
7606 if (R->getContainedDeducedType())
7607 ParsingInitForAutoVars.insert(NewVD);
7609 if (D.isInvalidType())
7610 NewVD->setInvalidDecl();
7612 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7613 NewVD->hasLocalStorage())
7614 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7615 NTCUC_AutoVar, NTCUK_Destruct);
7616 } else {
7617 bool Invalid = false;
7619 if (DC->isRecord() && !CurContext->isRecord()) {
7620 // This is an out-of-line definition of a static data member.
7621 switch (SC) {
7622 case SC_None:
7623 break;
7624 case SC_Static:
7625 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7626 diag::err_static_out_of_line)
7627 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7628 break;
7629 case SC_Auto:
7630 case SC_Register:
7631 case SC_Extern:
7632 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7633 // to names of variables declared in a block or to function parameters.
7634 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7635 // of class members
7637 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7638 diag::err_storage_class_for_static_member)
7639 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7640 break;
7641 case SC_PrivateExtern:
7642 llvm_unreachable("C storage class in c++!");
7646 if (SC == SC_Static && CurContext->isRecord()) {
7647 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7648 // Walk up the enclosing DeclContexts to check for any that are
7649 // incompatible with static data members.
7650 const DeclContext *FunctionOrMethod = nullptr;
7651 const CXXRecordDecl *AnonStruct = nullptr;
7652 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7653 if (Ctxt->isFunctionOrMethod()) {
7654 FunctionOrMethod = Ctxt;
7655 break;
7657 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7658 if (ParentDecl && !ParentDecl->getDeclName()) {
7659 AnonStruct = ParentDecl;
7660 break;
7663 if (FunctionOrMethod) {
7664 // C++ [class.static.data]p5: A local class shall not have static data
7665 // members.
7666 Diag(D.getIdentifierLoc(),
7667 diag::err_static_data_member_not_allowed_in_local_class)
7668 << Name << RD->getDeclName() << RD->getTagKind();
7669 } else if (AnonStruct) {
7670 // C++ [class.static.data]p4: Unnamed classes and classes contained
7671 // directly or indirectly within unnamed classes shall not contain
7672 // static data members.
7673 Diag(D.getIdentifierLoc(),
7674 diag::err_static_data_member_not_allowed_in_anon_struct)
7675 << Name << AnonStruct->getTagKind();
7676 Invalid = true;
7677 } else if (RD->isUnion()) {
7678 // C++98 [class.union]p1: If a union contains a static data member,
7679 // the program is ill-formed. C++11 drops this restriction.
7680 Diag(D.getIdentifierLoc(),
7681 getLangOpts().CPlusPlus11
7682 ? diag::warn_cxx98_compat_static_data_member_in_union
7683 : diag::ext_static_data_member_in_union) << Name;
7688 // Match up the template parameter lists with the scope specifier, then
7689 // determine whether we have a template or a template specialization.
7690 bool InvalidScope = false;
7691 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7692 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7693 D.getCXXScopeSpec(),
7694 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7695 ? D.getName().TemplateId
7696 : nullptr,
7697 TemplateParamLists,
7698 /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7699 Invalid |= InvalidScope;
7701 if (TemplateParams) {
7702 if (!TemplateParams->size() &&
7703 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7704 // There is an extraneous 'template<>' for this variable. Complain
7705 // about it, but allow the declaration of the variable.
7706 Diag(TemplateParams->getTemplateLoc(),
7707 diag::err_template_variable_noparams)
7708 << II
7709 << SourceRange(TemplateParams->getTemplateLoc(),
7710 TemplateParams->getRAngleLoc());
7711 TemplateParams = nullptr;
7712 } else {
7713 // Check that we can declare a template here.
7714 if (CheckTemplateDeclScope(S, TemplateParams))
7715 return nullptr;
7717 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7718 // This is an explicit specialization or a partial specialization.
7719 IsVariableTemplateSpecialization = true;
7720 IsPartialSpecialization = TemplateParams->size() > 0;
7721 } else { // if (TemplateParams->size() > 0)
7722 // This is a template declaration.
7723 IsVariableTemplate = true;
7725 // Only C++1y supports variable templates (N3651).
7726 Diag(D.getIdentifierLoc(),
7727 getLangOpts().CPlusPlus14
7728 ? diag::warn_cxx11_compat_variable_template
7729 : diag::ext_variable_template);
7732 } else {
7733 // Check that we can declare a member specialization here.
7734 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7735 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7736 return nullptr;
7737 assert((Invalid ||
7738 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7739 "should have a 'template<>' for this decl");
7742 if (IsVariableTemplateSpecialization) {
7743 SourceLocation TemplateKWLoc =
7744 TemplateParamLists.size() > 0
7745 ? TemplateParamLists[0]->getTemplateLoc()
7746 : SourceLocation();
7747 DeclResult Res = ActOnVarTemplateSpecialization(
7748 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7749 IsPartialSpecialization);
7750 if (Res.isInvalid())
7751 return nullptr;
7752 NewVD = cast<VarDecl>(Res.get());
7753 AddToScope = false;
7754 } else if (D.isDecompositionDeclarator()) {
7755 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7756 D.getIdentifierLoc(), R, TInfo, SC,
7757 Bindings);
7758 } else
7759 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7760 D.getIdentifierLoc(), II, R, TInfo, SC);
7762 // If this is supposed to be a variable template, create it as such.
7763 if (IsVariableTemplate) {
7764 NewTemplate =
7765 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7766 TemplateParams, NewVD);
7767 NewVD->setDescribedVarTemplate(NewTemplate);
7770 // If this decl has an auto type in need of deduction, make a note of the
7771 // Decl so we can diagnose uses of it in its own initializer.
7772 if (R->getContainedDeducedType())
7773 ParsingInitForAutoVars.insert(NewVD);
7775 if (D.isInvalidType() || Invalid) {
7776 NewVD->setInvalidDecl();
7777 if (NewTemplate)
7778 NewTemplate->setInvalidDecl();
7781 SetNestedNameSpecifier(*this, NewVD, D);
7783 // If we have any template parameter lists that don't directly belong to
7784 // the variable (matching the scope specifier), store them.
7785 // An explicit variable template specialization does not own any template
7786 // parameter lists.
7787 bool IsExplicitSpecialization =
7788 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7789 unsigned VDTemplateParamLists =
7790 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7791 if (TemplateParamLists.size() > VDTemplateParamLists)
7792 NewVD->setTemplateParameterListsInfo(
7793 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7796 if (D.getDeclSpec().isInlineSpecified()) {
7797 if (!getLangOpts().CPlusPlus) {
7798 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7799 << 0;
7800 } else if (CurContext->isFunctionOrMethod()) {
7801 // 'inline' is not allowed on block scope variable declaration.
7802 Diag(D.getDeclSpec().getInlineSpecLoc(),
7803 diag::err_inline_declaration_block_scope) << Name
7804 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7805 } else {
7806 Diag(D.getDeclSpec().getInlineSpecLoc(),
7807 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7808 : diag::ext_inline_variable);
7809 NewVD->setInlineSpecified();
7813 // Set the lexical context. If the declarator has a C++ scope specifier, the
7814 // lexical context will be different from the semantic context.
7815 NewVD->setLexicalDeclContext(CurContext);
7816 if (NewTemplate)
7817 NewTemplate->setLexicalDeclContext(CurContext);
7819 if (IsLocalExternDecl) {
7820 if (D.isDecompositionDeclarator())
7821 for (auto *B : Bindings)
7822 B->setLocalExternDecl();
7823 else
7824 NewVD->setLocalExternDecl();
7827 bool EmitTLSUnsupportedError = false;
7828 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7829 // C++11 [dcl.stc]p4:
7830 // When thread_local is applied to a variable of block scope the
7831 // storage-class-specifier static is implied if it does not appear
7832 // explicitly.
7833 // Core issue: 'static' is not implied if the variable is declared
7834 // 'extern'.
7835 if (NewVD->hasLocalStorage() &&
7836 (SCSpec != DeclSpec::SCS_unspecified ||
7837 TSCS != DeclSpec::TSCS_thread_local ||
7838 !DC->isFunctionOrMethod()))
7839 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7840 diag::err_thread_non_global)
7841 << DeclSpec::getSpecifierName(TSCS);
7842 else if (!Context.getTargetInfo().isTLSSupported()) {
7843 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7844 getLangOpts().SYCLIsDevice) {
7845 // Postpone error emission until we've collected attributes required to
7846 // figure out whether it's a host or device variable and whether the
7847 // error should be ignored.
7848 EmitTLSUnsupportedError = true;
7849 // We still need to mark the variable as TLS so it shows up in AST with
7850 // proper storage class for other tools to use even if we're not going
7851 // to emit any code for it.
7852 NewVD->setTSCSpec(TSCS);
7853 } else
7854 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7855 diag::err_thread_unsupported);
7856 } else
7857 NewVD->setTSCSpec(TSCS);
7860 switch (D.getDeclSpec().getConstexprSpecifier()) {
7861 case ConstexprSpecKind::Unspecified:
7862 break;
7864 case ConstexprSpecKind::Consteval:
7865 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7866 diag::err_constexpr_wrong_decl_kind)
7867 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7868 [[fallthrough]];
7870 case ConstexprSpecKind::Constexpr:
7871 NewVD->setConstexpr(true);
7872 // C++1z [dcl.spec.constexpr]p1:
7873 // A static data member declared with the constexpr specifier is
7874 // implicitly an inline variable.
7875 if (NewVD->isStaticDataMember() &&
7876 (getLangOpts().CPlusPlus17 ||
7877 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7878 NewVD->setImplicitlyInline();
7879 break;
7881 case ConstexprSpecKind::Constinit:
7882 if (!NewVD->hasGlobalStorage())
7883 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7884 diag::err_constinit_local_variable);
7885 else
7886 NewVD->addAttr(
7887 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7888 ConstInitAttr::Keyword_constinit));
7889 break;
7892 // C99 6.7.4p3
7893 // An inline definition of a function with external linkage shall
7894 // not contain a definition of a modifiable object with static or
7895 // thread storage duration...
7896 // We only apply this when the function is required to be defined
7897 // elsewhere, i.e. when the function is not 'extern inline'. Note
7898 // that a local variable with thread storage duration still has to
7899 // be marked 'static'. Also note that it's possible to get these
7900 // semantics in C++ using __attribute__((gnu_inline)).
7901 if (SC == SC_Static && S->getFnParent() != nullptr &&
7902 !NewVD->getType().isConstQualified()) {
7903 FunctionDecl *CurFD = getCurFunctionDecl();
7904 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7905 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7906 diag::warn_static_local_in_extern_inline);
7907 MaybeSuggestAddingStaticToDecl(CurFD);
7911 if (D.getDeclSpec().isModulePrivateSpecified()) {
7912 if (IsVariableTemplateSpecialization)
7913 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7914 << (IsPartialSpecialization ? 1 : 0)
7915 << FixItHint::CreateRemoval(
7916 D.getDeclSpec().getModulePrivateSpecLoc());
7917 else if (IsMemberSpecialization)
7918 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7919 << 2
7920 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7921 else if (NewVD->hasLocalStorage())
7922 Diag(NewVD->getLocation(), diag::err_module_private_local)
7923 << 0 << NewVD
7924 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7925 << FixItHint::CreateRemoval(
7926 D.getDeclSpec().getModulePrivateSpecLoc());
7927 else {
7928 NewVD->setModulePrivate();
7929 if (NewTemplate)
7930 NewTemplate->setModulePrivate();
7931 for (auto *B : Bindings)
7932 B->setModulePrivate();
7936 if (getLangOpts().OpenCL) {
7937 deduceOpenCLAddressSpace(NewVD);
7939 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7940 if (TSC != TSCS_unspecified) {
7941 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7942 diag::err_opencl_unknown_type_specifier)
7943 << getLangOpts().getOpenCLVersionString()
7944 << DeclSpec::getSpecifierName(TSC) << 1;
7945 NewVD->setInvalidDecl();
7949 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7950 // address space if the table has local storage (semantic checks elsewhere
7951 // will produce an error anyway).
7952 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
7953 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
7954 !NewVD->hasLocalStorage()) {
7955 QualType Type = Context.getAddrSpaceQualType(
7956 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
7957 NewVD->setType(Type);
7961 // Handle attributes prior to checking for duplicates in MergeVarDecl
7962 ProcessDeclAttributes(S, NewVD, D);
7964 // FIXME: This is probably the wrong location to be doing this and we should
7965 // probably be doing this for more attributes (especially for function
7966 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7967 // the code to copy attributes would be generated by TableGen.
7968 if (R->isFunctionPointerType())
7969 if (const auto *TT = R->getAs<TypedefType>())
7970 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7972 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7973 getLangOpts().SYCLIsDevice) {
7974 if (EmitTLSUnsupportedError &&
7975 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7976 (getLangOpts().OpenMPIsTargetDevice &&
7977 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7978 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7979 diag::err_thread_unsupported);
7981 if (EmitTLSUnsupportedError &&
7982 (LangOpts.SYCLIsDevice ||
7983 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
7984 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7985 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7986 // storage [duration]."
7987 if (SC == SC_None && S->getFnParent() != nullptr &&
7988 (NewVD->hasAttr<CUDASharedAttr>() ||
7989 NewVD->hasAttr<CUDAConstantAttr>())) {
7990 NewVD->setStorageClass(SC_Static);
7994 // Ensure that dllimport globals without explicit storage class are treated as
7995 // extern. The storage class is set above using parsed attributes. Now we can
7996 // check the VarDecl itself.
7997 assert(!NewVD->hasAttr<DLLImportAttr>() ||
7998 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7999 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8001 // In auto-retain/release, infer strong retension for variables of
8002 // retainable type.
8003 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
8004 NewVD->setInvalidDecl();
8006 // Handle GNU asm-label extension (encoded as an attribute).
8007 if (Expr *E = (Expr*)D.getAsmLabel()) {
8008 // The parser guarantees this is a string.
8009 StringLiteral *SE = cast<StringLiteral>(E);
8010 StringRef Label = SE->getString();
8011 if (S->getFnParent() != nullptr) {
8012 switch (SC) {
8013 case SC_None:
8014 case SC_Auto:
8015 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
8016 break;
8017 case SC_Register:
8018 // Local Named register
8019 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
8020 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
8021 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8022 break;
8023 case SC_Static:
8024 case SC_Extern:
8025 case SC_PrivateExtern:
8026 break;
8028 } else if (SC == SC_Register) {
8029 // Global Named register
8030 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
8031 const auto &TI = Context.getTargetInfo();
8032 bool HasSizeMismatch;
8034 if (!TI.isValidGCCRegisterName(Label))
8035 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8036 else if (!TI.validateGlobalRegisterVariable(Label,
8037 Context.getTypeSize(R),
8038 HasSizeMismatch))
8039 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
8040 else if (HasSizeMismatch)
8041 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
8044 if (!R->isIntegralType(Context) && !R->isPointerType()) {
8045 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
8046 NewVD->setInvalidDecl(true);
8050 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
8051 /*IsLiteralLabel=*/true,
8052 SE->getStrTokenLoc(0)));
8053 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8054 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8055 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
8056 if (I != ExtnameUndeclaredIdentifiers.end()) {
8057 if (isDeclExternC(NewVD)) {
8058 NewVD->addAttr(I->second);
8059 ExtnameUndeclaredIdentifiers.erase(I);
8060 } else
8061 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8062 << /*Variable*/1 << NewVD;
8066 // Find the shadowed declaration before filtering for scope.
8067 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8068 ? getShadowedDeclaration(NewVD, Previous)
8069 : nullptr;
8071 // Don't consider existing declarations that are in a different
8072 // scope and are out-of-semantic-context declarations (if the new
8073 // declaration has linkage).
8074 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
8075 D.getCXXScopeSpec().isNotEmpty() ||
8076 IsMemberSpecialization ||
8077 IsVariableTemplateSpecialization);
8079 // Check whether the previous declaration is in the same block scope. This
8080 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8081 if (getLangOpts().CPlusPlus &&
8082 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8083 NewVD->setPreviousDeclInSameBlockScope(
8084 Previous.isSingleResult() && !Previous.isShadowed() &&
8085 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8087 if (!getLangOpts().CPlusPlus) {
8088 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8089 } else {
8090 // If this is an explicit specialization of a static data member, check it.
8091 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
8092 CheckMemberSpecialization(NewVD, Previous))
8093 NewVD->setInvalidDecl();
8095 // Merge the decl with the existing one if appropriate.
8096 if (!Previous.empty()) {
8097 if (Previous.isSingleResult() &&
8098 isa<FieldDecl>(Previous.getFoundDecl()) &&
8099 D.getCXXScopeSpec().isSet()) {
8100 // The user tried to define a non-static data member
8101 // out-of-line (C++ [dcl.meaning]p1).
8102 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8103 << D.getCXXScopeSpec().getRange();
8104 Previous.clear();
8105 NewVD->setInvalidDecl();
8107 } else if (D.getCXXScopeSpec().isSet()) {
8108 // No previous declaration in the qualifying scope.
8109 Diag(D.getIdentifierLoc(), diag::err_no_member)
8110 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8111 << D.getCXXScopeSpec().getRange();
8112 NewVD->setInvalidDecl();
8115 if (!IsVariableTemplateSpecialization && !IsPlaceholderVariable)
8116 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8118 // CheckVariableDeclaration will set NewVD as invalid if something is in
8119 // error like WebAssembly tables being declared as arrays with a non-zero
8120 // size, but then parsing continues and emits further errors on that line.
8121 // To avoid that we check here if it happened and return nullptr.
8122 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8123 return nullptr;
8125 if (NewTemplate) {
8126 VarTemplateDecl *PrevVarTemplate =
8127 NewVD->getPreviousDecl()
8128 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8129 : nullptr;
8131 // Check the template parameter list of this declaration, possibly
8132 // merging in the template parameter list from the previous variable
8133 // template declaration.
8134 if (CheckTemplateParameterList(
8135 TemplateParams,
8136 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8137 : nullptr,
8138 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8139 DC->isDependentContext())
8140 ? TPC_ClassTemplateMember
8141 : TPC_VarTemplate))
8142 NewVD->setInvalidDecl();
8144 // If we are providing an explicit specialization of a static variable
8145 // template, make a note of that.
8146 if (PrevVarTemplate &&
8147 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8148 PrevVarTemplate->setMemberSpecialization();
8152 // Diagnose shadowed variables iff this isn't a redeclaration.
8153 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8154 CheckShadow(NewVD, ShadowedDecl, Previous);
8156 ProcessPragmaWeak(S, NewVD);
8158 // If this is the first declaration of an extern C variable, update
8159 // the map of such variables.
8160 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8161 isIncompleteDeclExternC(*this, NewVD))
8162 RegisterLocallyScopedExternCDecl(NewVD, S);
8164 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8165 MangleNumberingContext *MCtx;
8166 Decl *ManglingContextDecl;
8167 std::tie(MCtx, ManglingContextDecl) =
8168 getCurrentMangleNumberContext(NewVD->getDeclContext());
8169 if (MCtx) {
8170 Context.setManglingNumber(
8171 NewVD, MCtx->getManglingNumber(
8172 NewVD, getMSManglingNumber(getLangOpts(), S)));
8173 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8177 // Special handling of variable named 'main'.
8178 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
8179 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8180 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
8182 // C++ [basic.start.main]p3
8183 // A program that declares a variable main at global scope is ill-formed.
8184 if (getLangOpts().CPlusPlus)
8185 Diag(D.getBeginLoc(), diag::err_main_global_variable);
8187 // In C, and external-linkage variable named main results in undefined
8188 // behavior.
8189 else if (NewVD->hasExternalFormalLinkage())
8190 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8193 if (D.isRedeclaration() && !Previous.empty()) {
8194 NamedDecl *Prev = Previous.getRepresentativeDecl();
8195 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8196 D.isFunctionDefinition());
8199 if (NewTemplate) {
8200 if (NewVD->isInvalidDecl())
8201 NewTemplate->setInvalidDecl();
8202 ActOnDocumentableDecl(NewTemplate);
8203 return NewTemplate;
8206 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8207 CompleteMemberSpecialization(NewVD, Previous);
8209 emitReadOnlyPlacementAttrWarning(*this, NewVD);
8211 return NewVD;
8214 /// Enum describing the %select options in diag::warn_decl_shadow.
8215 enum ShadowedDeclKind {
8216 SDK_Local,
8217 SDK_Global,
8218 SDK_StaticMember,
8219 SDK_Field,
8220 SDK_Typedef,
8221 SDK_Using,
8222 SDK_StructuredBinding
8225 /// Determine what kind of declaration we're shadowing.
8226 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8227 const DeclContext *OldDC) {
8228 if (isa<TypeAliasDecl>(ShadowedDecl))
8229 return SDK_Using;
8230 else if (isa<TypedefDecl>(ShadowedDecl))
8231 return SDK_Typedef;
8232 else if (isa<BindingDecl>(ShadowedDecl))
8233 return SDK_StructuredBinding;
8234 else if (isa<RecordDecl>(OldDC))
8235 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8237 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8240 /// Return the location of the capture if the given lambda captures the given
8241 /// variable \p VD, or an invalid source location otherwise.
8242 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8243 const VarDecl *VD) {
8244 for (const Capture &Capture : LSI->Captures) {
8245 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8246 return Capture.getLocation();
8248 return SourceLocation();
8251 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8252 const LookupResult &R) {
8253 // Only diagnose if we're shadowing an unambiguous field or variable.
8254 if (R.getResultKind() != LookupResult::Found)
8255 return false;
8257 // Return false if warning is ignored.
8258 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8261 /// Return the declaration shadowed by the given variable \p D, or null
8262 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8263 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8264 const LookupResult &R) {
8265 if (!shouldWarnIfShadowedDecl(Diags, R))
8266 return nullptr;
8268 // Don't diagnose declarations at file scope.
8269 if (D->hasGlobalStorage() && !D->isStaticLocal())
8270 return nullptr;
8272 NamedDecl *ShadowedDecl = R.getFoundDecl();
8273 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8274 : nullptr;
8277 /// Return the declaration shadowed by the given typedef \p D, or null
8278 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8279 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8280 const LookupResult &R) {
8281 // Don't warn if typedef declaration is part of a class
8282 if (D->getDeclContext()->isRecord())
8283 return nullptr;
8285 if (!shouldWarnIfShadowedDecl(Diags, R))
8286 return nullptr;
8288 NamedDecl *ShadowedDecl = R.getFoundDecl();
8289 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8292 /// Return the declaration shadowed by the given variable \p D, or null
8293 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8294 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8295 const LookupResult &R) {
8296 if (!shouldWarnIfShadowedDecl(Diags, R))
8297 return nullptr;
8299 NamedDecl *ShadowedDecl = R.getFoundDecl();
8300 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8301 : nullptr;
8304 /// Diagnose variable or built-in function shadowing. Implements
8305 /// -Wshadow.
8307 /// This method is called whenever a VarDecl is added to a "useful"
8308 /// scope.
8310 /// \param ShadowedDecl the declaration that is shadowed by the given variable
8311 /// \param R the lookup of the name
8313 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8314 const LookupResult &R) {
8315 DeclContext *NewDC = D->getDeclContext();
8317 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8318 // Fields are not shadowed by variables in C++ static methods.
8319 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8320 if (MD->isStatic())
8321 return;
8323 // Fields shadowed by constructor parameters are a special case. Usually
8324 // the constructor initializes the field with the parameter.
8325 if (isa<CXXConstructorDecl>(NewDC))
8326 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8327 // Remember that this was shadowed so we can either warn about its
8328 // modification or its existence depending on warning settings.
8329 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8330 return;
8334 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8335 if (shadowedVar->isExternC()) {
8336 // For shadowing external vars, make sure that we point to the global
8337 // declaration, not a locally scoped extern declaration.
8338 for (auto *I : shadowedVar->redecls())
8339 if (I->isFileVarDecl()) {
8340 ShadowedDecl = I;
8341 break;
8345 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8347 unsigned WarningDiag = diag::warn_decl_shadow;
8348 SourceLocation CaptureLoc;
8349 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
8350 isa<CXXMethodDecl>(NewDC)) {
8351 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8352 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8353 if (RD->getLambdaCaptureDefault() == LCD_None) {
8354 // Try to avoid warnings for lambdas with an explicit capture list.
8355 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8356 // Warn only when the lambda captures the shadowed decl explicitly.
8357 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
8358 if (CaptureLoc.isInvalid())
8359 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8360 } else {
8361 // Remember that this was shadowed so we can avoid the warning if the
8362 // shadowed decl isn't captured and the warning settings allow it.
8363 cast<LambdaScopeInfo>(getCurFunction())
8364 ->ShadowingDecls.push_back(
8365 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
8366 return;
8370 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
8371 // A variable can't shadow a local variable in an enclosing scope, if
8372 // they are separated by a non-capturing declaration context.
8373 for (DeclContext *ParentDC = NewDC;
8374 ParentDC && !ParentDC->Equals(OldDC);
8375 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8376 // Only block literals, captured statements, and lambda expressions
8377 // can capture; other scopes don't.
8378 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8379 !isLambdaCallOperator(ParentDC)) {
8380 return;
8387 // Never warn about shadowing a placeholder variable.
8388 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8389 return;
8391 // Only warn about certain kinds of shadowing for class members.
8392 if (NewDC && NewDC->isRecord()) {
8393 // In particular, don't warn about shadowing non-class members.
8394 if (!OldDC->isRecord())
8395 return;
8397 // TODO: should we warn about static data members shadowing
8398 // static data members from base classes?
8400 // TODO: don't diagnose for inaccessible shadowed members.
8401 // This is hard to do perfectly because we might friend the
8402 // shadowing context, but that's just a false negative.
8406 DeclarationName Name = R.getLookupName();
8408 // Emit warning and note.
8409 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8410 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8411 if (!CaptureLoc.isInvalid())
8412 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8413 << Name << /*explicitly*/ 1;
8414 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8417 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8418 /// when these variables are captured by the lambda.
8419 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8420 for (const auto &Shadow : LSI->ShadowingDecls) {
8421 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8422 // Try to avoid the warning when the shadowed decl isn't captured.
8423 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8424 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8425 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8426 ? diag::warn_decl_shadow_uncaptured_local
8427 : diag::warn_decl_shadow)
8428 << Shadow.VD->getDeclName()
8429 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8430 if (!CaptureLoc.isInvalid())
8431 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8432 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8433 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8437 /// Check -Wshadow without the advantage of a previous lookup.
8438 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8439 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8440 return;
8442 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8443 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8444 LookupName(R, S);
8445 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8446 CheckShadow(D, ShadowedDecl, R);
8449 /// Check if 'E', which is an expression that is about to be modified, refers
8450 /// to a constructor parameter that shadows a field.
8451 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8452 // Quickly ignore expressions that can't be shadowing ctor parameters.
8453 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8454 return;
8455 E = E->IgnoreParenImpCasts();
8456 auto *DRE = dyn_cast<DeclRefExpr>(E);
8457 if (!DRE)
8458 return;
8459 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8460 auto I = ShadowingDecls.find(D);
8461 if (I == ShadowingDecls.end())
8462 return;
8463 const NamedDecl *ShadowedDecl = I->second;
8464 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8465 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8466 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8467 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8469 // Avoid issuing multiple warnings about the same decl.
8470 ShadowingDecls.erase(I);
8473 /// Check for conflict between this global or extern "C" declaration and
8474 /// previous global or extern "C" declarations. This is only used in C++.
8475 template<typename T>
8476 static bool checkGlobalOrExternCConflict(
8477 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8478 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8479 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8481 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8482 // The common case: this global doesn't conflict with any extern "C"
8483 // declaration.
8484 return false;
8487 if (Prev) {
8488 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8489 // Both the old and new declarations have C language linkage. This is a
8490 // redeclaration.
8491 Previous.clear();
8492 Previous.addDecl(Prev);
8493 return true;
8496 // This is a global, non-extern "C" declaration, and there is a previous
8497 // non-global extern "C" declaration. Diagnose if this is a variable
8498 // declaration.
8499 if (!isa<VarDecl>(ND))
8500 return false;
8501 } else {
8502 // The declaration is extern "C". Check for any declaration in the
8503 // translation unit which might conflict.
8504 if (IsGlobal) {
8505 // We have already performed the lookup into the translation unit.
8506 IsGlobal = false;
8507 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8508 I != E; ++I) {
8509 if (isa<VarDecl>(*I)) {
8510 Prev = *I;
8511 break;
8514 } else {
8515 DeclContext::lookup_result R =
8516 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8517 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8518 I != E; ++I) {
8519 if (isa<VarDecl>(*I)) {
8520 Prev = *I;
8521 break;
8523 // FIXME: If we have any other entity with this name in global scope,
8524 // the declaration is ill-formed, but that is a defect: it breaks the
8525 // 'stat' hack, for instance. Only variables can have mangled name
8526 // clashes with extern "C" declarations, so only they deserve a
8527 // diagnostic.
8531 if (!Prev)
8532 return false;
8535 // Use the first declaration's location to ensure we point at something which
8536 // is lexically inside an extern "C" linkage-spec.
8537 assert(Prev && "should have found a previous declaration to diagnose");
8538 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8539 Prev = FD->getFirstDecl();
8540 else
8541 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8543 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8544 << IsGlobal << ND;
8545 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8546 << IsGlobal;
8547 return false;
8550 /// Apply special rules for handling extern "C" declarations. Returns \c true
8551 /// if we have found that this is a redeclaration of some prior entity.
8553 /// Per C++ [dcl.link]p6:
8554 /// Two declarations [for a function or variable] with C language linkage
8555 /// with the same name that appear in different scopes refer to the same
8556 /// [entity]. An entity with C language linkage shall not be declared with
8557 /// the same name as an entity in global scope.
8558 template<typename T>
8559 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8560 LookupResult &Previous) {
8561 if (!S.getLangOpts().CPlusPlus) {
8562 // In C, when declaring a global variable, look for a corresponding 'extern'
8563 // variable declared in function scope. We don't need this in C++, because
8564 // we find local extern decls in the surrounding file-scope DeclContext.
8565 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8566 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8567 Previous.clear();
8568 Previous.addDecl(Prev);
8569 return true;
8572 return false;
8575 // A declaration in the translation unit can conflict with an extern "C"
8576 // declaration.
8577 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8578 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8580 // An extern "C" declaration can conflict with a declaration in the
8581 // translation unit or can be a redeclaration of an extern "C" declaration
8582 // in another scope.
8583 if (isIncompleteDeclExternC(S,ND))
8584 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8586 // Neither global nor extern "C": nothing to do.
8587 return false;
8590 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8591 // If the decl is already known invalid, don't check it.
8592 if (NewVD->isInvalidDecl())
8593 return;
8595 QualType T = NewVD->getType();
8597 // Defer checking an 'auto' type until its initializer is attached.
8598 if (T->isUndeducedType())
8599 return;
8601 if (NewVD->hasAttrs())
8602 CheckAlignasUnderalignment(NewVD);
8604 if (T->isObjCObjectType()) {
8605 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8606 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8607 T = Context.getObjCObjectPointerType(T);
8608 NewVD->setType(T);
8611 // Emit an error if an address space was applied to decl with local storage.
8612 // This includes arrays of objects with address space qualifiers, but not
8613 // automatic variables that point to other address spaces.
8614 // ISO/IEC TR 18037 S5.1.2
8615 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8616 T.getAddressSpace() != LangAS::Default) {
8617 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8618 NewVD->setInvalidDecl();
8619 return;
8622 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8623 // scope.
8624 if (getLangOpts().OpenCLVersion == 120 &&
8625 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8626 getLangOpts()) &&
8627 NewVD->isStaticLocal()) {
8628 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8629 NewVD->setInvalidDecl();
8630 return;
8633 if (getLangOpts().OpenCL) {
8634 if (!diagnoseOpenCLTypes(*this, NewVD))
8635 return;
8637 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8638 if (NewVD->hasAttr<BlocksAttr>()) {
8639 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8640 return;
8643 if (T->isBlockPointerType()) {
8644 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8645 // can't use 'extern' storage class.
8646 if (!T.isConstQualified()) {
8647 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8648 << 0 /*const*/;
8649 NewVD->setInvalidDecl();
8650 return;
8652 if (NewVD->hasExternalStorage()) {
8653 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8654 NewVD->setInvalidDecl();
8655 return;
8659 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8660 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8661 NewVD->hasExternalStorage()) {
8662 if (!T->isSamplerT() && !T->isDependentType() &&
8663 !(T.getAddressSpace() == LangAS::opencl_constant ||
8664 (T.getAddressSpace() == LangAS::opencl_global &&
8665 getOpenCLOptions().areProgramScopeVariablesSupported(
8666 getLangOpts())))) {
8667 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8668 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8669 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8670 << Scope << "global or constant";
8671 else
8672 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8673 << Scope << "constant";
8674 NewVD->setInvalidDecl();
8675 return;
8677 } else {
8678 if (T.getAddressSpace() == LangAS::opencl_global) {
8679 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8680 << 1 /*is any function*/ << "global";
8681 NewVD->setInvalidDecl();
8682 return;
8684 if (T.getAddressSpace() == LangAS::opencl_constant ||
8685 T.getAddressSpace() == LangAS::opencl_local) {
8686 FunctionDecl *FD = getCurFunctionDecl();
8687 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8688 // in functions.
8689 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8690 if (T.getAddressSpace() == LangAS::opencl_constant)
8691 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8692 << 0 /*non-kernel only*/ << "constant";
8693 else
8694 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8695 << 0 /*non-kernel only*/ << "local";
8696 NewVD->setInvalidDecl();
8697 return;
8699 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8700 // in the outermost scope of a kernel function.
8701 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8702 if (!getCurScope()->isFunctionScope()) {
8703 if (T.getAddressSpace() == LangAS::opencl_constant)
8704 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8705 << "constant";
8706 else
8707 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8708 << "local";
8709 NewVD->setInvalidDecl();
8710 return;
8713 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8714 // If we are parsing a template we didn't deduce an addr
8715 // space yet.
8716 T.getAddressSpace() != LangAS::Default) {
8717 // Do not allow other address spaces on automatic variable.
8718 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8719 NewVD->setInvalidDecl();
8720 return;
8725 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8726 && !NewVD->hasAttr<BlocksAttr>()) {
8727 if (getLangOpts().getGC() != LangOptions::NonGC)
8728 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8729 else {
8730 assert(!getLangOpts().ObjCAutoRefCount);
8731 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8735 // WebAssembly tables must be static with a zero length and can't be
8736 // declared within functions.
8737 if (T->isWebAssemblyTableType()) {
8738 if (getCurScope()->getParent()) { // Parent is null at top-level
8739 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8740 NewVD->setInvalidDecl();
8741 return;
8743 if (NewVD->getStorageClass() != SC_Static) {
8744 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8745 NewVD->setInvalidDecl();
8746 return;
8748 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8749 if (!ATy || ATy->getSize().getSExtValue() != 0) {
8750 Diag(NewVD->getLocation(),
8751 diag::err_typecheck_wasm_table_must_have_zero_length);
8752 NewVD->setInvalidDecl();
8753 return;
8757 bool isVM = T->isVariablyModifiedType();
8758 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8759 NewVD->hasAttr<BlocksAttr>())
8760 setFunctionHasBranchProtectedScope();
8762 if ((isVM && NewVD->hasLinkage()) ||
8763 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8764 bool SizeIsNegative;
8765 llvm::APSInt Oversized;
8766 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8767 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8768 QualType FixedT;
8769 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8770 FixedT = FixedTInfo->getType();
8771 else if (FixedTInfo) {
8772 // Type and type-as-written are canonically different. We need to fix up
8773 // both types separately.
8774 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8775 Oversized);
8777 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8778 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8779 // FIXME: This won't give the correct result for
8780 // int a[10][n];
8781 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8783 if (NewVD->isFileVarDecl())
8784 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8785 << SizeRange;
8786 else if (NewVD->isStaticLocal())
8787 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8788 << SizeRange;
8789 else
8790 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8791 << SizeRange;
8792 NewVD->setInvalidDecl();
8793 return;
8796 if (!FixedTInfo) {
8797 if (NewVD->isFileVarDecl())
8798 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8799 else
8800 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8801 NewVD->setInvalidDecl();
8802 return;
8805 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8806 NewVD->setType(FixedT);
8807 NewVD->setTypeSourceInfo(FixedTInfo);
8810 if (T->isVoidType()) {
8811 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8812 // of objects and functions.
8813 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8814 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8815 << T;
8816 NewVD->setInvalidDecl();
8817 return;
8821 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8822 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8823 NewVD->setInvalidDecl();
8824 return;
8827 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8828 !T.isWebAssemblyReferenceType()) {
8829 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8830 NewVD->setInvalidDecl();
8831 return;
8834 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8835 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8836 NewVD->setInvalidDecl();
8837 return;
8840 if (NewVD->isConstexpr() && !T->isDependentType() &&
8841 RequireLiteralType(NewVD->getLocation(), T,
8842 diag::err_constexpr_var_non_literal)) {
8843 NewVD->setInvalidDecl();
8844 return;
8847 // PPC MMA non-pointer types are not allowed as non-local variable types.
8848 if (Context.getTargetInfo().getTriple().isPPC64() &&
8849 !NewVD->isLocalVarDecl() &&
8850 CheckPPCMMAType(T, NewVD->getLocation())) {
8851 NewVD->setInvalidDecl();
8852 return;
8855 // Check that SVE types are only used in functions with SVE available.
8856 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8857 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8858 llvm::StringMap<bool> CallerFeatureMap;
8859 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8860 if (!Builtin::evaluateRequiredTargetFeatures(
8861 "sve", CallerFeatureMap)) {
8862 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8863 NewVD->setInvalidDecl();
8864 return;
8868 if (T->isRVVType())
8869 checkRVVTypeSupport(T, NewVD->getLocation(), cast<ValueDecl>(CurContext));
8872 /// Perform semantic checking on a newly-created variable
8873 /// declaration.
8875 /// This routine performs all of the type-checking required for a
8876 /// variable declaration once it has been built. It is used both to
8877 /// check variables after they have been parsed and their declarators
8878 /// have been translated into a declaration, and to check variables
8879 /// that have been instantiated from a template.
8881 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8883 /// Returns true if the variable declaration is a redeclaration.
8884 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8885 CheckVariableDeclarationType(NewVD);
8887 // If the decl is already known invalid, don't check it.
8888 if (NewVD->isInvalidDecl())
8889 return false;
8891 // If we did not find anything by this name, look for a non-visible
8892 // extern "C" declaration with the same name.
8893 if (Previous.empty() &&
8894 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8895 Previous.setShadowed();
8897 if (!Previous.empty()) {
8898 MergeVarDecl(NewVD, Previous);
8899 return true;
8901 return false;
8904 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8905 /// and if so, check that it's a valid override and remember it.
8906 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8907 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8909 // Look for methods in base classes that this method might override.
8910 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8911 /*DetectVirtual=*/false);
8912 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8913 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8914 DeclarationName Name = MD->getDeclName();
8916 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8917 // We really want to find the base class destructor here.
8918 QualType T = Context.getTypeDeclType(BaseRecord);
8919 CanQualType CT = Context.getCanonicalType(T);
8920 Name = Context.DeclarationNames.getCXXDestructorName(CT);
8923 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8924 CXXMethodDecl *BaseMD =
8925 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8926 if (!BaseMD || !BaseMD->isVirtual() ||
8927 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8928 /*ConsiderCudaAttrs=*/true,
8929 // C++2a [class.virtual]p2 does not consider requires
8930 // clauses when overriding.
8931 /*ConsiderRequiresClauses=*/false))
8932 continue;
8934 if (Overridden.insert(BaseMD).second) {
8935 MD->addOverriddenMethod(BaseMD);
8936 CheckOverridingFunctionReturnType(MD, BaseMD);
8937 CheckOverridingFunctionAttributes(MD, BaseMD);
8938 CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8939 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8942 // A method can only override one function from each base class. We
8943 // don't track indirectly overridden methods from bases of bases.
8944 return true;
8947 return false;
8950 DC->lookupInBases(VisitBase, Paths);
8951 return !Overridden.empty();
8954 namespace {
8955 // Struct for holding all of the extra arguments needed by
8956 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8957 struct ActOnFDArgs {
8958 Scope *S;
8959 Declarator &D;
8960 MultiTemplateParamsArg TemplateParamLists;
8961 bool AddToScope;
8963 } // end anonymous namespace
8965 namespace {
8967 // Callback to only accept typo corrections that have a non-zero edit distance.
8968 // Also only accept corrections that have the same parent decl.
8969 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8970 public:
8971 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8972 CXXRecordDecl *Parent)
8973 : Context(Context), OriginalFD(TypoFD),
8974 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8976 bool ValidateCandidate(const TypoCorrection &candidate) override {
8977 if (candidate.getEditDistance() == 0)
8978 return false;
8980 SmallVector<unsigned, 1> MismatchedParams;
8981 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8982 CDeclEnd = candidate.end();
8983 CDecl != CDeclEnd; ++CDecl) {
8984 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8986 if (FD && !FD->hasBody() &&
8987 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8988 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8989 CXXRecordDecl *Parent = MD->getParent();
8990 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8991 return true;
8992 } else if (!ExpectedParent) {
8993 return true;
8998 return false;
9001 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9002 return std::make_unique<DifferentNameValidatorCCC>(*this);
9005 private:
9006 ASTContext &Context;
9007 FunctionDecl *OriginalFD;
9008 CXXRecordDecl *ExpectedParent;
9011 } // end anonymous namespace
9013 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9014 TypoCorrectedFunctionDefinitions.insert(F);
9017 /// Generate diagnostics for an invalid function redeclaration.
9019 /// This routine handles generating the diagnostic messages for an invalid
9020 /// function redeclaration, including finding possible similar declarations
9021 /// or performing typo correction if there are no previous declarations with
9022 /// the same name.
9024 /// Returns a NamedDecl iff typo correction was performed and substituting in
9025 /// the new declaration name does not cause new errors.
9026 static NamedDecl *DiagnoseInvalidRedeclaration(
9027 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9028 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9029 DeclarationName Name = NewFD->getDeclName();
9030 DeclContext *NewDC = NewFD->getDeclContext();
9031 SmallVector<unsigned, 1> MismatchedParams;
9032 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9033 TypoCorrection Correction;
9034 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9035 unsigned DiagMsg =
9036 IsLocalFriend ? diag::err_no_matching_local_friend :
9037 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9038 diag::err_member_decl_does_not_match;
9039 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9040 IsLocalFriend ? Sema::LookupLocalFriendName
9041 : Sema::LookupOrdinaryName,
9042 Sema::ForVisibleRedeclaration);
9044 NewFD->setInvalidDecl();
9045 if (IsLocalFriend)
9046 SemaRef.LookupName(Prev, S);
9047 else
9048 SemaRef.LookupQualifiedName(Prev, NewDC);
9049 assert(!Prev.isAmbiguous() &&
9050 "Cannot have an ambiguity in previous-declaration lookup");
9051 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9052 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9053 MD ? MD->getParent() : nullptr);
9054 if (!Prev.empty()) {
9055 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9056 Func != FuncEnd; ++Func) {
9057 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9058 if (FD &&
9059 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9060 // Add 1 to the index so that 0 can mean the mismatch didn't
9061 // involve a parameter
9062 unsigned ParamNum =
9063 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9064 NearMatches.push_back(std::make_pair(FD, ParamNum));
9067 // If the qualified name lookup yielded nothing, try typo correction
9068 } else if ((Correction = SemaRef.CorrectTypo(
9069 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9070 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
9071 IsLocalFriend ? nullptr : NewDC))) {
9072 // Set up everything for the call to ActOnFunctionDeclarator
9073 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9074 ExtraArgs.D.getIdentifierLoc());
9075 Previous.clear();
9076 Previous.setLookupName(Correction.getCorrection());
9077 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9078 CDeclEnd = Correction.end();
9079 CDecl != CDeclEnd; ++CDecl) {
9080 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9081 if (FD && !FD->hasBody() &&
9082 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9083 Previous.addDecl(FD);
9086 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9088 NamedDecl *Result;
9089 // Retry building the function declaration with the new previous
9090 // declarations, and with errors suppressed.
9092 // Trap errors.
9093 Sema::SFINAETrap Trap(SemaRef);
9095 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9096 // pieces need to verify the typo-corrected C++ declaration and hopefully
9097 // eliminate the need for the parameter pack ExtraArgs.
9098 Result = SemaRef.ActOnFunctionDeclarator(
9099 ExtraArgs.S, ExtraArgs.D,
9100 Correction.getCorrectionDecl()->getDeclContext(),
9101 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9102 ExtraArgs.AddToScope);
9104 if (Trap.hasErrorOccurred())
9105 Result = nullptr;
9108 if (Result) {
9109 // Determine which correction we picked.
9110 Decl *Canonical = Result->getCanonicalDecl();
9111 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9112 I != E; ++I)
9113 if ((*I)->getCanonicalDecl() == Canonical)
9114 Correction.setCorrectionDecl(*I);
9116 // Let Sema know about the correction.
9117 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
9118 SemaRef.diagnoseTypo(
9119 Correction,
9120 SemaRef.PDiag(IsLocalFriend
9121 ? diag::err_no_matching_local_friend_suggest
9122 : diag::err_member_decl_does_not_match_suggest)
9123 << Name << NewDC << IsDefinition);
9124 return Result;
9127 // Pretend the typo correction never occurred
9128 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9129 ExtraArgs.D.getIdentifierLoc());
9130 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9131 Previous.clear();
9132 Previous.setLookupName(Name);
9135 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9136 << Name << NewDC << IsDefinition << NewFD->getLocation();
9138 bool NewFDisConst = false;
9139 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
9140 NewFDisConst = NewMD->isConst();
9142 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9143 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9144 NearMatch != NearMatchEnd; ++NearMatch) {
9145 FunctionDecl *FD = NearMatch->first;
9146 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9147 bool FDisConst = MD && MD->isConst();
9148 bool IsMember = MD || !IsLocalFriend;
9150 // FIXME: These notes are poorly worded for the local friend case.
9151 if (unsigned Idx = NearMatch->second) {
9152 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9153 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9154 if (Loc.isInvalid()) Loc = FD->getLocation();
9155 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9156 : diag::note_local_decl_close_param_match)
9157 << Idx << FDParam->getType()
9158 << NewFD->getParamDecl(Idx - 1)->getType();
9159 } else if (FDisConst != NewFDisConst) {
9160 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
9161 << NewFDisConst << FD->getSourceRange().getEnd()
9162 << (NewFDisConst
9163 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
9164 .getConstQualifierLoc())
9165 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
9166 .getRParenLoc()
9167 .getLocWithOffset(1),
9168 " const"));
9169 } else
9170 SemaRef.Diag(FD->getLocation(),
9171 IsMember ? diag::note_member_def_close_match
9172 : diag::note_local_decl_close_match);
9174 return nullptr;
9177 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9178 switch (D.getDeclSpec().getStorageClassSpec()) {
9179 default: llvm_unreachable("Unknown storage class!");
9180 case DeclSpec::SCS_auto:
9181 case DeclSpec::SCS_register:
9182 case DeclSpec::SCS_mutable:
9183 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9184 diag::err_typecheck_sclass_func);
9185 D.getMutableDeclSpec().ClearStorageClassSpecs();
9186 D.setInvalidType();
9187 break;
9188 case DeclSpec::SCS_unspecified: break;
9189 case DeclSpec::SCS_extern:
9190 if (D.getDeclSpec().isExternInLinkageSpec())
9191 return SC_None;
9192 return SC_Extern;
9193 case DeclSpec::SCS_static: {
9194 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9195 // C99 6.7.1p5:
9196 // The declaration of an identifier for a function that has
9197 // block scope shall have no explicit storage-class specifier
9198 // other than extern
9199 // See also (C++ [dcl.stc]p4).
9200 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9201 diag::err_static_block_func);
9202 break;
9203 } else
9204 return SC_Static;
9206 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9209 // No explicit storage class has already been returned
9210 return SC_None;
9213 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9214 DeclContext *DC, QualType &R,
9215 TypeSourceInfo *TInfo,
9216 StorageClass SC,
9217 bool &IsVirtualOkay) {
9218 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9219 DeclarationName Name = NameInfo.getName();
9221 FunctionDecl *NewFD = nullptr;
9222 bool isInline = D.getDeclSpec().isInlineSpecified();
9224 if (!SemaRef.getLangOpts().CPlusPlus) {
9225 // Determine whether the function was written with a prototype. This is
9226 // true when:
9227 // - there is a prototype in the declarator, or
9228 // - the type R of the function is some kind of typedef or other non-
9229 // attributed reference to a type name (which eventually refers to a
9230 // function type). Note, we can't always look at the adjusted type to
9231 // check this case because attributes may cause a non-function
9232 // declarator to still have a function type. e.g.,
9233 // typedef void func(int a);
9234 // __attribute__((noreturn)) func other_func; // This has a prototype
9235 bool HasPrototype =
9236 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9237 (D.getDeclSpec().isTypeRep() &&
9238 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9239 ->isFunctionProtoType()) ||
9240 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9241 assert(
9242 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9243 "Strict prototypes are required");
9245 NewFD = FunctionDecl::Create(
9246 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9247 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9248 ConstexprSpecKind::Unspecified,
9249 /*TrailingRequiresClause=*/nullptr);
9250 if (D.isInvalidType())
9251 NewFD->setInvalidDecl();
9253 return NewFD;
9256 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9258 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9259 if (ConstexprKind == ConstexprSpecKind::Constinit) {
9260 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9261 diag::err_constexpr_wrong_decl_kind)
9262 << static_cast<int>(ConstexprKind);
9263 ConstexprKind = ConstexprSpecKind::Unspecified;
9264 D.getMutableDeclSpec().ClearConstexprSpec();
9266 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9268 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9269 // This is a C++ constructor declaration.
9270 assert(DC->isRecord() &&
9271 "Constructors can only be declared in a member context");
9273 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9274 return CXXConstructorDecl::Create(
9275 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9276 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
9277 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9278 InheritedConstructor(), TrailingRequiresClause);
9280 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9281 // This is a C++ destructor declaration.
9282 if (DC->isRecord()) {
9283 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9284 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9285 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9286 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9287 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9288 /*isImplicitlyDeclared=*/false, ConstexprKind,
9289 TrailingRequiresClause);
9290 // User defined destructors start as not selected if the class definition is still
9291 // not done.
9292 if (Record->isBeingDefined())
9293 NewDD->setIneligibleOrNotSelected(true);
9295 // If the destructor needs an implicit exception specification, set it
9296 // now. FIXME: It'd be nice to be able to create the right type to start
9297 // with, but the type needs to reference the destructor declaration.
9298 if (SemaRef.getLangOpts().CPlusPlus11)
9299 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9301 IsVirtualOkay = true;
9302 return NewDD;
9304 } else {
9305 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9306 D.setInvalidType();
9308 // Create a FunctionDecl to satisfy the function definition parsing
9309 // code path.
9310 return FunctionDecl::Create(
9311 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9312 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9313 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9316 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9317 if (!DC->isRecord()) {
9318 SemaRef.Diag(D.getIdentifierLoc(),
9319 diag::err_conv_function_not_member);
9320 return nullptr;
9323 SemaRef.CheckConversionDeclarator(D, R, SC);
9324 if (D.isInvalidType())
9325 return nullptr;
9327 IsVirtualOkay = true;
9328 return CXXConversionDecl::Create(
9329 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9330 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9331 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9332 TrailingRequiresClause);
9334 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9335 if (TrailingRequiresClause)
9336 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9337 diag::err_trailing_requires_clause_on_deduction_guide)
9338 << TrailingRequiresClause->getSourceRange();
9339 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9340 return nullptr;
9341 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9342 ExplicitSpecifier, NameInfo, R, TInfo,
9343 D.getEndLoc());
9344 } else if (DC->isRecord()) {
9345 // If the name of the function is the same as the name of the record,
9346 // then this must be an invalid constructor that has a return type.
9347 // (The parser checks for a return type and makes the declarator a
9348 // constructor if it has no return type).
9349 if (Name.getAsIdentifierInfo() &&
9350 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9351 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9352 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9353 << SourceRange(D.getIdentifierLoc());
9354 return nullptr;
9357 // This is a C++ method declaration.
9358 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9359 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9360 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9361 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9362 IsVirtualOkay = !Ret->isStatic();
9363 return Ret;
9364 } else {
9365 bool isFriend =
9366 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9367 if (!isFriend && SemaRef.CurContext->isRecord())
9368 return nullptr;
9370 // Determine whether the function was written with a
9371 // prototype. This true when:
9372 // - we're in C++ (where every function has a prototype),
9373 return FunctionDecl::Create(
9374 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9375 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9376 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9380 enum OpenCLParamType {
9381 ValidKernelParam,
9382 PtrPtrKernelParam,
9383 PtrKernelParam,
9384 InvalidAddrSpacePtrKernelParam,
9385 InvalidKernelParam,
9386 RecordKernelParam
9389 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9390 // Size dependent types are just typedefs to normal integer types
9391 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9392 // integers other than by their names.
9393 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9395 // Remove typedefs one by one until we reach a typedef
9396 // for a size dependent type.
9397 QualType DesugaredTy = Ty;
9398 do {
9399 ArrayRef<StringRef> Names(SizeTypeNames);
9400 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9401 if (Names.end() != Match)
9402 return true;
9404 Ty = DesugaredTy;
9405 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9406 } while (DesugaredTy != Ty);
9408 return false;
9411 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9412 if (PT->isDependentType())
9413 return InvalidKernelParam;
9415 if (PT->isPointerType() || PT->isReferenceType()) {
9416 QualType PointeeType = PT->getPointeeType();
9417 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9418 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9419 PointeeType.getAddressSpace() == LangAS::Default)
9420 return InvalidAddrSpacePtrKernelParam;
9422 if (PointeeType->isPointerType()) {
9423 // This is a pointer to pointer parameter.
9424 // Recursively check inner type.
9425 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9426 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9427 ParamKind == InvalidKernelParam)
9428 return ParamKind;
9430 // OpenCL v3.0 s6.11.a:
9431 // A restriction to pass pointers to pointers only applies to OpenCL C
9432 // v1.2 or below.
9433 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9434 return ValidKernelParam;
9436 return PtrPtrKernelParam;
9439 // C++ for OpenCL v1.0 s2.4:
9440 // Moreover the types used in parameters of the kernel functions must be:
9441 // Standard layout types for pointer parameters. The same applies to
9442 // reference if an implementation supports them in kernel parameters.
9443 if (S.getLangOpts().OpenCLCPlusPlus &&
9444 !S.getOpenCLOptions().isAvailableOption(
9445 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9446 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9447 bool IsStandardLayoutType = true;
9448 if (CXXRec) {
9449 // If template type is not ODR-used its definition is only available
9450 // in the template definition not its instantiation.
9451 // FIXME: This logic doesn't work for types that depend on template
9452 // parameter (PR58590).
9453 if (!CXXRec->hasDefinition())
9454 CXXRec = CXXRec->getTemplateInstantiationPattern();
9455 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9456 IsStandardLayoutType = false;
9458 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9459 !IsStandardLayoutType)
9460 return InvalidKernelParam;
9463 // OpenCL v1.2 s6.9.p:
9464 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9465 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9466 return ValidKernelParam;
9468 return PtrKernelParam;
9471 // OpenCL v1.2 s6.9.k:
9472 // Arguments to kernel functions in a program cannot be declared with the
9473 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9474 // uintptr_t or a struct and/or union that contain fields declared to be one
9475 // of these built-in scalar types.
9476 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9477 return InvalidKernelParam;
9479 if (PT->isImageType())
9480 return PtrKernelParam;
9482 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9483 return InvalidKernelParam;
9485 // OpenCL extension spec v1.2 s9.5:
9486 // This extension adds support for half scalar and vector types as built-in
9487 // types that can be used for arithmetic operations, conversions etc.
9488 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9489 PT->isHalfType())
9490 return InvalidKernelParam;
9492 // Look into an array argument to check if it has a forbidden type.
9493 if (PT->isArrayType()) {
9494 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9495 // Call ourself to check an underlying type of an array. Since the
9496 // getPointeeOrArrayElementType returns an innermost type which is not an
9497 // array, this recursive call only happens once.
9498 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9501 // C++ for OpenCL v1.0 s2.4:
9502 // Moreover the types used in parameters of the kernel functions must be:
9503 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9504 // types) for parameters passed by value;
9505 if (S.getLangOpts().OpenCLCPlusPlus &&
9506 !S.getOpenCLOptions().isAvailableOption(
9507 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9508 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9509 return InvalidKernelParam;
9511 if (PT->isRecordType())
9512 return RecordKernelParam;
9514 return ValidKernelParam;
9517 static void checkIsValidOpenCLKernelParameter(
9518 Sema &S,
9519 Declarator &D,
9520 ParmVarDecl *Param,
9521 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9522 QualType PT = Param->getType();
9524 // Cache the valid types we encounter to avoid rechecking structs that are
9525 // used again
9526 if (ValidTypes.count(PT.getTypePtr()))
9527 return;
9529 switch (getOpenCLKernelParameterType(S, PT)) {
9530 case PtrPtrKernelParam:
9531 // OpenCL v3.0 s6.11.a:
9532 // A kernel function argument cannot be declared as a pointer to a pointer
9533 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9534 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9535 D.setInvalidType();
9536 return;
9538 case InvalidAddrSpacePtrKernelParam:
9539 // OpenCL v1.0 s6.5:
9540 // __kernel function arguments declared to be a pointer of a type can point
9541 // to one of the following address spaces only : __global, __local or
9542 // __constant.
9543 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9544 D.setInvalidType();
9545 return;
9547 // OpenCL v1.2 s6.9.k:
9548 // Arguments to kernel functions in a program cannot be declared with the
9549 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9550 // uintptr_t or a struct and/or union that contain fields declared to be
9551 // one of these built-in scalar types.
9553 case InvalidKernelParam:
9554 // OpenCL v1.2 s6.8 n:
9555 // A kernel function argument cannot be declared
9556 // of event_t type.
9557 // Do not diagnose half type since it is diagnosed as invalid argument
9558 // type for any function elsewhere.
9559 if (!PT->isHalfType()) {
9560 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9562 // Explain what typedefs are involved.
9563 const TypedefType *Typedef = nullptr;
9564 while ((Typedef = PT->getAs<TypedefType>())) {
9565 SourceLocation Loc = Typedef->getDecl()->getLocation();
9566 // SourceLocation may be invalid for a built-in type.
9567 if (Loc.isValid())
9568 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9569 PT = Typedef->desugar();
9573 D.setInvalidType();
9574 return;
9576 case PtrKernelParam:
9577 case ValidKernelParam:
9578 ValidTypes.insert(PT.getTypePtr());
9579 return;
9581 case RecordKernelParam:
9582 break;
9585 // Track nested structs we will inspect
9586 SmallVector<const Decl *, 4> VisitStack;
9588 // Track where we are in the nested structs. Items will migrate from
9589 // VisitStack to HistoryStack as we do the DFS for bad field.
9590 SmallVector<const FieldDecl *, 4> HistoryStack;
9591 HistoryStack.push_back(nullptr);
9593 // At this point we already handled everything except of a RecordType or
9594 // an ArrayType of a RecordType.
9595 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9596 const RecordType *RecTy =
9597 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9598 const RecordDecl *OrigRecDecl = RecTy->getDecl();
9600 VisitStack.push_back(RecTy->getDecl());
9601 assert(VisitStack.back() && "First decl null?");
9603 do {
9604 const Decl *Next = VisitStack.pop_back_val();
9605 if (!Next) {
9606 assert(!HistoryStack.empty());
9607 // Found a marker, we have gone up a level
9608 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9609 ValidTypes.insert(Hist->getType().getTypePtr());
9611 continue;
9614 // Adds everything except the original parameter declaration (which is not a
9615 // field itself) to the history stack.
9616 const RecordDecl *RD;
9617 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9618 HistoryStack.push_back(Field);
9620 QualType FieldTy = Field->getType();
9621 // Other field types (known to be valid or invalid) are handled while we
9622 // walk around RecordDecl::fields().
9623 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9624 "Unexpected type.");
9625 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9627 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9628 } else {
9629 RD = cast<RecordDecl>(Next);
9632 // Add a null marker so we know when we've gone back up a level
9633 VisitStack.push_back(nullptr);
9635 for (const auto *FD : RD->fields()) {
9636 QualType QT = FD->getType();
9638 if (ValidTypes.count(QT.getTypePtr()))
9639 continue;
9641 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9642 if (ParamType == ValidKernelParam)
9643 continue;
9645 if (ParamType == RecordKernelParam) {
9646 VisitStack.push_back(FD);
9647 continue;
9650 // OpenCL v1.2 s6.9.p:
9651 // Arguments to kernel functions that are declared to be a struct or union
9652 // do not allow OpenCL objects to be passed as elements of the struct or
9653 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9654 // of SVM.
9655 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9656 ParamType == InvalidAddrSpacePtrKernelParam) {
9657 S.Diag(Param->getLocation(),
9658 diag::err_record_with_pointers_kernel_param)
9659 << PT->isUnionType()
9660 << PT;
9661 } else {
9662 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9665 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9666 << OrigRecDecl->getDeclName();
9668 // We have an error, now let's go back up through history and show where
9669 // the offending field came from
9670 for (ArrayRef<const FieldDecl *>::const_iterator
9671 I = HistoryStack.begin() + 1,
9672 E = HistoryStack.end();
9673 I != E; ++I) {
9674 const FieldDecl *OuterField = *I;
9675 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9676 << OuterField->getType();
9679 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9680 << QT->isPointerType()
9681 << QT;
9682 D.setInvalidType();
9683 return;
9685 } while (!VisitStack.empty());
9688 /// Find the DeclContext in which a tag is implicitly declared if we see an
9689 /// elaborated type specifier in the specified context, and lookup finds
9690 /// nothing.
9691 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9692 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9693 DC = DC->getParent();
9694 return DC;
9697 /// Find the Scope in which a tag is implicitly declared if we see an
9698 /// elaborated type specifier in the specified context, and lookup finds
9699 /// nothing.
9700 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9701 while (S->isClassScope() ||
9702 (LangOpts.CPlusPlus &&
9703 S->isFunctionPrototypeScope()) ||
9704 ((S->getFlags() & Scope::DeclScope) == 0) ||
9705 (S->getEntity() && S->getEntity()->isTransparentContext()))
9706 S = S->getParent();
9707 return S;
9710 /// Determine whether a declaration matches a known function in namespace std.
9711 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9712 unsigned BuiltinID) {
9713 switch (BuiltinID) {
9714 case Builtin::BI__GetExceptionInfo:
9715 // No type checking whatsoever.
9716 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9718 case Builtin::BIaddressof:
9719 case Builtin::BI__addressof:
9720 case Builtin::BIforward:
9721 case Builtin::BIforward_like:
9722 case Builtin::BImove:
9723 case Builtin::BImove_if_noexcept:
9724 case Builtin::BIas_const: {
9725 // Ensure that we don't treat the algorithm
9726 // OutputIt std::move(InputIt, InputIt, OutputIt)
9727 // as the builtin std::move.
9728 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9729 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9732 default:
9733 return false;
9737 NamedDecl*
9738 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9739 TypeSourceInfo *TInfo, LookupResult &Previous,
9740 MultiTemplateParamsArg TemplateParamListsRef,
9741 bool &AddToScope) {
9742 QualType R = TInfo->getType();
9744 assert(R->isFunctionType());
9745 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9746 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9748 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9749 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9750 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9751 if (!TemplateParamLists.empty() &&
9752 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9753 TemplateParamLists.back() = Invented;
9754 else
9755 TemplateParamLists.push_back(Invented);
9758 // TODO: consider using NameInfo for diagnostic.
9759 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9760 DeclarationName Name = NameInfo.getName();
9761 StorageClass SC = getFunctionStorageClass(*this, D);
9763 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9764 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9765 diag::err_invalid_thread)
9766 << DeclSpec::getSpecifierName(TSCS);
9768 if (D.isFirstDeclarationOfMember())
9769 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9770 D.getIdentifierLoc());
9772 bool isFriend = false;
9773 FunctionTemplateDecl *FunctionTemplate = nullptr;
9774 bool isMemberSpecialization = false;
9775 bool isFunctionTemplateSpecialization = false;
9777 bool isDependentClassScopeExplicitSpecialization = false;
9778 bool HasExplicitTemplateArgs = false;
9779 TemplateArgumentListInfo TemplateArgs;
9781 bool isVirtualOkay = false;
9783 DeclContext *OriginalDC = DC;
9784 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9786 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9787 isVirtualOkay);
9788 if (!NewFD) return nullptr;
9790 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9791 NewFD->setTopLevelDeclInObjCContainer();
9793 // Set the lexical context. If this is a function-scope declaration, or has a
9794 // C++ scope specifier, or is the object of a friend declaration, the lexical
9795 // context will be different from the semantic context.
9796 NewFD->setLexicalDeclContext(CurContext);
9798 if (IsLocalExternDecl)
9799 NewFD->setLocalExternDecl();
9801 if (getLangOpts().CPlusPlus) {
9802 // The rules for implicit inlines changed in C++20 for methods and friends
9803 // with an in-class definition (when such a definition is not attached to
9804 // the global module). User-specified 'inline' overrides this (set when
9805 // the function decl is created above).
9806 // FIXME: We need a better way to separate C++ standard and clang modules.
9807 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9808 !NewFD->getOwningModule() ||
9809 NewFD->getOwningModule()->isGlobalModule() ||
9810 NewFD->getOwningModule()->isHeaderLikeModule();
9811 bool isInline = D.getDeclSpec().isInlineSpecified();
9812 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9813 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9814 isFriend = D.getDeclSpec().isFriendSpecified();
9815 if (isFriend && !isInline && D.isFunctionDefinition()) {
9816 // Pre-C++20 [class.friend]p5
9817 // A function can be defined in a friend declaration of a
9818 // class . . . . Such a function is implicitly inline.
9819 // Post C++20 [class.friend]p7
9820 // Such a function is implicitly an inline function if it is attached
9821 // to the global module.
9822 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9825 // If this is a method defined in an __interface, and is not a constructor
9826 // or an overloaded operator, then set the pure flag (isVirtual will already
9827 // return true).
9828 if (const CXXRecordDecl *Parent =
9829 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9830 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9831 NewFD->setPure(true);
9833 // C++ [class.union]p2
9834 // A union can have member functions, but not virtual functions.
9835 if (isVirtual && Parent->isUnion()) {
9836 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9837 NewFD->setInvalidDecl();
9839 if ((Parent->isClass() || Parent->isStruct()) &&
9840 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9841 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9842 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9843 if (auto *Def = Parent->getDefinition())
9844 Def->setInitMethod(true);
9848 SetNestedNameSpecifier(*this, NewFD, D);
9849 isMemberSpecialization = false;
9850 isFunctionTemplateSpecialization = false;
9851 if (D.isInvalidType())
9852 NewFD->setInvalidDecl();
9854 // Match up the template parameter lists with the scope specifier, then
9855 // determine whether we have a template or a template specialization.
9856 bool Invalid = false;
9857 TemplateParameterList *TemplateParams =
9858 MatchTemplateParametersToScopeSpecifier(
9859 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9860 D.getCXXScopeSpec(),
9861 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9862 ? D.getName().TemplateId
9863 : nullptr,
9864 TemplateParamLists, isFriend, isMemberSpecialization,
9865 Invalid);
9866 if (TemplateParams) {
9867 // Check that we can declare a template here.
9868 if (CheckTemplateDeclScope(S, TemplateParams))
9869 NewFD->setInvalidDecl();
9871 if (TemplateParams->size() > 0) {
9872 // This is a function template
9874 // A destructor cannot be a template.
9875 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9876 Diag(NewFD->getLocation(), diag::err_destructor_template);
9877 NewFD->setInvalidDecl();
9880 // If we're adding a template to a dependent context, we may need to
9881 // rebuilding some of the types used within the template parameter list,
9882 // now that we know what the current instantiation is.
9883 if (DC->isDependentContext()) {
9884 ContextRAII SavedContext(*this, DC);
9885 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9886 Invalid = true;
9889 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9890 NewFD->getLocation(),
9891 Name, TemplateParams,
9892 NewFD);
9893 FunctionTemplate->setLexicalDeclContext(CurContext);
9894 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9896 // For source fidelity, store the other template param lists.
9897 if (TemplateParamLists.size() > 1) {
9898 NewFD->setTemplateParameterListsInfo(Context,
9899 ArrayRef<TemplateParameterList *>(TemplateParamLists)
9900 .drop_back(1));
9902 } else {
9903 // This is a function template specialization.
9904 isFunctionTemplateSpecialization = true;
9905 // For source fidelity, store all the template param lists.
9906 if (TemplateParamLists.size() > 0)
9907 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9909 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9910 if (isFriend) {
9911 // We want to remove the "template<>", found here.
9912 SourceRange RemoveRange = TemplateParams->getSourceRange();
9914 // If we remove the template<> and the name is not a
9915 // template-id, we're actually silently creating a problem:
9916 // the friend declaration will refer to an untemplated decl,
9917 // and clearly the user wants a template specialization. So
9918 // we need to insert '<>' after the name.
9919 SourceLocation InsertLoc;
9920 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9921 InsertLoc = D.getName().getSourceRange().getEnd();
9922 InsertLoc = getLocForEndOfToken(InsertLoc);
9925 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9926 << Name << RemoveRange
9927 << FixItHint::CreateRemoval(RemoveRange)
9928 << FixItHint::CreateInsertion(InsertLoc, "<>");
9929 Invalid = true;
9932 } else {
9933 // Check that we can declare a template here.
9934 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9935 CheckTemplateDeclScope(S, TemplateParamLists.back()))
9936 NewFD->setInvalidDecl();
9938 // All template param lists were matched against the scope specifier:
9939 // this is NOT (an explicit specialization of) a template.
9940 if (TemplateParamLists.size() > 0)
9941 // For source fidelity, store all the template param lists.
9942 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9945 if (Invalid) {
9946 NewFD->setInvalidDecl();
9947 if (FunctionTemplate)
9948 FunctionTemplate->setInvalidDecl();
9951 // C++ [dcl.fct.spec]p5:
9952 // The virtual specifier shall only be used in declarations of
9953 // nonstatic class member functions that appear within a
9954 // member-specification of a class declaration; see 10.3.
9956 if (isVirtual && !NewFD->isInvalidDecl()) {
9957 if (!isVirtualOkay) {
9958 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9959 diag::err_virtual_non_function);
9960 } else if (!CurContext->isRecord()) {
9961 // 'virtual' was specified outside of the class.
9962 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9963 diag::err_virtual_out_of_class)
9964 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9965 } else if (NewFD->getDescribedFunctionTemplate()) {
9966 // C++ [temp.mem]p3:
9967 // A member function template shall not be virtual.
9968 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9969 diag::err_virtual_member_function_template)
9970 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9971 } else {
9972 // Okay: Add virtual to the method.
9973 NewFD->setVirtualAsWritten(true);
9976 if (getLangOpts().CPlusPlus14 &&
9977 NewFD->getReturnType()->isUndeducedType())
9978 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9981 if (getLangOpts().CPlusPlus14 &&
9982 (NewFD->isDependentContext() ||
9983 (isFriend && CurContext->isDependentContext())) &&
9984 NewFD->getReturnType()->isUndeducedType()) {
9985 // If the function template is referenced directly (for instance, as a
9986 // member of the current instantiation), pretend it has a dependent type.
9987 // This is not really justified by the standard, but is the only sane
9988 // thing to do.
9989 // FIXME: For a friend function, we have not marked the function as being
9990 // a friend yet, so 'isDependentContext' on the FD doesn't work.
9991 const FunctionProtoType *FPT =
9992 NewFD->getType()->castAs<FunctionProtoType>();
9993 QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9994 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9995 FPT->getExtProtoInfo()));
9998 // C++ [dcl.fct.spec]p3:
9999 // The inline specifier shall not appear on a block scope function
10000 // declaration.
10001 if (isInline && !NewFD->isInvalidDecl()) {
10002 if (CurContext->isFunctionOrMethod()) {
10003 // 'inline' is not allowed on block scope function declaration.
10004 Diag(D.getDeclSpec().getInlineSpecLoc(),
10005 diag::err_inline_declaration_block_scope) << Name
10006 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10010 // C++ [dcl.fct.spec]p6:
10011 // The explicit specifier shall be used only in the declaration of a
10012 // constructor or conversion function within its class definition;
10013 // see 12.3.1 and 12.3.2.
10014 if (hasExplicit && !NewFD->isInvalidDecl() &&
10015 !isa<CXXDeductionGuideDecl>(NewFD)) {
10016 if (!CurContext->isRecord()) {
10017 // 'explicit' was specified outside of the class.
10018 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10019 diag::err_explicit_out_of_class)
10020 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10021 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10022 !isa<CXXConversionDecl>(NewFD)) {
10023 // 'explicit' was specified on a function that wasn't a constructor
10024 // or conversion function.
10025 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10026 diag::err_explicit_non_ctor_or_conv_function)
10027 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10031 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10032 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10033 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10034 // are implicitly inline.
10035 NewFD->setImplicitlyInline();
10037 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10038 // be either constructors or to return a literal type. Therefore,
10039 // destructors cannot be declared constexpr.
10040 if (isa<CXXDestructorDecl>(NewFD) &&
10041 (!getLangOpts().CPlusPlus20 ||
10042 ConstexprKind == ConstexprSpecKind::Consteval)) {
10043 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10044 << static_cast<int>(ConstexprKind);
10045 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10046 ? ConstexprSpecKind::Unspecified
10047 : ConstexprSpecKind::Constexpr);
10049 // C++20 [dcl.constexpr]p2: An allocation function, or a
10050 // deallocation function shall not be declared with the consteval
10051 // specifier.
10052 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10053 (NewFD->getOverloadedOperator() == OO_New ||
10054 NewFD->getOverloadedOperator() == OO_Array_New ||
10055 NewFD->getOverloadedOperator() == OO_Delete ||
10056 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
10057 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10058 diag::err_invalid_consteval_decl_kind)
10059 << NewFD;
10060 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10064 // If __module_private__ was specified, mark the function accordingly.
10065 if (D.getDeclSpec().isModulePrivateSpecified()) {
10066 if (isFunctionTemplateSpecialization) {
10067 SourceLocation ModulePrivateLoc
10068 = D.getDeclSpec().getModulePrivateSpecLoc();
10069 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10070 << 0
10071 << FixItHint::CreateRemoval(ModulePrivateLoc);
10072 } else {
10073 NewFD->setModulePrivate();
10074 if (FunctionTemplate)
10075 FunctionTemplate->setModulePrivate();
10079 if (isFriend) {
10080 if (FunctionTemplate) {
10081 FunctionTemplate->setObjectOfFriendDecl();
10082 FunctionTemplate->setAccess(AS_public);
10084 NewFD->setObjectOfFriendDecl();
10085 NewFD->setAccess(AS_public);
10088 // If a function is defined as defaulted or deleted, mark it as such now.
10089 // We'll do the relevant checks on defaulted / deleted functions later.
10090 switch (D.getFunctionDefinitionKind()) {
10091 case FunctionDefinitionKind::Declaration:
10092 case FunctionDefinitionKind::Definition:
10093 break;
10095 case FunctionDefinitionKind::Defaulted:
10096 NewFD->setDefaulted();
10097 break;
10099 case FunctionDefinitionKind::Deleted:
10100 NewFD->setDeletedAsWritten();
10101 break;
10104 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10105 D.isFunctionDefinition() && !isInline) {
10106 // Pre C++20 [class.mfct]p2:
10107 // A member function may be defined (8.4) in its class definition, in
10108 // which case it is an inline member function (7.1.2)
10109 // Post C++20 [class.mfct]p1:
10110 // If a member function is attached to the global module and is defined
10111 // in its class definition, it is inline.
10112 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10115 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
10116 !CurContext->isRecord()) {
10117 // C++ [class.static]p1:
10118 // A data or function member of a class may be declared static
10119 // in a class definition, in which case it is a static member of
10120 // the class.
10122 // Complain about the 'static' specifier if it's on an out-of-line
10123 // member function definition.
10125 // MSVC permits the use of a 'static' storage specifier on an out-of-line
10126 // member function template declaration and class member template
10127 // declaration (MSVC versions before 2015), warn about this.
10128 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10129 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10130 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10131 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
10132 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
10133 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10136 // C++11 [except.spec]p15:
10137 // A deallocation function with no exception-specification is treated
10138 // as if it were specified with noexcept(true).
10139 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10140 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10141 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10142 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10143 NewFD->setType(Context.getFunctionType(
10144 FPT->getReturnType(), FPT->getParamTypes(),
10145 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
10147 // C++20 [dcl.inline]/7
10148 // If an inline function or variable that is attached to a named module
10149 // is declared in a definition domain, it shall be defined in that
10150 // domain.
10151 // So, if the current declaration does not have a definition, we must
10152 // check at the end of the TU (or when the PMF starts) to see that we
10153 // have a definition at that point.
10154 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10155 NewFD->hasOwningModule() &&
10156 NewFD->getOwningModule()->isModulePurview()) {
10157 PendingInlineFuncDecls.insert(NewFD);
10161 // Filter out previous declarations that don't match the scope.
10162 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
10163 D.getCXXScopeSpec().isNotEmpty() ||
10164 isMemberSpecialization ||
10165 isFunctionTemplateSpecialization);
10167 // Handle GNU asm-label extension (encoded as an attribute).
10168 if (Expr *E = (Expr*) D.getAsmLabel()) {
10169 // The parser guarantees this is a string.
10170 StringLiteral *SE = cast<StringLiteral>(E);
10171 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10172 /*IsLiteralLabel=*/true,
10173 SE->getStrTokenLoc(0)));
10174 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10175 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10176 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
10177 if (I != ExtnameUndeclaredIdentifiers.end()) {
10178 if (isDeclExternC(NewFD)) {
10179 NewFD->addAttr(I->second);
10180 ExtnameUndeclaredIdentifiers.erase(I);
10181 } else
10182 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10183 << /*Variable*/0 << NewFD;
10187 // Copy the parameter declarations from the declarator D to the function
10188 // declaration NewFD, if they are available. First scavenge them into Params.
10189 SmallVector<ParmVarDecl*, 16> Params;
10190 unsigned FTIIdx;
10191 if (D.isFunctionDeclarator(FTIIdx)) {
10192 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
10194 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10195 // function that takes no arguments, not a function that takes a
10196 // single void argument.
10197 // We let through "const void" here because Sema::GetTypeForDeclarator
10198 // already checks for that case.
10199 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10200 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10201 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10202 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10203 Param->setDeclContext(NewFD);
10204 Params.push_back(Param);
10206 if (Param->isInvalidDecl())
10207 NewFD->setInvalidDecl();
10211 if (!getLangOpts().CPlusPlus) {
10212 // In C, find all the tag declarations from the prototype and move them
10213 // into the function DeclContext. Remove them from the surrounding tag
10214 // injection context of the function, which is typically but not always
10215 // the TU.
10216 DeclContext *PrototypeTagContext =
10217 getTagInjectionContext(NewFD->getLexicalDeclContext());
10218 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10219 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10221 // We don't want to reparent enumerators. Look at their parent enum
10222 // instead.
10223 if (!TD) {
10224 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10225 TD = cast<EnumDecl>(ECD->getDeclContext());
10227 if (!TD)
10228 continue;
10229 DeclContext *TagDC = TD->getLexicalDeclContext();
10230 if (!TagDC->containsDecl(TD))
10231 continue;
10232 TagDC->removeDecl(TD);
10233 TD->setDeclContext(NewFD);
10234 NewFD->addDecl(TD);
10236 // Preserve the lexical DeclContext if it is not the surrounding tag
10237 // injection context of the FD. In this example, the semantic context of
10238 // E will be f and the lexical context will be S, while both the
10239 // semantic and lexical contexts of S will be f:
10240 // void f(struct S { enum E { a } f; } s);
10241 if (TagDC != PrototypeTagContext)
10242 TD->setLexicalDeclContext(TagDC);
10245 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10246 // When we're declaring a function with a typedef, typeof, etc as in the
10247 // following example, we'll need to synthesize (unnamed)
10248 // parameters for use in the declaration.
10250 // @code
10251 // typedef void fn(int);
10252 // fn f;
10253 // @endcode
10255 // Synthesize a parameter for each argument type.
10256 for (const auto &AI : FT->param_types()) {
10257 ParmVarDecl *Param =
10258 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10259 Param->setScopeInfo(0, Params.size());
10260 Params.push_back(Param);
10262 } else {
10263 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10264 "Should not need args for typedef of non-prototype fn");
10267 // Finally, we know we have the right number of parameters, install them.
10268 NewFD->setParams(Params);
10270 if (D.getDeclSpec().isNoreturnSpecified())
10271 NewFD->addAttr(
10272 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10274 // Functions returning a variably modified type violate C99 6.7.5.2p2
10275 // because all functions have linkage.
10276 if (!NewFD->isInvalidDecl() &&
10277 NewFD->getReturnType()->isVariablyModifiedType()) {
10278 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10279 NewFD->setInvalidDecl();
10282 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10283 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10284 !NewFD->hasAttr<SectionAttr>())
10285 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10286 Context, PragmaClangTextSection.SectionName,
10287 PragmaClangTextSection.PragmaLocation));
10289 // Apply an implicit SectionAttr if #pragma code_seg is active.
10290 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10291 !NewFD->hasAttr<SectionAttr>()) {
10292 NewFD->addAttr(SectionAttr::CreateImplicit(
10293 Context, CodeSegStack.CurrentValue->getString(),
10294 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10295 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10296 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10297 ASTContext::PSF_Read,
10298 NewFD))
10299 NewFD->dropAttr<SectionAttr>();
10302 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10303 // active.
10304 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10305 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10306 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10307 Context, PragmaClangTextSection.PragmaLocation));
10309 // Apply an implicit CodeSegAttr from class declspec or
10310 // apply an implicit SectionAttr from #pragma code_seg if active.
10311 if (!NewFD->hasAttr<CodeSegAttr>()) {
10312 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
10313 D.isFunctionDefinition())) {
10314 NewFD->addAttr(SAttr);
10318 // Handle attributes.
10319 ProcessDeclAttributes(S, NewFD, D);
10320 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10321 if (NewTVA && !NewTVA->isDefaultVersion() &&
10322 !Context.getTargetInfo().hasFeature("fmv")) {
10323 // Don't add to scope fmv functions declarations if fmv disabled
10324 AddToScope = false;
10325 return NewFD;
10328 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10329 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10330 // type.
10332 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10333 // type declaration will generate a compilation error.
10334 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10335 if (AddressSpace != LangAS::Default) {
10336 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10337 NewFD->setInvalidDecl();
10341 if (getLangOpts().HLSL) {
10342 auto &TargetInfo = getASTContext().getTargetInfo();
10343 // Skip operator overload which not identifier.
10344 // Also make sure NewFD is in translation-unit scope.
10345 if (!NewFD->isInvalidDecl() && Name.isIdentifier() &&
10346 NewFD->getName() == TargetInfo.getTargetOpts().HLSLEntry &&
10347 S->getDepth() == 0) {
10348 CheckHLSLEntryPoint(NewFD);
10349 if (!NewFD->isInvalidDecl()) {
10350 auto Env = TargetInfo.getTriple().getEnvironment();
10351 HLSLShaderAttr::ShaderType ShaderType =
10352 static_cast<HLSLShaderAttr::ShaderType>(
10353 hlsl::getStageFromEnvironment(Env));
10354 // To share code with HLSLShaderAttr, add HLSLShaderAttr to entry
10355 // function.
10356 if (HLSLShaderAttr *NT = NewFD->getAttr<HLSLShaderAttr>()) {
10357 if (NT->getType() != ShaderType)
10358 Diag(NT->getLocation(), diag::err_hlsl_entry_shader_attr_mismatch)
10359 << NT;
10360 } else {
10361 NewFD->addAttr(HLSLShaderAttr::Create(Context, ShaderType,
10362 NewFD->getBeginLoc()));
10368 if (!getLangOpts().CPlusPlus) {
10369 // Perform semantic checking on the function declaration.
10370 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10371 CheckMain(NewFD, D.getDeclSpec());
10373 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10374 CheckMSVCRTEntryPoint(NewFD);
10376 if (!NewFD->isInvalidDecl())
10377 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10378 isMemberSpecialization,
10379 D.isFunctionDefinition()));
10380 else if (!Previous.empty())
10381 // Recover gracefully from an invalid redeclaration.
10382 D.setRedeclaration(true);
10383 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10384 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10385 "previous declaration set still overloaded");
10387 // Diagnose no-prototype function declarations with calling conventions that
10388 // don't support variadic calls. Only do this in C and do it after merging
10389 // possibly prototyped redeclarations.
10390 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10391 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10392 CallingConv CC = FT->getExtInfo().getCC();
10393 if (!supportsVariadicCall(CC)) {
10394 // Windows system headers sometimes accidentally use stdcall without
10395 // (void) parameters, so we relax this to a warning.
10396 int DiagID =
10397 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10398 Diag(NewFD->getLocation(), DiagID)
10399 << FunctionType::getNameForCallConv(CC);
10403 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10404 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10405 checkNonTrivialCUnion(NewFD->getReturnType(),
10406 NewFD->getReturnTypeSourceRange().getBegin(),
10407 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
10408 } else {
10409 // C++11 [replacement.functions]p3:
10410 // The program's definitions shall not be specified as inline.
10412 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10414 // Suppress the diagnostic if the function is __attribute__((used)), since
10415 // that forces an external definition to be emitted.
10416 if (D.getDeclSpec().isInlineSpecified() &&
10417 NewFD->isReplaceableGlobalAllocationFunction() &&
10418 !NewFD->hasAttr<UsedAttr>())
10419 Diag(D.getDeclSpec().getInlineSpecLoc(),
10420 diag::ext_operator_new_delete_declared_inline)
10421 << NewFD->getDeclName();
10423 // If the declarator is a template-id, translate the parser's template
10424 // argument list into our AST format.
10425 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10426 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
10427 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10428 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10429 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10430 TemplateId->NumArgs);
10431 translateTemplateArguments(TemplateArgsPtr,
10432 TemplateArgs);
10434 HasExplicitTemplateArgs = true;
10436 if (NewFD->isInvalidDecl()) {
10437 HasExplicitTemplateArgs = false;
10438 } else if (FunctionTemplate) {
10439 // Function template with explicit template arguments.
10440 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10441 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10443 HasExplicitTemplateArgs = false;
10444 } else {
10445 assert((isFunctionTemplateSpecialization ||
10446 D.getDeclSpec().isFriendSpecified()) &&
10447 "should have a 'template<>' for this decl");
10448 // "friend void foo<>(int);" is an implicit specialization decl.
10449 isFunctionTemplateSpecialization = true;
10451 } else if (isFriend && isFunctionTemplateSpecialization) {
10452 // This combination is only possible in a recovery case; the user
10453 // wrote something like:
10454 // template <> friend void foo(int);
10455 // which we're recovering from as if the user had written:
10456 // friend void foo<>(int);
10457 // Go ahead and fake up a template id.
10458 HasExplicitTemplateArgs = true;
10459 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
10460 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
10463 // We do not add HD attributes to specializations here because
10464 // they may have different constexpr-ness compared to their
10465 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10466 // may end up with different effective targets. Instead, a
10467 // specialization inherits its target attributes from its template
10468 // in the CheckFunctionTemplateSpecialization() call below.
10469 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10470 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
10472 // If it's a friend (and only if it's a friend), it's possible
10473 // that either the specialized function type or the specialized
10474 // template is dependent, and therefore matching will fail. In
10475 // this case, don't check the specialization yet.
10476 if (isFunctionTemplateSpecialization && isFriend &&
10477 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
10478 TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
10479 TemplateArgs.arguments()))) {
10480 assert(HasExplicitTemplateArgs &&
10481 "friend function specialization without template args");
10482 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
10483 Previous))
10484 NewFD->setInvalidDecl();
10485 } else if (isFunctionTemplateSpecialization) {
10486 if (CurContext->isDependentContext() && CurContext->isRecord()
10487 && !isFriend) {
10488 isDependentClassScopeExplicitSpecialization = true;
10489 } else if (!NewFD->isInvalidDecl() &&
10490 CheckFunctionTemplateSpecialization(
10491 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
10492 Previous))
10493 NewFD->setInvalidDecl();
10495 // C++ [dcl.stc]p1:
10496 // A storage-class-specifier shall not be specified in an explicit
10497 // specialization (14.7.3)
10498 FunctionTemplateSpecializationInfo *Info =
10499 NewFD->getTemplateSpecializationInfo();
10500 if (Info && SC != SC_None) {
10501 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10502 Diag(NewFD->getLocation(),
10503 diag::err_explicit_specialization_inconsistent_storage_class)
10504 << SC
10505 << FixItHint::CreateRemoval(
10506 D.getDeclSpec().getStorageClassSpecLoc());
10508 else
10509 Diag(NewFD->getLocation(),
10510 diag::ext_explicit_specialization_storage_class)
10511 << FixItHint::CreateRemoval(
10512 D.getDeclSpec().getStorageClassSpecLoc());
10514 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10515 if (CheckMemberSpecialization(NewFD, Previous))
10516 NewFD->setInvalidDecl();
10519 // Perform semantic checking on the function declaration.
10520 if (!isDependentClassScopeExplicitSpecialization) {
10521 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10522 CheckMain(NewFD, D.getDeclSpec());
10524 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10525 CheckMSVCRTEntryPoint(NewFD);
10527 if (!NewFD->isInvalidDecl())
10528 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10529 isMemberSpecialization,
10530 D.isFunctionDefinition()));
10531 else if (!Previous.empty())
10532 // Recover gracefully from an invalid redeclaration.
10533 D.setRedeclaration(true);
10536 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10537 !D.isRedeclaration() ||
10538 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10539 "previous declaration set still overloaded");
10541 NamedDecl *PrincipalDecl = (FunctionTemplate
10542 ? cast<NamedDecl>(FunctionTemplate)
10543 : NewFD);
10545 if (isFriend && NewFD->getPreviousDecl()) {
10546 AccessSpecifier Access = AS_public;
10547 if (!NewFD->isInvalidDecl())
10548 Access = NewFD->getPreviousDecl()->getAccess();
10550 NewFD->setAccess(Access);
10551 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10554 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10555 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10556 PrincipalDecl->setNonMemberOperator();
10558 // If we have a function template, check the template parameter
10559 // list. This will check and merge default template arguments.
10560 if (FunctionTemplate) {
10561 FunctionTemplateDecl *PrevTemplate =
10562 FunctionTemplate->getPreviousDecl();
10563 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10564 PrevTemplate ? PrevTemplate->getTemplateParameters()
10565 : nullptr,
10566 D.getDeclSpec().isFriendSpecified()
10567 ? (D.isFunctionDefinition()
10568 ? TPC_FriendFunctionTemplateDefinition
10569 : TPC_FriendFunctionTemplate)
10570 : (D.getCXXScopeSpec().isSet() &&
10571 DC && DC->isRecord() &&
10572 DC->isDependentContext())
10573 ? TPC_ClassTemplateMember
10574 : TPC_FunctionTemplate);
10577 if (NewFD->isInvalidDecl()) {
10578 // Ignore all the rest of this.
10579 } else if (!D.isRedeclaration()) {
10580 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10581 AddToScope };
10582 // Fake up an access specifier if it's supposed to be a class member.
10583 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10584 NewFD->setAccess(AS_public);
10586 // Qualified decls generally require a previous declaration.
10587 if (D.getCXXScopeSpec().isSet()) {
10588 // ...with the major exception of templated-scope or
10589 // dependent-scope friend declarations.
10591 // TODO: we currently also suppress this check in dependent
10592 // contexts because (1) the parameter depth will be off when
10593 // matching friend templates and (2) we might actually be
10594 // selecting a friend based on a dependent factor. But there
10595 // are situations where these conditions don't apply and we
10596 // can actually do this check immediately.
10598 // Unless the scope is dependent, it's always an error if qualified
10599 // redeclaration lookup found nothing at all. Diagnose that now;
10600 // nothing will diagnose that error later.
10601 if (isFriend &&
10602 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10603 (!Previous.empty() && CurContext->isDependentContext()))) {
10604 // ignore these
10605 } else if (NewFD->isCPUDispatchMultiVersion() ||
10606 NewFD->isCPUSpecificMultiVersion()) {
10607 // ignore this, we allow the redeclaration behavior here to create new
10608 // versions of the function.
10609 } else {
10610 // The user tried to provide an out-of-line definition for a
10611 // function that is a member of a class or namespace, but there
10612 // was no such member function declared (C++ [class.mfct]p2,
10613 // C++ [namespace.memdef]p2). For example:
10615 // class X {
10616 // void f() const;
10617 // };
10619 // void X::f() { } // ill-formed
10621 // Complain about this problem, and attempt to suggest close
10622 // matches (e.g., those that differ only in cv-qualifiers and
10623 // whether the parameter types are references).
10625 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10626 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10627 AddToScope = ExtraArgs.AddToScope;
10628 return Result;
10632 // Unqualified local friend declarations are required to resolve
10633 // to something.
10634 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10635 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10636 *this, Previous, NewFD, ExtraArgs, true, S)) {
10637 AddToScope = ExtraArgs.AddToScope;
10638 return Result;
10641 } else if (!D.isFunctionDefinition() &&
10642 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10643 !isFriend && !isFunctionTemplateSpecialization &&
10644 !isMemberSpecialization) {
10645 // An out-of-line member function declaration must also be a
10646 // definition (C++ [class.mfct]p2).
10647 // Note that this is not the case for explicit specializations of
10648 // function templates or member functions of class templates, per
10649 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10650 // extension for compatibility with old SWIG code which likes to
10651 // generate them.
10652 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10653 << D.getCXXScopeSpec().getRange();
10657 // If this is the first declaration of a library builtin function, add
10658 // attributes as appropriate.
10659 if (!D.isRedeclaration()) {
10660 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10661 if (unsigned BuiltinID = II->getBuiltinID()) {
10662 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10663 if (!InStdNamespace &&
10664 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10665 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10666 // Validate the type matches unless this builtin is specified as
10667 // matching regardless of its declared type.
10668 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10669 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10670 } else {
10671 ASTContext::GetBuiltinTypeError Error;
10672 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10673 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10675 if (!Error && !BuiltinType.isNull() &&
10676 Context.hasSameFunctionTypeIgnoringExceptionSpec(
10677 NewFD->getType(), BuiltinType))
10678 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10681 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10682 isStdBuiltin(Context, NewFD, BuiltinID)) {
10683 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10689 ProcessPragmaWeak(S, NewFD);
10690 checkAttributesAfterMerging(*this, *NewFD);
10692 AddKnownFunctionAttributes(NewFD);
10694 if (NewFD->hasAttr<OverloadableAttr>() &&
10695 !NewFD->getType()->getAs<FunctionProtoType>()) {
10696 Diag(NewFD->getLocation(),
10697 diag::err_attribute_overloadable_no_prototype)
10698 << NewFD;
10699 NewFD->dropAttr<OverloadableAttr>();
10702 // If there's a #pragma GCC visibility in scope, and this isn't a class
10703 // member, set the visibility of this function.
10704 if (!DC->isRecord() && NewFD->isExternallyVisible())
10705 AddPushedVisibilityAttribute(NewFD);
10707 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10708 // marking the function.
10709 AddCFAuditedAttribute(NewFD);
10711 // If this is a function definition, check if we have to apply any
10712 // attributes (i.e. optnone and no_builtin) due to a pragma.
10713 if (D.isFunctionDefinition()) {
10714 AddRangeBasedOptnone(NewFD);
10715 AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10716 AddSectionMSAllocText(NewFD);
10717 ModifyFnAttributesMSPragmaOptimize(NewFD);
10720 // If this is the first declaration of an extern C variable, update
10721 // the map of such variables.
10722 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10723 isIncompleteDeclExternC(*this, NewFD))
10724 RegisterLocallyScopedExternCDecl(NewFD, S);
10726 // Set this FunctionDecl's range up to the right paren.
10727 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10729 if (D.isRedeclaration() && !Previous.empty()) {
10730 NamedDecl *Prev = Previous.getRepresentativeDecl();
10731 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10732 isMemberSpecialization ||
10733 isFunctionTemplateSpecialization,
10734 D.isFunctionDefinition());
10737 if (getLangOpts().CUDA) {
10738 IdentifierInfo *II = NewFD->getIdentifier();
10739 if (II && II->isStr(getCudaConfigureFuncName()) &&
10740 !NewFD->isInvalidDecl() &&
10741 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10742 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10743 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10744 << getCudaConfigureFuncName();
10745 Context.setcudaConfigureCallDecl(NewFD);
10748 // Variadic functions, other than a *declaration* of printf, are not allowed
10749 // in device-side CUDA code, unless someone passed
10750 // -fcuda-allow-variadic-functions.
10751 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10752 (NewFD->hasAttr<CUDADeviceAttr>() ||
10753 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10754 !(II && II->isStr("printf") && NewFD->isExternC() &&
10755 !D.isFunctionDefinition())) {
10756 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10760 MarkUnusedFileScopedDecl(NewFD);
10764 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10765 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10766 if (SC == SC_Static) {
10767 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10768 D.setInvalidType();
10771 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10772 if (!NewFD->getReturnType()->isVoidType()) {
10773 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10774 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10775 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10776 : FixItHint());
10777 D.setInvalidType();
10780 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10781 for (auto *Param : NewFD->parameters())
10782 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10784 if (getLangOpts().OpenCLCPlusPlus) {
10785 if (DC->isRecord()) {
10786 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10787 D.setInvalidType();
10789 if (FunctionTemplate) {
10790 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10791 D.setInvalidType();
10796 if (getLangOpts().CPlusPlus) {
10797 // Precalculate whether this is a friend function template with a constraint
10798 // that depends on an enclosing template, per [temp.friend]p9.
10799 if (isFriend && FunctionTemplate &&
10800 FriendConstraintsDependOnEnclosingTemplate(NewFD))
10801 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
10803 if (FunctionTemplate) {
10804 if (NewFD->isInvalidDecl())
10805 FunctionTemplate->setInvalidDecl();
10806 return FunctionTemplate;
10809 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10810 CompleteMemberSpecialization(NewFD, Previous);
10813 for (const ParmVarDecl *Param : NewFD->parameters()) {
10814 QualType PT = Param->getType();
10816 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10817 // types.
10818 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10819 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10820 QualType ElemTy = PipeTy->getElementType();
10821 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10822 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10823 D.setInvalidType();
10827 // WebAssembly tables can't be used as function parameters.
10828 if (Context.getTargetInfo().getTriple().isWasm()) {
10829 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
10830 Diag(Param->getTypeSpecStartLoc(),
10831 diag::err_wasm_table_as_function_parameter);
10832 D.setInvalidType();
10837 // Here we have an function template explicit specialization at class scope.
10838 // The actual specialization will be postponed to template instatiation
10839 // time via the ClassScopeFunctionSpecializationDecl node.
10840 if (isDependentClassScopeExplicitSpecialization) {
10841 ClassScopeFunctionSpecializationDecl *NewSpec =
10842 ClassScopeFunctionSpecializationDecl::Create(
10843 Context, CurContext, NewFD->getLocation(),
10844 cast<CXXMethodDecl>(NewFD),
10845 HasExplicitTemplateArgs, TemplateArgs);
10846 CurContext->addDecl(NewSpec);
10847 AddToScope = false;
10850 // Diagnose availability attributes. Availability cannot be used on functions
10851 // that are run during load/unload.
10852 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10853 if (NewFD->hasAttr<ConstructorAttr>()) {
10854 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10855 << 1;
10856 NewFD->dropAttr<AvailabilityAttr>();
10858 if (NewFD->hasAttr<DestructorAttr>()) {
10859 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10860 << 2;
10861 NewFD->dropAttr<AvailabilityAttr>();
10865 // Diagnose no_builtin attribute on function declaration that are not a
10866 // definition.
10867 // FIXME: We should really be doing this in
10868 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10869 // the FunctionDecl and at this point of the code
10870 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10871 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10872 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10873 switch (D.getFunctionDefinitionKind()) {
10874 case FunctionDefinitionKind::Defaulted:
10875 case FunctionDefinitionKind::Deleted:
10876 Diag(NBA->getLocation(),
10877 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10878 << NBA->getSpelling();
10879 break;
10880 case FunctionDefinitionKind::Declaration:
10881 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10882 << NBA->getSpelling();
10883 break;
10884 case FunctionDefinitionKind::Definition:
10885 break;
10888 return NewFD;
10891 /// Return a CodeSegAttr from a containing class. The Microsoft docs say
10892 /// when __declspec(code_seg) "is applied to a class, all member functions of
10893 /// the class and nested classes -- this includes compiler-generated special
10894 /// member functions -- are put in the specified segment."
10895 /// The actual behavior is a little more complicated. The Microsoft compiler
10896 /// won't check outer classes if there is an active value from #pragma code_seg.
10897 /// The CodeSeg is always applied from the direct parent but only from outer
10898 /// classes when the #pragma code_seg stack is empty. See:
10899 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10900 /// available since MS has removed the page.
10901 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10902 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10903 if (!Method)
10904 return nullptr;
10905 const CXXRecordDecl *Parent = Method->getParent();
10906 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10907 Attr *NewAttr = SAttr->clone(S.getASTContext());
10908 NewAttr->setImplicit(true);
10909 return NewAttr;
10912 // The Microsoft compiler won't check outer classes for the CodeSeg
10913 // when the #pragma code_seg stack is active.
10914 if (S.CodeSegStack.CurrentValue)
10915 return nullptr;
10917 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10918 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10919 Attr *NewAttr = SAttr->clone(S.getASTContext());
10920 NewAttr->setImplicit(true);
10921 return NewAttr;
10924 return nullptr;
10927 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10928 /// containing class. Otherwise it will return implicit SectionAttr if the
10929 /// function is a definition and there is an active value on CodeSegStack
10930 /// (from the current #pragma code-seg value).
10932 /// \param FD Function being declared.
10933 /// \param IsDefinition Whether it is a definition or just a declaration.
10934 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10935 /// nullptr if no attribute should be added.
10936 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10937 bool IsDefinition) {
10938 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10939 return A;
10940 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10941 CodeSegStack.CurrentValue)
10942 return SectionAttr::CreateImplicit(
10943 getASTContext(), CodeSegStack.CurrentValue->getString(),
10944 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
10945 return nullptr;
10948 /// Determines if we can perform a correct type check for \p D as a
10949 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10950 /// best-effort check.
10952 /// \param NewD The new declaration.
10953 /// \param OldD The old declaration.
10954 /// \param NewT The portion of the type of the new declaration to check.
10955 /// \param OldT The portion of the type of the old declaration to check.
10956 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10957 QualType NewT, QualType OldT) {
10958 if (!NewD->getLexicalDeclContext()->isDependentContext())
10959 return true;
10961 // For dependently-typed local extern declarations and friends, we can't
10962 // perform a correct type check in general until instantiation:
10964 // int f();
10965 // template<typename T> void g() { T f(); }
10967 // (valid if g() is only instantiated with T = int).
10968 if (NewT->isDependentType() &&
10969 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10970 return false;
10972 // Similarly, if the previous declaration was a dependent local extern
10973 // declaration, we don't really know its type yet.
10974 if (OldT->isDependentType() && OldD->isLocalExternDecl())
10975 return false;
10977 return true;
10980 /// Checks if the new declaration declared in dependent context must be
10981 /// put in the same redeclaration chain as the specified declaration.
10983 /// \param D Declaration that is checked.
10984 /// \param PrevDecl Previous declaration found with proper lookup method for the
10985 /// same declaration name.
10986 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10987 /// belongs to.
10989 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10990 if (!D->getLexicalDeclContext()->isDependentContext())
10991 return true;
10993 // Don't chain dependent friend function definitions until instantiation, to
10994 // permit cases like
10996 // void func();
10997 // template<typename T> class C1 { friend void func() {} };
10998 // template<typename T> class C2 { friend void func() {} };
11000 // ... which is valid if only one of C1 and C2 is ever instantiated.
11002 // FIXME: This need only apply to function definitions. For now, we proxy
11003 // this by checking for a file-scope function. We do not want this to apply
11004 // to friend declarations nominating member functions, because that gets in
11005 // the way of access checks.
11006 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11007 return false;
11009 auto *VD = dyn_cast<ValueDecl>(D);
11010 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11011 return !VD || !PrevVD ||
11012 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11013 PrevVD->getType());
11016 /// Check the target or target_version attribute of the function for
11017 /// MultiVersion validity.
11019 /// Returns true if there was an error, false otherwise.
11020 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11021 const auto *TA = FD->getAttr<TargetAttr>();
11022 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11023 assert(
11024 (TA || TVA) &&
11025 "MultiVersion candidate requires a target or target_version attribute");
11026 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11027 enum ErrType { Feature = 0, Architecture = 1 };
11029 if (TA) {
11030 ParsedTargetAttr ParseInfo =
11031 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11032 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11033 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11034 << Architecture << ParseInfo.CPU;
11035 return true;
11037 for (const auto &Feat : ParseInfo.Features) {
11038 auto BareFeat = StringRef{Feat}.substr(1);
11039 if (Feat[0] == '-') {
11040 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11041 << Feature << ("no-" + BareFeat).str();
11042 return true;
11045 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11046 !TargetInfo.isValidFeatureName(BareFeat)) {
11047 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11048 << Feature << BareFeat;
11049 return true;
11054 if (TVA) {
11055 llvm::SmallVector<StringRef, 8> Feats;
11056 TVA->getFeatures(Feats);
11057 for (const auto &Feat : Feats) {
11058 if (!TargetInfo.validateCpuSupports(Feat)) {
11059 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11060 << Feature << Feat;
11061 return true;
11065 return false;
11068 // Provide a white-list of attributes that are allowed to be combined with
11069 // multiversion functions.
11070 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11071 MultiVersionKind MVKind) {
11072 // Note: this list/diagnosis must match the list in
11073 // checkMultiversionAttributesAllSame.
11074 switch (Kind) {
11075 default:
11076 return false;
11077 case attr::Used:
11078 return MVKind == MultiVersionKind::Target;
11079 case attr::NonNull:
11080 case attr::NoThrow:
11081 return true;
11085 static bool checkNonMultiVersionCompatAttributes(Sema &S,
11086 const FunctionDecl *FD,
11087 const FunctionDecl *CausedFD,
11088 MultiVersionKind MVKind) {
11089 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11090 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11091 << static_cast<unsigned>(MVKind) << A;
11092 if (CausedFD)
11093 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11094 return true;
11097 for (const Attr *A : FD->attrs()) {
11098 switch (A->getKind()) {
11099 case attr::CPUDispatch:
11100 case attr::CPUSpecific:
11101 if (MVKind != MultiVersionKind::CPUDispatch &&
11102 MVKind != MultiVersionKind::CPUSpecific)
11103 return Diagnose(S, A);
11104 break;
11105 case attr::Target:
11106 if (MVKind != MultiVersionKind::Target)
11107 return Diagnose(S, A);
11108 break;
11109 case attr::TargetVersion:
11110 if (MVKind != MultiVersionKind::TargetVersion)
11111 return Diagnose(S, A);
11112 break;
11113 case attr::TargetClones:
11114 if (MVKind != MultiVersionKind::TargetClones)
11115 return Diagnose(S, A);
11116 break;
11117 default:
11118 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11119 return Diagnose(S, A);
11120 break;
11123 return false;
11126 bool Sema::areMultiversionVariantFunctionsCompatible(
11127 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11128 const PartialDiagnostic &NoProtoDiagID,
11129 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11130 const PartialDiagnosticAt &NoSupportDiagIDAt,
11131 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11132 bool ConstexprSupported, bool CLinkageMayDiffer) {
11133 enum DoesntSupport {
11134 FuncTemplates = 0,
11135 VirtFuncs = 1,
11136 DeducedReturn = 2,
11137 Constructors = 3,
11138 Destructors = 4,
11139 DeletedFuncs = 5,
11140 DefaultedFuncs = 6,
11141 ConstexprFuncs = 7,
11142 ConstevalFuncs = 8,
11143 Lambda = 9,
11145 enum Different {
11146 CallingConv = 0,
11147 ReturnType = 1,
11148 ConstexprSpec = 2,
11149 InlineSpec = 3,
11150 Linkage = 4,
11151 LanguageLinkage = 5,
11154 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11155 !OldFD->getType()->getAs<FunctionProtoType>()) {
11156 Diag(OldFD->getLocation(), NoProtoDiagID);
11157 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11158 return true;
11161 if (NoProtoDiagID.getDiagID() != 0 &&
11162 !NewFD->getType()->getAs<FunctionProtoType>())
11163 return Diag(NewFD->getLocation(), NoProtoDiagID);
11165 if (!TemplatesSupported &&
11166 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11167 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11168 << FuncTemplates;
11170 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11171 if (NewCXXFD->isVirtual())
11172 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11173 << VirtFuncs;
11175 if (isa<CXXConstructorDecl>(NewCXXFD))
11176 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11177 << Constructors;
11179 if (isa<CXXDestructorDecl>(NewCXXFD))
11180 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11181 << Destructors;
11184 if (NewFD->isDeleted())
11185 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11186 << DeletedFuncs;
11188 if (NewFD->isDefaulted())
11189 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11190 << DefaultedFuncs;
11192 if (!ConstexprSupported && NewFD->isConstexpr())
11193 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11194 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11196 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11197 const auto *NewType = cast<FunctionType>(NewQType);
11198 QualType NewReturnType = NewType->getReturnType();
11200 if (NewReturnType->isUndeducedType())
11201 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11202 << DeducedReturn;
11204 // Ensure the return type is identical.
11205 if (OldFD) {
11206 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11207 const auto *OldType = cast<FunctionType>(OldQType);
11208 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11209 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11211 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
11212 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11214 QualType OldReturnType = OldType->getReturnType();
11216 if (OldReturnType != NewReturnType)
11217 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11219 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11220 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11222 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11223 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11225 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11226 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11228 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11229 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11231 if (CheckEquivalentExceptionSpec(
11232 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
11233 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
11234 return true;
11236 return false;
11239 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11240 const FunctionDecl *NewFD,
11241 bool CausesMV,
11242 MultiVersionKind MVKind) {
11243 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11244 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11245 if (OldFD)
11246 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11247 return true;
11250 bool IsCPUSpecificCPUDispatchMVKind =
11251 MVKind == MultiVersionKind::CPUDispatch ||
11252 MVKind == MultiVersionKind::CPUSpecific;
11254 if (CausesMV && OldFD &&
11255 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11256 return true;
11258 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11259 return true;
11261 // Only allow transition to MultiVersion if it hasn't been used.
11262 if (OldFD && CausesMV && OldFD->isUsed(false))
11263 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11265 return S.areMultiversionVariantFunctionsCompatible(
11266 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11267 PartialDiagnosticAt(NewFD->getLocation(),
11268 S.PDiag(diag::note_multiversioning_caused_here)),
11269 PartialDiagnosticAt(NewFD->getLocation(),
11270 S.PDiag(diag::err_multiversion_doesnt_support)
11271 << static_cast<unsigned>(MVKind)),
11272 PartialDiagnosticAt(NewFD->getLocation(),
11273 S.PDiag(diag::err_multiversion_diff)),
11274 /*TemplatesSupported=*/false,
11275 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11276 /*CLinkageMayDiffer=*/false);
11279 /// Check the validity of a multiversion function declaration that is the
11280 /// first of its kind. Also sets the multiversion'ness' of the function itself.
11282 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11284 /// Returns true if there was an error, false otherwise.
11285 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11286 MultiVersionKind MVKind = FD->getMultiVersionKind();
11287 assert(MVKind != MultiVersionKind::None &&
11288 "Function lacks multiversion attribute");
11289 const auto *TA = FD->getAttr<TargetAttr>();
11290 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11291 // Target and target_version only causes MV if it is default, otherwise this
11292 // is a normal function.
11293 if ((TA && !TA->isDefaultVersion()) || (TVA && !TVA->isDefaultVersion()))
11294 return false;
11296 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11297 FD->setInvalidDecl();
11298 return true;
11301 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11302 FD->setInvalidDecl();
11303 return true;
11306 FD->setIsMultiVersion();
11307 return false;
11310 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11311 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11312 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11313 return true;
11316 return false;
11319 static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11320 FunctionDecl *NewFD,
11321 bool &Redeclaration,
11322 NamedDecl *&OldDecl,
11323 LookupResult &Previous) {
11324 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11325 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11326 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11327 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11328 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11329 // to change, this is a simple redeclaration.
11330 if ((NewTA && !NewTA->isDefaultVersion() &&
11331 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) ||
11332 (NewTVA && !NewTVA->isDefaultVersion() &&
11333 (!OldTVA || OldTVA->getName() == NewTVA->getName())))
11334 return false;
11336 // Otherwise, this decl causes MultiVersioning.
11337 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11338 NewTVA ? MultiVersionKind::TargetVersion
11339 : MultiVersionKind::Target)) {
11340 NewFD->setInvalidDecl();
11341 return true;
11344 if (CheckMultiVersionValue(S, NewFD)) {
11345 NewFD->setInvalidDecl();
11346 return true;
11349 // If this is 'default', permit the forward declaration.
11350 if (!OldFD->isMultiVersion() &&
11351 ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11352 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA))) {
11353 Redeclaration = true;
11354 OldDecl = OldFD;
11355 OldFD->setIsMultiVersion();
11356 NewFD->setIsMultiVersion();
11357 return false;
11360 if (CheckMultiVersionValue(S, OldFD)) {
11361 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11362 NewFD->setInvalidDecl();
11363 return true;
11366 if (NewTA) {
11367 ParsedTargetAttr OldParsed =
11368 S.getASTContext().getTargetInfo().parseTargetAttr(
11369 OldTA->getFeaturesStr());
11370 llvm::sort(OldParsed.Features);
11371 ParsedTargetAttr NewParsed =
11372 S.getASTContext().getTargetInfo().parseTargetAttr(
11373 NewTA->getFeaturesStr());
11374 // Sort order doesn't matter, it just needs to be consistent.
11375 llvm::sort(NewParsed.Features);
11376 if (OldParsed == NewParsed) {
11377 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11378 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11379 NewFD->setInvalidDecl();
11380 return true;
11384 if (NewTVA) {
11385 llvm::SmallVector<StringRef, 8> Feats;
11386 OldTVA->getFeatures(Feats);
11387 llvm::sort(Feats);
11388 llvm::SmallVector<StringRef, 8> NewFeats;
11389 NewTVA->getFeatures(NewFeats);
11390 llvm::sort(NewFeats);
11392 if (Feats == NewFeats) {
11393 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11394 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11395 NewFD->setInvalidDecl();
11396 return true;
11400 for (const auto *FD : OldFD->redecls()) {
11401 const auto *CurTA = FD->getAttr<TargetAttr>();
11402 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11403 // We allow forward declarations before ANY multiversioning attributes, but
11404 // nothing after the fact.
11405 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11406 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11407 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11408 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11409 << (NewTA ? 0 : 2);
11410 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11411 NewFD->setInvalidDecl();
11412 return true;
11416 OldFD->setIsMultiVersion();
11417 NewFD->setIsMultiVersion();
11418 Redeclaration = false;
11419 OldDecl = nullptr;
11420 Previous.clear();
11421 return false;
11424 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
11425 MultiVersionKind New) {
11426 if (Old == New || Old == MultiVersionKind::None ||
11427 New == MultiVersionKind::None)
11428 return true;
11430 return (Old == MultiVersionKind::CPUDispatch &&
11431 New == MultiVersionKind::CPUSpecific) ||
11432 (Old == MultiVersionKind::CPUSpecific &&
11433 New == MultiVersionKind::CPUDispatch);
11436 /// Check the validity of a new function declaration being added to an existing
11437 /// multiversioned declaration collection.
11438 static bool CheckMultiVersionAdditionalDecl(
11439 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11440 MultiVersionKind NewMVKind, const CPUDispatchAttr *NewCPUDisp,
11441 const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones,
11442 bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
11443 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11444 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11445 MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11446 // Disallow mixing of multiversioning types.
11447 if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
11448 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11449 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11450 NewFD->setInvalidDecl();
11451 return true;
11454 ParsedTargetAttr NewParsed;
11455 if (NewTA) {
11456 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11457 NewTA->getFeaturesStr());
11458 llvm::sort(NewParsed.Features);
11460 llvm::SmallVector<StringRef, 8> NewFeats;
11461 if (NewTVA) {
11462 NewTVA->getFeatures(NewFeats);
11463 llvm::sort(NewFeats);
11466 bool UseMemberUsingDeclRules =
11467 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11469 bool MayNeedOverloadableChecks =
11470 AllowOverloadingOfFunction(Previous, S.Context, NewFD);
11472 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11473 // of a previous member of the MultiVersion set.
11474 for (NamedDecl *ND : Previous) {
11475 FunctionDecl *CurFD = ND->getAsFunction();
11476 if (!CurFD || CurFD->isInvalidDecl())
11477 continue;
11478 if (MayNeedOverloadableChecks &&
11479 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11480 continue;
11482 if (NewMVKind == MultiVersionKind::None &&
11483 OldMVKind == MultiVersionKind::TargetVersion) {
11484 NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11485 S.Context, "default", NewFD->getSourceRange()));
11486 NewFD->setIsMultiVersion();
11487 NewMVKind = MultiVersionKind::TargetVersion;
11488 if (!NewTVA) {
11489 NewTVA = NewFD->getAttr<TargetVersionAttr>();
11490 NewTVA->getFeatures(NewFeats);
11491 llvm::sort(NewFeats);
11495 switch (NewMVKind) {
11496 case MultiVersionKind::None:
11497 assert(OldMVKind == MultiVersionKind::TargetClones &&
11498 "Only target_clones can be omitted in subsequent declarations");
11499 break;
11500 case MultiVersionKind::Target: {
11501 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11502 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11503 NewFD->setIsMultiVersion();
11504 Redeclaration = true;
11505 OldDecl = ND;
11506 return false;
11509 ParsedTargetAttr CurParsed =
11510 S.getASTContext().getTargetInfo().parseTargetAttr(
11511 CurTA->getFeaturesStr());
11512 llvm::sort(CurParsed.Features);
11513 if (CurParsed == NewParsed) {
11514 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11515 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11516 NewFD->setInvalidDecl();
11517 return true;
11519 break;
11521 case MultiVersionKind::TargetVersion: {
11522 const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>();
11523 if (CurTVA->getName() == NewTVA->getName()) {
11524 NewFD->setIsMultiVersion();
11525 Redeclaration = true;
11526 OldDecl = ND;
11527 return false;
11529 llvm::SmallVector<StringRef, 8> CurFeats;
11530 if (CurTVA) {
11531 CurTVA->getFeatures(CurFeats);
11532 llvm::sort(CurFeats);
11534 if (CurFeats == NewFeats) {
11535 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11536 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11537 NewFD->setInvalidDecl();
11538 return true;
11540 break;
11542 case MultiVersionKind::TargetClones: {
11543 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
11544 Redeclaration = true;
11545 OldDecl = CurFD;
11546 NewFD->setIsMultiVersion();
11548 if (CurClones && NewClones &&
11549 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11550 !std::equal(CurClones->featuresStrs_begin(),
11551 CurClones->featuresStrs_end(),
11552 NewClones->featuresStrs_begin()))) {
11553 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11554 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11555 NewFD->setInvalidDecl();
11556 return true;
11559 return false;
11561 case MultiVersionKind::CPUSpecific:
11562 case MultiVersionKind::CPUDispatch: {
11563 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11564 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11565 // Handle CPUDispatch/CPUSpecific versions.
11566 // Only 1 CPUDispatch function is allowed, this will make it go through
11567 // the redeclaration errors.
11568 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11569 CurFD->hasAttr<CPUDispatchAttr>()) {
11570 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11571 std::equal(
11572 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11573 NewCPUDisp->cpus_begin(),
11574 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11575 return Cur->getName() == New->getName();
11576 })) {
11577 NewFD->setIsMultiVersion();
11578 Redeclaration = true;
11579 OldDecl = ND;
11580 return false;
11583 // If the declarations don't match, this is an error condition.
11584 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11585 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11586 NewFD->setInvalidDecl();
11587 return true;
11589 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11590 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11591 std::equal(
11592 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11593 NewCPUSpec->cpus_begin(),
11594 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11595 return Cur->getName() == New->getName();
11596 })) {
11597 NewFD->setIsMultiVersion();
11598 Redeclaration = true;
11599 OldDecl = ND;
11600 return false;
11603 // Only 1 version of CPUSpecific is allowed for each CPU.
11604 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11605 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11606 if (CurII == NewII) {
11607 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11608 << NewII;
11609 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11610 NewFD->setInvalidDecl();
11611 return true;
11616 break;
11621 // Else, this is simply a non-redecl case. Checking the 'value' is only
11622 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11623 // handled in the attribute adding step.
11624 if ((NewMVKind == MultiVersionKind::TargetVersion ||
11625 NewMVKind == MultiVersionKind::Target) &&
11626 CheckMultiVersionValue(S, NewFD)) {
11627 NewFD->setInvalidDecl();
11628 return true;
11631 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11632 !OldFD->isMultiVersion(), NewMVKind)) {
11633 NewFD->setInvalidDecl();
11634 return true;
11637 // Permit forward declarations in the case where these two are compatible.
11638 if (!OldFD->isMultiVersion()) {
11639 OldFD->setIsMultiVersion();
11640 NewFD->setIsMultiVersion();
11641 Redeclaration = true;
11642 OldDecl = OldFD;
11643 return false;
11646 NewFD->setIsMultiVersion();
11647 Redeclaration = false;
11648 OldDecl = nullptr;
11649 Previous.clear();
11650 return false;
11653 /// Check the validity of a mulitversion function declaration.
11654 /// Also sets the multiversion'ness' of the function itself.
11656 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11658 /// Returns true if there was an error, false otherwise.
11659 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11660 bool &Redeclaration, NamedDecl *&OldDecl,
11661 LookupResult &Previous) {
11662 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11663 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11664 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11665 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11666 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11667 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11669 // Main isn't allowed to become a multiversion function, however it IS
11670 // permitted to have 'main' be marked with the 'target' optimization hint,
11671 // for 'target_version' only default is allowed.
11672 if (NewFD->isMain()) {
11673 if (MVKind != MultiVersionKind::None &&
11674 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11675 !(MVKind == MultiVersionKind::TargetVersion &&
11676 NewTVA->isDefaultVersion())) {
11677 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11678 NewFD->setInvalidDecl();
11679 return true;
11681 return false;
11684 // Target attribute on AArch64 is not used for multiversioning
11685 if (NewTA && S.getASTContext().getTargetInfo().getTriple().isAArch64())
11686 return false;
11688 if (!OldDecl || !OldDecl->getAsFunction() ||
11689 OldDecl->getDeclContext()->getRedeclContext() !=
11690 NewFD->getDeclContext()->getRedeclContext()) {
11691 // If there's no previous declaration, AND this isn't attempting to cause
11692 // multiversioning, this isn't an error condition.
11693 if (MVKind == MultiVersionKind::None)
11694 return false;
11695 return CheckMultiVersionFirstFunction(S, NewFD);
11698 FunctionDecl *OldFD = OldDecl->getAsFunction();
11700 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) {
11701 // No target_version attributes mean default
11702 if (!NewTVA) {
11703 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11704 if (OldTVA) {
11705 NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11706 S.Context, "default", NewFD->getSourceRange()));
11707 NewFD->setIsMultiVersion();
11708 OldFD->setIsMultiVersion();
11709 OldDecl = OldFD;
11710 Redeclaration = true;
11711 return true;
11714 return false;
11717 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11718 // for target_clones and target_version.
11719 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11720 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
11721 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
11722 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11723 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11724 NewFD->setInvalidDecl();
11725 return true;
11728 if (!OldFD->isMultiVersion()) {
11729 switch (MVKind) {
11730 case MultiVersionKind::Target:
11731 case MultiVersionKind::TargetVersion:
11732 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration,
11733 OldDecl, Previous);
11734 case MultiVersionKind::TargetClones:
11735 if (OldFD->isUsed(false)) {
11736 NewFD->setInvalidDecl();
11737 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11739 OldFD->setIsMultiVersion();
11740 break;
11742 case MultiVersionKind::CPUDispatch:
11743 case MultiVersionKind::CPUSpecific:
11744 case MultiVersionKind::None:
11745 break;
11749 // At this point, we have a multiversion function decl (in OldFD) AND an
11750 // appropriate attribute in the current function decl. Resolve that these are
11751 // still compatible with previous declarations.
11752 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewCPUDisp,
11753 NewCPUSpec, NewClones, Redeclaration,
11754 OldDecl, Previous);
11757 /// Perform semantic checking of a new function declaration.
11759 /// Performs semantic analysis of the new function declaration
11760 /// NewFD. This routine performs all semantic checking that does not
11761 /// require the actual declarator involved in the declaration, and is
11762 /// used both for the declaration of functions as they are parsed
11763 /// (called via ActOnDeclarator) and for the declaration of functions
11764 /// that have been instantiated via C++ template instantiation (called
11765 /// via InstantiateDecl).
11767 /// \param IsMemberSpecialization whether this new function declaration is
11768 /// a member specialization (that replaces any definition provided by the
11769 /// previous declaration).
11771 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11773 /// \returns true if the function declaration is a redeclaration.
11774 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11775 LookupResult &Previous,
11776 bool IsMemberSpecialization,
11777 bool DeclIsDefn) {
11778 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11779 "Variably modified return types are not handled here");
11781 // Determine whether the type of this function should be merged with
11782 // a previous visible declaration. This never happens for functions in C++,
11783 // and always happens in C if the previous declaration was visible.
11784 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11785 !Previous.isShadowed();
11787 bool Redeclaration = false;
11788 NamedDecl *OldDecl = nullptr;
11789 bool MayNeedOverloadableChecks = false;
11791 // Merge or overload the declaration with an existing declaration of
11792 // the same name, if appropriate.
11793 if (!Previous.empty()) {
11794 // Determine whether NewFD is an overload of PrevDecl or
11795 // a declaration that requires merging. If it's an overload,
11796 // there's no more work to do here; we'll just add the new
11797 // function to the scope.
11798 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11799 NamedDecl *Candidate = Previous.getRepresentativeDecl();
11800 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11801 Redeclaration = true;
11802 OldDecl = Candidate;
11804 } else {
11805 MayNeedOverloadableChecks = true;
11806 switch (CheckOverload(S, NewFD, Previous, OldDecl,
11807 /*NewIsUsingDecl*/ false)) {
11808 case Ovl_Match:
11809 Redeclaration = true;
11810 break;
11812 case Ovl_NonFunction:
11813 Redeclaration = true;
11814 break;
11816 case Ovl_Overload:
11817 Redeclaration = false;
11818 break;
11823 // Check for a previous extern "C" declaration with this name.
11824 if (!Redeclaration &&
11825 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11826 if (!Previous.empty()) {
11827 // This is an extern "C" declaration with the same name as a previous
11828 // declaration, and thus redeclares that entity...
11829 Redeclaration = true;
11830 OldDecl = Previous.getFoundDecl();
11831 MergeTypeWithPrevious = false;
11833 // ... except in the presence of __attribute__((overloadable)).
11834 if (OldDecl->hasAttr<OverloadableAttr>() ||
11835 NewFD->hasAttr<OverloadableAttr>()) {
11836 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11837 MayNeedOverloadableChecks = true;
11838 Redeclaration = false;
11839 OldDecl = nullptr;
11845 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11846 return Redeclaration;
11848 // PPC MMA non-pointer types are not allowed as function return types.
11849 if (Context.getTargetInfo().getTriple().isPPC64() &&
11850 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11851 NewFD->setInvalidDecl();
11854 // C++11 [dcl.constexpr]p8:
11855 // A constexpr specifier for a non-static member function that is not
11856 // a constructor declares that member function to be const.
11858 // This needs to be delayed until we know whether this is an out-of-line
11859 // definition of a static member function.
11861 // This rule is not present in C++1y, so we produce a backwards
11862 // compatibility warning whenever it happens in C++11.
11863 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11864 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11865 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11866 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11867 CXXMethodDecl *OldMD = nullptr;
11868 if (OldDecl)
11869 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11870 if (!OldMD || !OldMD->isStatic()) {
11871 const FunctionProtoType *FPT =
11872 MD->getType()->castAs<FunctionProtoType>();
11873 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11874 EPI.TypeQuals.addConst();
11875 MD->setType(Context.getFunctionType(FPT->getReturnType(),
11876 FPT->getParamTypes(), EPI));
11878 // Warn that we did this, if we're not performing template instantiation.
11879 // In that case, we'll have warned already when the template was defined.
11880 if (!inTemplateInstantiation()) {
11881 SourceLocation AddConstLoc;
11882 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11883 .IgnoreParens().getAs<FunctionTypeLoc>())
11884 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11886 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11887 << FixItHint::CreateInsertion(AddConstLoc, " const");
11892 if (Redeclaration) {
11893 // NewFD and OldDecl represent declarations that need to be
11894 // merged.
11895 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11896 DeclIsDefn)) {
11897 NewFD->setInvalidDecl();
11898 return Redeclaration;
11901 Previous.clear();
11902 Previous.addDecl(OldDecl);
11904 if (FunctionTemplateDecl *OldTemplateDecl =
11905 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11906 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11907 FunctionTemplateDecl *NewTemplateDecl
11908 = NewFD->getDescribedFunctionTemplate();
11909 assert(NewTemplateDecl && "Template/non-template mismatch");
11911 // The call to MergeFunctionDecl above may have created some state in
11912 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11913 // can add it as a redeclaration.
11914 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11916 NewFD->setPreviousDeclaration(OldFD);
11917 if (NewFD->isCXXClassMember()) {
11918 NewFD->setAccess(OldTemplateDecl->getAccess());
11919 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11922 // If this is an explicit specialization of a member that is a function
11923 // template, mark it as a member specialization.
11924 if (IsMemberSpecialization &&
11925 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11926 NewTemplateDecl->setMemberSpecialization();
11927 assert(OldTemplateDecl->isMemberSpecialization());
11928 // Explicit specializations of a member template do not inherit deleted
11929 // status from the parent member template that they are specializing.
11930 if (OldFD->isDeleted()) {
11931 // FIXME: This assert will not hold in the presence of modules.
11932 assert(OldFD->getCanonicalDecl() == OldFD);
11933 // FIXME: We need an update record for this AST mutation.
11934 OldFD->setDeletedAsWritten(false);
11938 } else {
11939 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11940 auto *OldFD = cast<FunctionDecl>(OldDecl);
11941 // This needs to happen first so that 'inline' propagates.
11942 NewFD->setPreviousDeclaration(OldFD);
11943 if (NewFD->isCXXClassMember())
11944 NewFD->setAccess(OldFD->getAccess());
11947 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11948 !NewFD->getAttr<OverloadableAttr>()) {
11949 assert((Previous.empty() ||
11950 llvm::any_of(Previous,
11951 [](const NamedDecl *ND) {
11952 return ND->hasAttr<OverloadableAttr>();
11953 })) &&
11954 "Non-redecls shouldn't happen without overloadable present");
11956 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11957 const auto *FD = dyn_cast<FunctionDecl>(ND);
11958 return FD && !FD->hasAttr<OverloadableAttr>();
11961 if (OtherUnmarkedIter != Previous.end()) {
11962 Diag(NewFD->getLocation(),
11963 diag::err_attribute_overloadable_multiple_unmarked_overloads);
11964 Diag((*OtherUnmarkedIter)->getLocation(),
11965 diag::note_attribute_overloadable_prev_overload)
11966 << false;
11968 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11972 if (LangOpts.OpenMP)
11973 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11975 // Semantic checking for this function declaration (in isolation).
11977 if (getLangOpts().CPlusPlus) {
11978 // C++-specific checks.
11979 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11980 CheckConstructor(Constructor);
11981 } else if (CXXDestructorDecl *Destructor =
11982 dyn_cast<CXXDestructorDecl>(NewFD)) {
11983 // We check here for invalid destructor names.
11984 // If we have a friend destructor declaration that is dependent, we can't
11985 // diagnose right away because cases like this are still valid:
11986 // template <class T> struct A { friend T::X::~Y(); };
11987 // struct B { struct Y { ~Y(); }; using X = Y; };
11988 // template struct A<B>;
11989 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
11990 !Destructor->getThisType()->isDependentType()) {
11991 CXXRecordDecl *Record = Destructor->getParent();
11992 QualType ClassType = Context.getTypeDeclType(Record);
11994 DeclarationName Name = Context.DeclarationNames.getCXXDestructorName(
11995 Context.getCanonicalType(ClassType));
11996 if (NewFD->getDeclName() != Name) {
11997 Diag(NewFD->getLocation(), diag::err_destructor_name);
11998 NewFD->setInvalidDecl();
11999 return Redeclaration;
12002 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12003 if (auto *TD = Guide->getDescribedFunctionTemplate())
12004 CheckDeductionGuideTemplate(TD);
12006 // A deduction guide is not on the list of entities that can be
12007 // explicitly specialized.
12008 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12009 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12010 << /*explicit specialization*/ 1;
12013 // Find any virtual functions that this function overrides.
12014 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12015 if (!Method->isFunctionTemplateSpecialization() &&
12016 !Method->getDescribedFunctionTemplate() &&
12017 Method->isCanonicalDecl()) {
12018 AddOverriddenMethods(Method->getParent(), Method);
12020 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12021 // C++2a [class.virtual]p6
12022 // A virtual method shall not have a requires-clause.
12023 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
12024 diag::err_constrained_virtual_method);
12026 if (Method->isStatic())
12027 checkThisInStaticMemberFunctionType(Method);
12030 // C++20: dcl.decl.general p4:
12031 // The optional requires-clause ([temp.pre]) in an init-declarator or
12032 // member-declarator shall be present only if the declarator declares a
12033 // templated function ([dcl.fct]).
12034 if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
12035 // [temp.pre]/8:
12036 // An entity is templated if it is
12037 // - a template,
12038 // - an entity defined ([basic.def]) or created ([class.temporary]) in a
12039 // templated entity,
12040 // - a member of a templated entity,
12041 // - an enumerator for an enumeration that is a templated entity, or
12042 // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
12043 // appearing in the declaration of a templated entity. [Note 6: A local
12044 // class, a local or block variable, or a friend function defined in a
12045 // templated entity is a templated entity. — end note]
12047 // A templated function is a function template or a function that is
12048 // templated. A templated class is a class template or a class that is
12049 // templated. A templated variable is a variable template or a variable
12050 // that is templated.
12052 if (!NewFD->getDescribedFunctionTemplate() && // -a template
12053 // defined... in a templated entity
12054 !(DeclIsDefn && NewFD->isTemplated()) &&
12055 // a member of a templated entity
12056 !(isa<CXXMethodDecl>(NewFD) && NewFD->isTemplated()) &&
12057 // Don't complain about instantiations, they've already had these
12058 // rules + others enforced.
12059 !NewFD->isTemplateInstantiation()) {
12060 Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
12064 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12065 ActOnConversionDeclarator(Conversion);
12067 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12068 if (NewFD->isOverloadedOperator() &&
12069 CheckOverloadedOperatorDeclaration(NewFD)) {
12070 NewFD->setInvalidDecl();
12071 return Redeclaration;
12074 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12075 if (NewFD->getLiteralIdentifier() &&
12076 CheckLiteralOperatorDeclaration(NewFD)) {
12077 NewFD->setInvalidDecl();
12078 return Redeclaration;
12081 // In C++, check default arguments now that we have merged decls. Unless
12082 // the lexical context is the class, because in this case this is done
12083 // during delayed parsing anyway.
12084 if (!CurContext->isRecord())
12085 CheckCXXDefaultArguments(NewFD);
12087 // If this function is declared as being extern "C", then check to see if
12088 // the function returns a UDT (class, struct, or union type) that is not C
12089 // compatible, and if it does, warn the user.
12090 // But, issue any diagnostic on the first declaration only.
12091 if (Previous.empty() && NewFD->isExternC()) {
12092 QualType R = NewFD->getReturnType();
12093 if (R->isIncompleteType() && !R->isVoidType())
12094 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12095 << NewFD << R;
12096 else if (!R.isPODType(Context) && !R->isVoidType() &&
12097 !R->isObjCObjectPointerType())
12098 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12101 // C++1z [dcl.fct]p6:
12102 // [...] whether the function has a non-throwing exception-specification
12103 // [is] part of the function type
12105 // This results in an ABI break between C++14 and C++17 for functions whose
12106 // declared type includes an exception-specification in a parameter or
12107 // return type. (Exception specifications on the function itself are OK in
12108 // most cases, and exception specifications are not permitted in most other
12109 // contexts where they could make it into a mangling.)
12110 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12111 auto HasNoexcept = [&](QualType T) -> bool {
12112 // Strip off declarator chunks that could be between us and a function
12113 // type. We don't need to look far, exception specifications are very
12114 // restricted prior to C++17.
12115 if (auto *RT = T->getAs<ReferenceType>())
12116 T = RT->getPointeeType();
12117 else if (T->isAnyPointerType())
12118 T = T->getPointeeType();
12119 else if (auto *MPT = T->getAs<MemberPointerType>())
12120 T = MPT->getPointeeType();
12121 if (auto *FPT = T->getAs<FunctionProtoType>())
12122 if (FPT->isNothrow())
12123 return true;
12124 return false;
12127 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12128 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12129 for (QualType T : FPT->param_types())
12130 AnyNoexcept |= HasNoexcept(T);
12131 if (AnyNoexcept)
12132 Diag(NewFD->getLocation(),
12133 diag::warn_cxx17_compat_exception_spec_in_signature)
12134 << NewFD;
12137 if (!Redeclaration && LangOpts.CUDA)
12138 checkCUDATargetOverload(NewFD, Previous);
12141 // Check if the function definition uses any AArch64 SME features without
12142 // having the '+sme' feature enabled.
12143 if (DeclIsDefn) {
12144 bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>();
12145 bool UsesZA = NewFD->hasAttr<ArmNewZAAttr>();
12146 if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) {
12147 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12148 UsesSM |=
12149 EPI.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;
12150 UsesZA |= EPI.AArch64SMEAttributes & FunctionType::SME_PStateZASharedMask;
12153 if (UsesSM || UsesZA) {
12154 llvm::StringMap<bool> FeatureMap;
12155 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12156 if (!FeatureMap.contains("sme")) {
12157 if (UsesSM)
12158 Diag(NewFD->getLocation(),
12159 diag::err_sme_definition_using_sm_in_non_sme_target);
12160 else
12161 Diag(NewFD->getLocation(),
12162 diag::err_sme_definition_using_za_in_non_sme_target);
12167 return Redeclaration;
12170 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
12171 // C++11 [basic.start.main]p3:
12172 // A program that [...] declares main to be inline, static or
12173 // constexpr is ill-formed.
12174 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12175 // appear in a declaration of main.
12176 // static main is not an error under C99, but we should warn about it.
12177 // We accept _Noreturn main as an extension.
12178 if (FD->getStorageClass() == SC_Static)
12179 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
12180 ? diag::err_static_main : diag::warn_static_main)
12181 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12182 if (FD->isInlineSpecified())
12183 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12184 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
12185 if (DS.isNoreturnSpecified()) {
12186 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12187 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12188 Diag(NoreturnLoc, diag::ext_noreturn_main);
12189 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12190 << FixItHint::CreateRemoval(NoreturnRange);
12192 if (FD->isConstexpr()) {
12193 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12194 << FD->isConsteval()
12195 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
12196 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12199 if (getLangOpts().OpenCL) {
12200 Diag(FD->getLocation(), diag::err_opencl_no_main)
12201 << FD->hasAttr<OpenCLKernelAttr>();
12202 FD->setInvalidDecl();
12203 return;
12206 // Functions named main in hlsl are default entries, but don't have specific
12207 // signatures they are required to conform to.
12208 if (getLangOpts().HLSL)
12209 return;
12211 QualType T = FD->getType();
12212 assert(T->isFunctionType() && "function decl is not of function type");
12213 const FunctionType* FT = T->castAs<FunctionType>();
12215 // Set default calling convention for main()
12216 if (FT->getCallConv() != CC_C) {
12217 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12218 FD->setType(QualType(FT, 0));
12219 T = Context.getCanonicalType(FD->getType());
12222 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12223 // In C with GNU extensions we allow main() to have non-integer return
12224 // type, but we should warn about the extension, and we disable the
12225 // implicit-return-zero rule.
12227 // GCC in C mode accepts qualified 'int'.
12228 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12229 FD->setHasImplicitReturnZero(true);
12230 else {
12231 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12232 SourceRange RTRange = FD->getReturnTypeSourceRange();
12233 if (RTRange.isValid())
12234 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12235 << FixItHint::CreateReplacement(RTRange, "int");
12237 } else {
12238 // In C and C++, main magically returns 0 if you fall off the end;
12239 // set the flag which tells us that.
12240 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12242 // All the standards say that main() should return 'int'.
12243 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12244 FD->setHasImplicitReturnZero(true);
12245 else {
12246 // Otherwise, this is just a flat-out error.
12247 SourceRange RTRange = FD->getReturnTypeSourceRange();
12248 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12249 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12250 : FixItHint());
12251 FD->setInvalidDecl(true);
12255 // Treat protoless main() as nullary.
12256 if (isa<FunctionNoProtoType>(FT)) return;
12258 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12259 unsigned nparams = FTP->getNumParams();
12260 assert(FD->getNumParams() == nparams);
12262 bool HasExtraParameters = (nparams > 3);
12264 if (FTP->isVariadic()) {
12265 Diag(FD->getLocation(), diag::ext_variadic_main);
12266 // FIXME: if we had information about the location of the ellipsis, we
12267 // could add a FixIt hint to remove it as a parameter.
12270 // Darwin passes an undocumented fourth argument of type char**. If
12271 // other platforms start sprouting these, the logic below will start
12272 // getting shifty.
12273 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12274 HasExtraParameters = false;
12276 if (HasExtraParameters) {
12277 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12278 FD->setInvalidDecl(true);
12279 nparams = 3;
12282 // FIXME: a lot of the following diagnostics would be improved
12283 // if we had some location information about types.
12285 QualType CharPP =
12286 Context.getPointerType(Context.getPointerType(Context.CharTy));
12287 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12289 for (unsigned i = 0; i < nparams; ++i) {
12290 QualType AT = FTP->getParamType(i);
12292 bool mismatch = true;
12294 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12295 mismatch = false;
12296 else if (Expected[i] == CharPP) {
12297 // As an extension, the following forms are okay:
12298 // char const **
12299 // char const * const *
12300 // char * const *
12302 QualifierCollector qs;
12303 const PointerType* PT;
12304 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12305 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12306 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12307 Context.CharTy)) {
12308 qs.removeConst();
12309 mismatch = !qs.empty();
12313 if (mismatch) {
12314 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12315 // TODO: suggest replacing given type with expected type
12316 FD->setInvalidDecl(true);
12320 if (nparams == 1 && !FD->isInvalidDecl()) {
12321 Diag(FD->getLocation(), diag::warn_main_one_arg);
12324 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12325 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12326 FD->setInvalidDecl();
12330 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12332 // Default calling convention for main and wmain is __cdecl
12333 if (FD->getName() == "main" || FD->getName() == "wmain")
12334 return false;
12336 // Default calling convention for MinGW is __cdecl
12337 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12338 if (T.isWindowsGNUEnvironment())
12339 return false;
12341 // Default calling convention for WinMain, wWinMain and DllMain
12342 // is __stdcall on 32 bit Windows
12343 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12344 return true;
12346 return false;
12349 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12350 QualType T = FD->getType();
12351 assert(T->isFunctionType() && "function decl is not of function type");
12352 const FunctionType *FT = T->castAs<FunctionType>();
12354 // Set an implicit return of 'zero' if the function can return some integral,
12355 // enumeration, pointer or nullptr type.
12356 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12357 FT->getReturnType()->isAnyPointerType() ||
12358 FT->getReturnType()->isNullPtrType())
12359 // DllMain is exempt because a return value of zero means it failed.
12360 if (FD->getName() != "DllMain")
12361 FD->setHasImplicitReturnZero(true);
12363 // Explicity specified calling conventions are applied to MSVC entry points
12364 if (!hasExplicitCallingConv(T)) {
12365 if (isDefaultStdCall(FD, *this)) {
12366 if (FT->getCallConv() != CC_X86StdCall) {
12367 FT = Context.adjustFunctionType(
12368 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
12369 FD->setType(QualType(FT, 0));
12371 } else if (FT->getCallConv() != CC_C) {
12372 FT = Context.adjustFunctionType(FT,
12373 FT->getExtInfo().withCallingConv(CC_C));
12374 FD->setType(QualType(FT, 0));
12378 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12379 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12380 FD->setInvalidDecl();
12384 void Sema::CheckHLSLEntryPoint(FunctionDecl *FD) {
12385 auto &TargetInfo = getASTContext().getTargetInfo();
12386 auto const Triple = TargetInfo.getTriple();
12387 switch (Triple.getEnvironment()) {
12388 default:
12389 // FIXME: check all shader profiles.
12390 break;
12391 case llvm::Triple::EnvironmentType::Compute:
12392 if (!FD->hasAttr<HLSLNumThreadsAttr>()) {
12393 Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads)
12394 << Triple.getEnvironmentName();
12395 FD->setInvalidDecl();
12397 break;
12400 for (const auto *Param : FD->parameters()) {
12401 if (!Param->hasAttr<HLSLAnnotationAttr>()) {
12402 // FIXME: Handle struct parameters where annotations are on struct fields.
12403 // See: https://github.com/llvm/llvm-project/issues/57875
12404 Diag(FD->getLocation(), diag::err_hlsl_missing_semantic_annotation);
12405 Diag(Param->getLocation(), diag::note_previous_decl) << Param;
12406 FD->setInvalidDecl();
12409 // FIXME: Verify return type semantic annotation.
12412 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
12413 // FIXME: Need strict checking. In C89, we need to check for
12414 // any assignment, increment, decrement, function-calls, or
12415 // commas outside of a sizeof. In C99, it's the same list,
12416 // except that the aforementioned are allowed in unevaluated
12417 // expressions. Everything else falls under the
12418 // "may accept other forms of constant expressions" exception.
12420 // Regular C++ code will not end up here (exceptions: language extensions,
12421 // OpenCL C++ etc), so the constant expression rules there don't matter.
12422 if (Init->isValueDependent()) {
12423 assert(Init->containsErrors() &&
12424 "Dependent code should only occur in error-recovery path.");
12425 return true;
12427 const Expr *Culprit;
12428 if (Init->isConstantInitializer(Context, false, &Culprit))
12429 return false;
12430 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
12431 << Culprit->getSourceRange();
12432 return true;
12435 namespace {
12436 // Visits an initialization expression to see if OrigDecl is evaluated in
12437 // its own initialization and throws a warning if it does.
12438 class SelfReferenceChecker
12439 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12440 Sema &S;
12441 Decl *OrigDecl;
12442 bool isRecordType;
12443 bool isPODType;
12444 bool isReferenceType;
12446 bool isInitList;
12447 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12449 public:
12450 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12452 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12453 S(S), OrigDecl(OrigDecl) {
12454 isPODType = false;
12455 isRecordType = false;
12456 isReferenceType = false;
12457 isInitList = false;
12458 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12459 isPODType = VD->getType().isPODType(S.Context);
12460 isRecordType = VD->getType()->isRecordType();
12461 isReferenceType = VD->getType()->isReferenceType();
12465 // For most expressions, just call the visitor. For initializer lists,
12466 // track the index of the field being initialized since fields are
12467 // initialized in order allowing use of previously initialized fields.
12468 void CheckExpr(Expr *E) {
12469 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12470 if (!InitList) {
12471 Visit(E);
12472 return;
12475 // Track and increment the index here.
12476 isInitList = true;
12477 InitFieldIndex.push_back(0);
12478 for (auto *Child : InitList->children()) {
12479 CheckExpr(cast<Expr>(Child));
12480 ++InitFieldIndex.back();
12482 InitFieldIndex.pop_back();
12485 // Returns true if MemberExpr is checked and no further checking is needed.
12486 // Returns false if additional checking is required.
12487 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12488 llvm::SmallVector<FieldDecl*, 4> Fields;
12489 Expr *Base = E;
12490 bool ReferenceField = false;
12492 // Get the field members used.
12493 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12494 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12495 if (!FD)
12496 return false;
12497 Fields.push_back(FD);
12498 if (FD->getType()->isReferenceType())
12499 ReferenceField = true;
12500 Base = ME->getBase()->IgnoreParenImpCasts();
12503 // Keep checking only if the base Decl is the same.
12504 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12505 if (!DRE || DRE->getDecl() != OrigDecl)
12506 return false;
12508 // A reference field can be bound to an unininitialized field.
12509 if (CheckReference && !ReferenceField)
12510 return true;
12512 // Convert FieldDecls to their index number.
12513 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12514 for (const FieldDecl *I : llvm::reverse(Fields))
12515 UsedFieldIndex.push_back(I->getFieldIndex());
12517 // See if a warning is needed by checking the first difference in index
12518 // numbers. If field being used has index less than the field being
12519 // initialized, then the use is safe.
12520 for (auto UsedIter = UsedFieldIndex.begin(),
12521 UsedEnd = UsedFieldIndex.end(),
12522 OrigIter = InitFieldIndex.begin(),
12523 OrigEnd = InitFieldIndex.end();
12524 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12525 if (*UsedIter < *OrigIter)
12526 return true;
12527 if (*UsedIter > *OrigIter)
12528 break;
12531 // TODO: Add a different warning which will print the field names.
12532 HandleDeclRefExpr(DRE);
12533 return true;
12536 // For most expressions, the cast is directly above the DeclRefExpr.
12537 // For conditional operators, the cast can be outside the conditional
12538 // operator if both expressions are DeclRefExpr's.
12539 void HandleValue(Expr *E) {
12540 E = E->IgnoreParens();
12541 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12542 HandleDeclRefExpr(DRE);
12543 return;
12546 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12547 Visit(CO->getCond());
12548 HandleValue(CO->getTrueExpr());
12549 HandleValue(CO->getFalseExpr());
12550 return;
12553 if (BinaryConditionalOperator *BCO =
12554 dyn_cast<BinaryConditionalOperator>(E)) {
12555 Visit(BCO->getCond());
12556 HandleValue(BCO->getFalseExpr());
12557 return;
12560 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12561 HandleValue(OVE->getSourceExpr());
12562 return;
12565 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12566 if (BO->getOpcode() == BO_Comma) {
12567 Visit(BO->getLHS());
12568 HandleValue(BO->getRHS());
12569 return;
12573 if (isa<MemberExpr>(E)) {
12574 if (isInitList) {
12575 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12576 false /*CheckReference*/))
12577 return;
12580 Expr *Base = E->IgnoreParenImpCasts();
12581 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12582 // Check for static member variables and don't warn on them.
12583 if (!isa<FieldDecl>(ME->getMemberDecl()))
12584 return;
12585 Base = ME->getBase()->IgnoreParenImpCasts();
12587 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12588 HandleDeclRefExpr(DRE);
12589 return;
12592 Visit(E);
12595 // Reference types not handled in HandleValue are handled here since all
12596 // uses of references are bad, not just r-value uses.
12597 void VisitDeclRefExpr(DeclRefExpr *E) {
12598 if (isReferenceType)
12599 HandleDeclRefExpr(E);
12602 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12603 if (E->getCastKind() == CK_LValueToRValue) {
12604 HandleValue(E->getSubExpr());
12605 return;
12608 Inherited::VisitImplicitCastExpr(E);
12611 void VisitMemberExpr(MemberExpr *E) {
12612 if (isInitList) {
12613 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12614 return;
12617 // Don't warn on arrays since they can be treated as pointers.
12618 if (E->getType()->canDecayToPointerType()) return;
12620 // Warn when a non-static method call is followed by non-static member
12621 // field accesses, which is followed by a DeclRefExpr.
12622 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12623 bool Warn = (MD && !MD->isStatic());
12624 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12625 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12626 if (!isa<FieldDecl>(ME->getMemberDecl()))
12627 Warn = false;
12628 Base = ME->getBase()->IgnoreParenImpCasts();
12631 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12632 if (Warn)
12633 HandleDeclRefExpr(DRE);
12634 return;
12637 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12638 // Visit that expression.
12639 Visit(Base);
12642 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12643 Expr *Callee = E->getCallee();
12645 if (isa<UnresolvedLookupExpr>(Callee))
12646 return Inherited::VisitCXXOperatorCallExpr(E);
12648 Visit(Callee);
12649 for (auto Arg: E->arguments())
12650 HandleValue(Arg->IgnoreParenImpCasts());
12653 void VisitUnaryOperator(UnaryOperator *E) {
12654 // For POD record types, addresses of its own members are well-defined.
12655 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12656 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12657 if (!isPODType)
12658 HandleValue(E->getSubExpr());
12659 return;
12662 if (E->isIncrementDecrementOp()) {
12663 HandleValue(E->getSubExpr());
12664 return;
12667 Inherited::VisitUnaryOperator(E);
12670 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12672 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12673 if (E->getConstructor()->isCopyConstructor()) {
12674 Expr *ArgExpr = E->getArg(0);
12675 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12676 if (ILE->getNumInits() == 1)
12677 ArgExpr = ILE->getInit(0);
12678 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12679 if (ICE->getCastKind() == CK_NoOp)
12680 ArgExpr = ICE->getSubExpr();
12681 HandleValue(ArgExpr);
12682 return;
12684 Inherited::VisitCXXConstructExpr(E);
12687 void VisitCallExpr(CallExpr *E) {
12688 // Treat std::move as a use.
12689 if (E->isCallToStdMove()) {
12690 HandleValue(E->getArg(0));
12691 return;
12694 Inherited::VisitCallExpr(E);
12697 void VisitBinaryOperator(BinaryOperator *E) {
12698 if (E->isCompoundAssignmentOp()) {
12699 HandleValue(E->getLHS());
12700 Visit(E->getRHS());
12701 return;
12704 Inherited::VisitBinaryOperator(E);
12707 // A custom visitor for BinaryConditionalOperator is needed because the
12708 // regular visitor would check the condition and true expression separately
12709 // but both point to the same place giving duplicate diagnostics.
12710 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12711 Visit(E->getCond());
12712 Visit(E->getFalseExpr());
12715 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12716 Decl* ReferenceDecl = DRE->getDecl();
12717 if (OrigDecl != ReferenceDecl) return;
12718 unsigned diag;
12719 if (isReferenceType) {
12720 diag = diag::warn_uninit_self_reference_in_reference_init;
12721 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12722 diag = diag::warn_static_self_reference_in_init;
12723 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12724 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12725 DRE->getDecl()->getType()->isRecordType()) {
12726 diag = diag::warn_uninit_self_reference_in_init;
12727 } else {
12728 // Local variables will be handled by the CFG analysis.
12729 return;
12732 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12733 S.PDiag(diag)
12734 << DRE->getDecl() << OrigDecl->getLocation()
12735 << DRE->getSourceRange());
12739 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12740 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12741 bool DirectInit) {
12742 // Parameters arguments are occassionially constructed with itself,
12743 // for instance, in recursive functions. Skip them.
12744 if (isa<ParmVarDecl>(OrigDecl))
12745 return;
12747 E = E->IgnoreParens();
12749 // Skip checking T a = a where T is not a record or reference type.
12750 // Doing so is a way to silence uninitialized warnings.
12751 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12752 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12753 if (ICE->getCastKind() == CK_LValueToRValue)
12754 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12755 if (DRE->getDecl() == OrigDecl)
12756 return;
12758 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12760 } // end anonymous namespace
12762 namespace {
12763 // Simple wrapper to add the name of a variable or (if no variable is
12764 // available) a DeclarationName into a diagnostic.
12765 struct VarDeclOrName {
12766 VarDecl *VDecl;
12767 DeclarationName Name;
12769 friend const Sema::SemaDiagnosticBuilder &
12770 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12771 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12774 } // end anonymous namespace
12776 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12777 DeclarationName Name, QualType Type,
12778 TypeSourceInfo *TSI,
12779 SourceRange Range, bool DirectInit,
12780 Expr *Init) {
12781 bool IsInitCapture = !VDecl;
12782 assert((!VDecl || !VDecl->isInitCapture()) &&
12783 "init captures are expected to be deduced prior to initialization");
12785 VarDeclOrName VN{VDecl, Name};
12787 DeducedType *Deduced = Type->getContainedDeducedType();
12788 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12790 // C++11 [dcl.spec.auto]p3
12791 if (!Init) {
12792 assert(VDecl && "no init for init capture deduction?");
12794 // Except for class argument deduction, and then for an initializing
12795 // declaration only, i.e. no static at class scope or extern.
12796 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12797 VDecl->hasExternalStorage() ||
12798 VDecl->isStaticDataMember()) {
12799 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12800 << VDecl->getDeclName() << Type;
12801 return QualType();
12805 ArrayRef<Expr*> DeduceInits;
12806 if (Init)
12807 DeduceInits = Init;
12809 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
12810 if (DirectInit && PL)
12811 DeduceInits = PL->exprs();
12813 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12814 assert(VDecl && "non-auto type for init capture deduction?");
12815 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12816 InitializationKind Kind = InitializationKind::CreateForInit(
12817 VDecl->getLocation(), DirectInit, Init);
12818 // FIXME: Initialization should not be taking a mutable list of inits.
12819 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12820 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12821 InitsCopy, PL);
12824 if (DirectInit) {
12825 if (auto *IL = dyn_cast<InitListExpr>(Init))
12826 DeduceInits = IL->inits();
12829 // Deduction only works if we have exactly one source expression.
12830 if (DeduceInits.empty()) {
12831 // It isn't possible to write this directly, but it is possible to
12832 // end up in this situation with "auto x(some_pack...);"
12833 Diag(Init->getBeginLoc(), IsInitCapture
12834 ? diag::err_init_capture_no_expression
12835 : diag::err_auto_var_init_no_expression)
12836 << VN << Type << Range;
12837 return QualType();
12840 if (DeduceInits.size() > 1) {
12841 Diag(DeduceInits[1]->getBeginLoc(),
12842 IsInitCapture ? diag::err_init_capture_multiple_expressions
12843 : diag::err_auto_var_init_multiple_expressions)
12844 << VN << Type << Range;
12845 return QualType();
12848 Expr *DeduceInit = DeduceInits[0];
12849 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12850 Diag(Init->getBeginLoc(), IsInitCapture
12851 ? diag::err_init_capture_paren_braces
12852 : diag::err_auto_var_init_paren_braces)
12853 << isa<InitListExpr>(Init) << VN << Type << Range;
12854 return QualType();
12857 // Expressions default to 'id' when we're in a debugger.
12858 bool DefaultedAnyToId = false;
12859 if (getLangOpts().DebuggerCastResultToId &&
12860 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12861 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12862 if (Result.isInvalid()) {
12863 return QualType();
12865 Init = Result.get();
12866 DefaultedAnyToId = true;
12869 // C++ [dcl.decomp]p1:
12870 // If the assignment-expression [...] has array type A and no ref-qualifier
12871 // is present, e has type cv A
12872 if (VDecl && isa<DecompositionDecl>(VDecl) &&
12873 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12874 DeduceInit->getType()->isConstantArrayType())
12875 return Context.getQualifiedType(DeduceInit->getType(),
12876 Type.getQualifiers());
12878 QualType DeducedType;
12879 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
12880 TemplateDeductionResult Result =
12881 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
12882 if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed) {
12883 if (!IsInitCapture)
12884 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12885 else if (isa<InitListExpr>(Init))
12886 Diag(Range.getBegin(),
12887 diag::err_init_capture_deduction_failure_from_init_list)
12888 << VN
12889 << (DeduceInit->getType().isNull() ? TSI->getType()
12890 : DeduceInit->getType())
12891 << DeduceInit->getSourceRange();
12892 else
12893 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12894 << VN << TSI->getType()
12895 << (DeduceInit->getType().isNull() ? TSI->getType()
12896 : DeduceInit->getType())
12897 << DeduceInit->getSourceRange();
12900 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12901 // 'id' instead of a specific object type prevents most of our usual
12902 // checks.
12903 // We only want to warn outside of template instantiations, though:
12904 // inside a template, the 'id' could have come from a parameter.
12905 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12906 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12907 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12908 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12911 return DeducedType;
12914 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12915 Expr *Init) {
12916 assert(!Init || !Init->containsErrors());
12917 QualType DeducedType = deduceVarTypeFromInitializer(
12918 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12919 VDecl->getSourceRange(), DirectInit, Init);
12920 if (DeducedType.isNull()) {
12921 VDecl->setInvalidDecl();
12922 return true;
12925 VDecl->setType(DeducedType);
12926 assert(VDecl->isLinkageValid());
12928 // In ARC, infer lifetime.
12929 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12930 VDecl->setInvalidDecl();
12932 if (getLangOpts().OpenCL)
12933 deduceOpenCLAddressSpace(VDecl);
12935 // If this is a redeclaration, check that the type we just deduced matches
12936 // the previously declared type.
12937 if (VarDecl *Old = VDecl->getPreviousDecl()) {
12938 // We never need to merge the type, because we cannot form an incomplete
12939 // array of auto, nor deduce such a type.
12940 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12943 // Check the deduced type is valid for a variable declaration.
12944 CheckVariableDeclarationType(VDecl);
12945 return VDecl->isInvalidDecl();
12948 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12949 SourceLocation Loc) {
12950 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12951 Init = EWC->getSubExpr();
12953 if (auto *CE = dyn_cast<ConstantExpr>(Init))
12954 Init = CE->getSubExpr();
12956 QualType InitType = Init->getType();
12957 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12958 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12959 "shouldn't be called if type doesn't have a non-trivial C struct");
12960 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12961 for (auto *I : ILE->inits()) {
12962 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12963 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12964 continue;
12965 SourceLocation SL = I->getExprLoc();
12966 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12968 return;
12971 if (isa<ImplicitValueInitExpr>(Init)) {
12972 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12973 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12974 NTCUK_Init);
12975 } else {
12976 // Assume all other explicit initializers involving copying some existing
12977 // object.
12978 // TODO: ignore any explicit initializers where we can guarantee
12979 // copy-elision.
12980 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12981 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12985 namespace {
12987 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12988 // Ignore unavailable fields. A field can be marked as unavailable explicitly
12989 // in the source code or implicitly by the compiler if it is in a union
12990 // defined in a system header and has non-trivial ObjC ownership
12991 // qualifications. We don't want those fields to participate in determining
12992 // whether the containing union is non-trivial.
12993 return FD->hasAttr<UnavailableAttr>();
12996 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12997 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12998 void> {
12999 using Super =
13000 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13001 void>;
13003 DiagNonTrivalCUnionDefaultInitializeVisitor(
13004 QualType OrigTy, SourceLocation OrigLoc,
13005 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13006 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13008 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13009 const FieldDecl *FD, bool InNonTrivialUnion) {
13010 if (const auto *AT = S.Context.getAsArrayType(QT))
13011 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13012 InNonTrivialUnion);
13013 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13016 void visitARCStrong(QualType QT, const FieldDecl *FD,
13017 bool InNonTrivialUnion) {
13018 if (InNonTrivialUnion)
13019 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13020 << 1 << 0 << QT << FD->getName();
13023 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13024 if (InNonTrivialUnion)
13025 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13026 << 1 << 0 << QT << FD->getName();
13029 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13030 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13031 if (RD->isUnion()) {
13032 if (OrigLoc.isValid()) {
13033 bool IsUnion = false;
13034 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13035 IsUnion = OrigRD->isUnion();
13036 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13037 << 0 << OrigTy << IsUnion << UseContext;
13038 // Reset OrigLoc so that this diagnostic is emitted only once.
13039 OrigLoc = SourceLocation();
13041 InNonTrivialUnion = true;
13044 if (InNonTrivialUnion)
13045 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13046 << 0 << 0 << QT.getUnqualifiedType() << "";
13048 for (const FieldDecl *FD : RD->fields())
13049 if (!shouldIgnoreForRecordTriviality(FD))
13050 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13053 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13055 // The non-trivial C union type or the struct/union type that contains a
13056 // non-trivial C union.
13057 QualType OrigTy;
13058 SourceLocation OrigLoc;
13059 Sema::NonTrivialCUnionContext UseContext;
13060 Sema &S;
13063 struct DiagNonTrivalCUnionDestructedTypeVisitor
13064 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13065 using Super =
13066 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13068 DiagNonTrivalCUnionDestructedTypeVisitor(
13069 QualType OrigTy, SourceLocation OrigLoc,
13070 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13071 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13073 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13074 const FieldDecl *FD, bool InNonTrivialUnion) {
13075 if (const auto *AT = S.Context.getAsArrayType(QT))
13076 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13077 InNonTrivialUnion);
13078 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13081 void visitARCStrong(QualType QT, const FieldDecl *FD,
13082 bool InNonTrivialUnion) {
13083 if (InNonTrivialUnion)
13084 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13085 << 1 << 1 << QT << FD->getName();
13088 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13089 if (InNonTrivialUnion)
13090 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13091 << 1 << 1 << QT << FD->getName();
13094 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13095 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13096 if (RD->isUnion()) {
13097 if (OrigLoc.isValid()) {
13098 bool IsUnion = false;
13099 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13100 IsUnion = OrigRD->isUnion();
13101 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13102 << 1 << OrigTy << IsUnion << UseContext;
13103 // Reset OrigLoc so that this diagnostic is emitted only once.
13104 OrigLoc = SourceLocation();
13106 InNonTrivialUnion = true;
13109 if (InNonTrivialUnion)
13110 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13111 << 0 << 1 << QT.getUnqualifiedType() << "";
13113 for (const FieldDecl *FD : RD->fields())
13114 if (!shouldIgnoreForRecordTriviality(FD))
13115 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13118 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13119 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13120 bool InNonTrivialUnion) {}
13122 // The non-trivial C union type or the struct/union type that contains a
13123 // non-trivial C union.
13124 QualType OrigTy;
13125 SourceLocation OrigLoc;
13126 Sema::NonTrivialCUnionContext UseContext;
13127 Sema &S;
13130 struct DiagNonTrivalCUnionCopyVisitor
13131 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13132 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13134 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13135 Sema::NonTrivialCUnionContext UseContext,
13136 Sema &S)
13137 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13139 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13140 const FieldDecl *FD, bool InNonTrivialUnion) {
13141 if (const auto *AT = S.Context.getAsArrayType(QT))
13142 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13143 InNonTrivialUnion);
13144 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13147 void visitARCStrong(QualType QT, const FieldDecl *FD,
13148 bool InNonTrivialUnion) {
13149 if (InNonTrivialUnion)
13150 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13151 << 1 << 2 << QT << FD->getName();
13154 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13155 if (InNonTrivialUnion)
13156 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13157 << 1 << 2 << QT << FD->getName();
13160 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13161 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13162 if (RD->isUnion()) {
13163 if (OrigLoc.isValid()) {
13164 bool IsUnion = false;
13165 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13166 IsUnion = OrigRD->isUnion();
13167 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13168 << 2 << OrigTy << IsUnion << UseContext;
13169 // Reset OrigLoc so that this diagnostic is emitted only once.
13170 OrigLoc = SourceLocation();
13172 InNonTrivialUnion = true;
13175 if (InNonTrivialUnion)
13176 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13177 << 0 << 2 << QT.getUnqualifiedType() << "";
13179 for (const FieldDecl *FD : RD->fields())
13180 if (!shouldIgnoreForRecordTriviality(FD))
13181 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13184 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13185 const FieldDecl *FD, bool InNonTrivialUnion) {}
13186 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13187 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13188 bool InNonTrivialUnion) {}
13190 // The non-trivial C union type or the struct/union type that contains a
13191 // non-trivial C union.
13192 QualType OrigTy;
13193 SourceLocation OrigLoc;
13194 Sema::NonTrivialCUnionContext UseContext;
13195 Sema &S;
13198 } // namespace
13200 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13201 NonTrivialCUnionContext UseContext,
13202 unsigned NonTrivialKind) {
13203 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13204 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13205 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13206 "shouldn't be called if type doesn't have a non-trivial C union");
13208 if ((NonTrivialKind & NTCUK_Init) &&
13209 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13210 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13211 .visit(QT, nullptr, false);
13212 if ((NonTrivialKind & NTCUK_Destruct) &&
13213 QT.hasNonTrivialToPrimitiveDestructCUnion())
13214 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13215 .visit(QT, nullptr, false);
13216 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13217 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13218 .visit(QT, nullptr, false);
13221 /// AddInitializerToDecl - Adds the initializer Init to the
13222 /// declaration dcl. If DirectInit is true, this is C++ direct
13223 /// initialization rather than copy initialization.
13224 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13225 // If there is no declaration, there was an error parsing it. Just ignore
13226 // the initializer.
13227 if (!RealDecl || RealDecl->isInvalidDecl()) {
13228 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13229 return;
13232 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13233 // Pure-specifiers are handled in ActOnPureSpecifier.
13234 Diag(Method->getLocation(), diag::err_member_function_initialization)
13235 << Method->getDeclName() << Init->getSourceRange();
13236 Method->setInvalidDecl();
13237 return;
13240 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13241 if (!VDecl) {
13242 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13243 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13244 RealDecl->setInvalidDecl();
13245 return;
13248 // WebAssembly tables can't be used to initialise a variable.
13249 if (Init && !Init->getType().isNull() &&
13250 Init->getType()->isWebAssemblyTableType()) {
13251 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13252 VDecl->setInvalidDecl();
13253 return;
13256 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13257 if (VDecl->getType()->isUndeducedType()) {
13258 // Attempt typo correction early so that the type of the init expression can
13259 // be deduced based on the chosen correction if the original init contains a
13260 // TypoExpr.
13261 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
13262 if (!Res.isUsable()) {
13263 // There are unresolved typos in Init, just drop them.
13264 // FIXME: improve the recovery strategy to preserve the Init.
13265 RealDecl->setInvalidDecl();
13266 return;
13268 if (Res.get()->containsErrors()) {
13269 // Invalidate the decl as we don't know the type for recovery-expr yet.
13270 RealDecl->setInvalidDecl();
13271 VDecl->setInit(Res.get());
13272 return;
13274 Init = Res.get();
13276 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
13277 return;
13280 // dllimport cannot be used on variable definitions.
13281 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13282 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13283 VDecl->setInvalidDecl();
13284 return;
13287 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13288 // the identifier has external or internal linkage, the declaration shall
13289 // have no initializer for the identifier.
13290 // C++14 [dcl.init]p5 is the same restriction for C++.
13291 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13292 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13293 VDecl->setInvalidDecl();
13294 return;
13297 if (!VDecl->getType()->isDependentType()) {
13298 // A definition must end up with a complete type, which means it must be
13299 // complete with the restriction that an array type might be completed by
13300 // the initializer; note that later code assumes this restriction.
13301 QualType BaseDeclType = VDecl->getType();
13302 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13303 BaseDeclType = Array->getElementType();
13304 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13305 diag::err_typecheck_decl_incomplete_type)) {
13306 RealDecl->setInvalidDecl();
13307 return;
13310 // The variable can not have an abstract class type.
13311 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13312 diag::err_abstract_type_in_decl,
13313 AbstractVariableType))
13314 VDecl->setInvalidDecl();
13317 // C++ [module.import/6] external definitions are not permitted in header
13318 // units.
13319 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13320 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13321 VDecl->getFormalLinkage() == Linkage::ExternalLinkage &&
13322 !VDecl->isInline() && !VDecl->isTemplated() &&
13323 !isa<VarTemplateSpecializationDecl>(VDecl)) {
13324 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13325 VDecl->setInvalidDecl();
13328 // If adding the initializer will turn this declaration into a definition,
13329 // and we already have a definition for this variable, diagnose or otherwise
13330 // handle the situation.
13331 if (VarDecl *Def = VDecl->getDefinition())
13332 if (Def != VDecl &&
13333 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13334 !VDecl->isThisDeclarationADemotedDefinition() &&
13335 checkVarDeclRedefinition(Def, VDecl))
13336 return;
13338 if (getLangOpts().CPlusPlus) {
13339 // C++ [class.static.data]p4
13340 // If a static data member is of const integral or const
13341 // enumeration type, its declaration in the class definition can
13342 // specify a constant-initializer which shall be an integral
13343 // constant expression (5.19). In that case, the member can appear
13344 // in integral constant expressions. The member shall still be
13345 // defined in a namespace scope if it is used in the program and the
13346 // namespace scope definition shall not contain an initializer.
13348 // We already performed a redefinition check above, but for static
13349 // data members we also need to check whether there was an in-class
13350 // declaration with an initializer.
13351 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13352 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13353 << VDecl->getDeclName();
13354 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13355 diag::note_previous_initializer)
13356 << 0;
13357 return;
13360 if (VDecl->hasLocalStorage())
13361 setFunctionHasBranchProtectedScope();
13363 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
13364 VDecl->setInvalidDecl();
13365 return;
13369 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13370 // a kernel function cannot be initialized."
13371 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13372 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13373 VDecl->setInvalidDecl();
13374 return;
13377 // The LoaderUninitialized attribute acts as a definition (of undef).
13378 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13379 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13380 VDecl->setInvalidDecl();
13381 return;
13384 // Get the decls type and save a reference for later, since
13385 // CheckInitializerTypes may change it.
13386 QualType DclT = VDecl->getType(), SavT = DclT;
13388 // Expressions default to 'id' when we're in a debugger
13389 // and we are assigning it to a variable of Objective-C pointer type.
13390 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13391 Init->getType() == Context.UnknownAnyTy) {
13392 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
13393 if (Result.isInvalid()) {
13394 VDecl->setInvalidDecl();
13395 return;
13397 Init = Result.get();
13400 // Perform the initialization.
13401 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13402 bool IsParenListInit = false;
13403 if (!VDecl->isInvalidDecl()) {
13404 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
13405 InitializationKind Kind = InitializationKind::CreateForInit(
13406 VDecl->getLocation(), DirectInit, Init);
13408 MultiExprArg Args = Init;
13409 if (CXXDirectInit)
13410 Args = MultiExprArg(CXXDirectInit->getExprs(),
13411 CXXDirectInit->getNumExprs());
13413 // Try to correct any TypoExprs in the initialization arguments.
13414 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13415 ExprResult Res = CorrectDelayedTyposInExpr(
13416 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13417 [this, Entity, Kind](Expr *E) {
13418 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13419 return Init.Failed() ? ExprError() : E;
13421 if (Res.isInvalid()) {
13422 VDecl->setInvalidDecl();
13423 } else if (Res.get() != Args[Idx]) {
13424 Args[Idx] = Res.get();
13427 if (VDecl->isInvalidDecl())
13428 return;
13430 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13431 /*TopLevelOfInitList=*/false,
13432 /*TreatUnavailableAsInvalid=*/false);
13433 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13434 if (Result.isInvalid()) {
13435 // If the provided initializer fails to initialize the var decl,
13436 // we attach a recovery expr for better recovery.
13437 auto RecoveryExpr =
13438 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13439 if (RecoveryExpr.get())
13440 VDecl->setInit(RecoveryExpr.get());
13441 return;
13444 Init = Result.getAs<Expr>();
13445 IsParenListInit = !InitSeq.steps().empty() &&
13446 InitSeq.step_begin()->Kind ==
13447 InitializationSequence::SK_ParenthesizedListInit;
13450 // Check for self-references within variable initializers.
13451 // Variables declared within a function/method body (except for references)
13452 // are handled by a dataflow analysis.
13453 // This is undefined behavior in C++, but valid in C.
13454 if (getLangOpts().CPlusPlus)
13455 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13456 VDecl->getType()->isReferenceType())
13457 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13459 // If the type changed, it means we had an incomplete type that was
13460 // completed by the initializer. For example:
13461 // int ary[] = { 1, 3, 5 };
13462 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13463 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13464 VDecl->setType(DclT);
13466 if (!VDecl->isInvalidDecl()) {
13467 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13469 if (VDecl->hasAttr<BlocksAttr>())
13470 checkRetainCycles(VDecl, Init);
13472 // It is safe to assign a weak reference into a strong variable.
13473 // Although this code can still have problems:
13474 // id x = self.weakProp;
13475 // id y = self.weakProp;
13476 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13477 // paths through the function. This should be revisited if
13478 // -Wrepeated-use-of-weak is made flow-sensitive.
13479 if (FunctionScopeInfo *FSI = getCurFunction())
13480 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13481 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
13482 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13483 Init->getBeginLoc()))
13484 FSI->markSafeWeakUse(Init);
13487 // The initialization is usually a full-expression.
13489 // FIXME: If this is a braced initialization of an aggregate, it is not
13490 // an expression, and each individual field initializer is a separate
13491 // full-expression. For instance, in:
13493 // struct Temp { ~Temp(); };
13494 // struct S { S(Temp); };
13495 // struct T { S a, b; } t = { Temp(), Temp() }
13497 // we should destroy the first Temp before constructing the second.
13498 ExprResult Result =
13499 ActOnFinishFullExpr(Init, VDecl->getLocation(),
13500 /*DiscardedValue*/ false, VDecl->isConstexpr());
13501 if (Result.isInvalid()) {
13502 VDecl->setInvalidDecl();
13503 return;
13505 Init = Result.get();
13507 // Attach the initializer to the decl.
13508 VDecl->setInit(Init);
13510 if (VDecl->isLocalVarDecl()) {
13511 // Don't check the initializer if the declaration is malformed.
13512 if (VDecl->isInvalidDecl()) {
13513 // do nothing
13515 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13516 // This is true even in C++ for OpenCL.
13517 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13518 CheckForConstantInitializer(Init, DclT);
13520 // Otherwise, C++ does not restrict the initializer.
13521 } else if (getLangOpts().CPlusPlus) {
13522 // do nothing
13524 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13525 // static storage duration shall be constant expressions or string literals.
13526 } else if (VDecl->getStorageClass() == SC_Static) {
13527 CheckForConstantInitializer(Init, DclT);
13529 // C89 is stricter than C99 for aggregate initializers.
13530 // C89 6.5.7p3: All the expressions [...] in an initializer list
13531 // for an object that has aggregate or union type shall be
13532 // constant expressions.
13533 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13534 isa<InitListExpr>(Init)) {
13535 const Expr *Culprit;
13536 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
13537 Diag(Culprit->getExprLoc(),
13538 diag::ext_aggregate_init_not_constant)
13539 << Culprit->getSourceRange();
13543 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13544 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13545 if (VDecl->hasLocalStorage())
13546 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13547 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13548 VDecl->getLexicalDeclContext()->isRecord()) {
13549 // This is an in-class initialization for a static data member, e.g.,
13551 // struct S {
13552 // static const int value = 17;
13553 // };
13555 // C++ [class.mem]p4:
13556 // A member-declarator can contain a constant-initializer only
13557 // if it declares a static member (9.4) of const integral or
13558 // const enumeration type, see 9.4.2.
13560 // C++11 [class.static.data]p3:
13561 // If a non-volatile non-inline const static data member is of integral
13562 // or enumeration type, its declaration in the class definition can
13563 // specify a brace-or-equal-initializer in which every initializer-clause
13564 // that is an assignment-expression is a constant expression. A static
13565 // data member of literal type can be declared in the class definition
13566 // with the constexpr specifier; if so, its declaration shall specify a
13567 // brace-or-equal-initializer in which every initializer-clause that is
13568 // an assignment-expression is a constant expression.
13570 // Do nothing on dependent types.
13571 if (DclT->isDependentType()) {
13573 // Allow any 'static constexpr' members, whether or not they are of literal
13574 // type. We separately check that every constexpr variable is of literal
13575 // type.
13576 } else if (VDecl->isConstexpr()) {
13578 // Require constness.
13579 } else if (!DclT.isConstQualified()) {
13580 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13581 << Init->getSourceRange();
13582 VDecl->setInvalidDecl();
13584 // We allow integer constant expressions in all cases.
13585 } else if (DclT->isIntegralOrEnumerationType()) {
13586 // Check whether the expression is a constant expression.
13587 SourceLocation Loc;
13588 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
13589 // In C++11, a non-constexpr const static data member with an
13590 // in-class initializer cannot be volatile.
13591 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13592 else if (Init->isValueDependent())
13593 ; // Nothing to check.
13594 else if (Init->isIntegerConstantExpr(Context, &Loc))
13595 ; // Ok, it's an ICE!
13596 else if (Init->getType()->isScopedEnumeralType() &&
13597 Init->isCXX11ConstantExpr(Context))
13598 ; // Ok, it is a scoped-enum constant expression.
13599 else if (Init->isEvaluatable(Context)) {
13600 // If we can constant fold the initializer through heroics, accept it,
13601 // but report this as a use of an extension for -pedantic.
13602 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13603 << Init->getSourceRange();
13604 } else {
13605 // Otherwise, this is some crazy unknown case. Report the issue at the
13606 // location provided by the isIntegerConstantExpr failed check.
13607 Diag(Loc, diag::err_in_class_initializer_non_constant)
13608 << Init->getSourceRange();
13609 VDecl->setInvalidDecl();
13612 // We allow foldable floating-point constants as an extension.
13613 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13614 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13615 // it anyway and provide a fixit to add the 'constexpr'.
13616 if (getLangOpts().CPlusPlus11) {
13617 Diag(VDecl->getLocation(),
13618 diag::ext_in_class_initializer_float_type_cxx11)
13619 << DclT << Init->getSourceRange();
13620 Diag(VDecl->getBeginLoc(),
13621 diag::note_in_class_initializer_float_type_cxx11)
13622 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13623 } else {
13624 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13625 << DclT << Init->getSourceRange();
13627 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13628 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13629 << Init->getSourceRange();
13630 VDecl->setInvalidDecl();
13634 // Suggest adding 'constexpr' in C++11 for literal types.
13635 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13636 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13637 << DclT << Init->getSourceRange()
13638 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13639 VDecl->setConstexpr(true);
13641 } else {
13642 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13643 << DclT << Init->getSourceRange();
13644 VDecl->setInvalidDecl();
13646 } else if (VDecl->isFileVarDecl()) {
13647 // In C, extern is typically used to avoid tentative definitions when
13648 // declaring variables in headers, but adding an intializer makes it a
13649 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13650 // In C++, extern is often used to give implictly static const variables
13651 // external linkage, so don't warn in that case. If selectany is present,
13652 // this might be header code intended for C and C++ inclusion, so apply the
13653 // C++ rules.
13654 if (VDecl->getStorageClass() == SC_Extern &&
13655 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13656 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
13657 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13658 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
13659 Diag(VDecl->getLocation(), diag::warn_extern_init);
13661 // In Microsoft C++ mode, a const variable defined in namespace scope has
13662 // external linkage by default if the variable is declared with
13663 // __declspec(dllexport).
13664 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13665 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
13666 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13667 VDecl->setStorageClass(SC_Extern);
13669 // C99 6.7.8p4. All file scoped initializers need to be constant.
13670 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
13671 CheckForConstantInitializer(Init, DclT);
13674 QualType InitType = Init->getType();
13675 if (!InitType.isNull() &&
13676 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13677 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
13678 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
13680 // We will represent direct-initialization similarly to copy-initialization:
13681 // int x(1); -as-> int x = 1;
13682 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13684 // Clients that want to distinguish between the two forms, can check for
13685 // direct initializer using VarDecl::getInitStyle().
13686 // A major benefit is that clients that don't particularly care about which
13687 // exactly form was it (like the CodeGen) can handle both cases without
13688 // special case code.
13690 // C++ 8.5p11:
13691 // The form of initialization (using parentheses or '=') is generally
13692 // insignificant, but does matter when the entity being initialized has a
13693 // class type.
13694 if (CXXDirectInit) {
13695 assert(DirectInit && "Call-style initializer must be direct init.");
13696 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13697 : VarDecl::CallInit);
13698 } else if (DirectInit) {
13699 // This must be list-initialization. No other way is direct-initialization.
13700 VDecl->setInitStyle(VarDecl::ListInit);
13703 if (LangOpts.OpenMP &&
13704 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
13705 VDecl->isFileVarDecl())
13706 DeclsToCheckForDeferredDiags.insert(VDecl);
13707 CheckCompleteVariableDeclaration(VDecl);
13710 /// ActOnInitializerError - Given that there was an error parsing an
13711 /// initializer for the given declaration, try to at least re-establish
13712 /// invariants such as whether a variable's type is either dependent or
13713 /// complete.
13714 void Sema::ActOnInitializerError(Decl *D) {
13715 // Our main concern here is re-establishing invariants like "a
13716 // variable's type is either dependent or complete".
13717 if (!D || D->isInvalidDecl()) return;
13719 VarDecl *VD = dyn_cast<VarDecl>(D);
13720 if (!VD) return;
13722 // Bindings are not usable if we can't make sense of the initializer.
13723 if (auto *DD = dyn_cast<DecompositionDecl>(D))
13724 for (auto *BD : DD->bindings())
13725 BD->setInvalidDecl();
13727 // Auto types are meaningless if we can't make sense of the initializer.
13728 if (VD->getType()->isUndeducedType()) {
13729 D->setInvalidDecl();
13730 return;
13733 QualType Ty = VD->getType();
13734 if (Ty->isDependentType()) return;
13736 // Require a complete type.
13737 if (RequireCompleteType(VD->getLocation(),
13738 Context.getBaseElementType(Ty),
13739 diag::err_typecheck_decl_incomplete_type)) {
13740 VD->setInvalidDecl();
13741 return;
13744 // Require a non-abstract type.
13745 if (RequireNonAbstractType(VD->getLocation(), Ty,
13746 diag::err_abstract_type_in_decl,
13747 AbstractVariableType)) {
13748 VD->setInvalidDecl();
13749 return;
13752 // Don't bother complaining about constructors or destructors,
13753 // though.
13756 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13757 // If there is no declaration, there was an error parsing it. Just ignore it.
13758 if (!RealDecl)
13759 return;
13761 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13762 QualType Type = Var->getType();
13764 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13765 if (isa<DecompositionDecl>(RealDecl)) {
13766 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13767 Var->setInvalidDecl();
13768 return;
13771 if (Type->isUndeducedType() &&
13772 DeduceVariableDeclarationType(Var, false, nullptr))
13773 return;
13775 // C++11 [class.static.data]p3: A static data member can be declared with
13776 // the constexpr specifier; if so, its declaration shall specify
13777 // a brace-or-equal-initializer.
13778 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13779 // the definition of a variable [...] or the declaration of a static data
13780 // member.
13781 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13782 !Var->isThisDeclarationADemotedDefinition()) {
13783 if (Var->isStaticDataMember()) {
13784 // C++1z removes the relevant rule; the in-class declaration is always
13785 // a definition there.
13786 if (!getLangOpts().CPlusPlus17 &&
13787 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13788 Diag(Var->getLocation(),
13789 diag::err_constexpr_static_mem_var_requires_init)
13790 << Var;
13791 Var->setInvalidDecl();
13792 return;
13794 } else {
13795 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13796 Var->setInvalidDecl();
13797 return;
13801 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13802 // be initialized.
13803 if (!Var->isInvalidDecl() &&
13804 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13805 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13806 bool HasConstExprDefaultConstructor = false;
13807 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13808 for (auto *Ctor : RD->ctors()) {
13809 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13810 Ctor->getMethodQualifiers().getAddressSpace() ==
13811 LangAS::opencl_constant) {
13812 HasConstExprDefaultConstructor = true;
13816 if (!HasConstExprDefaultConstructor) {
13817 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13818 Var->setInvalidDecl();
13819 return;
13823 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13824 if (Var->getStorageClass() == SC_Extern) {
13825 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13826 << Var;
13827 Var->setInvalidDecl();
13828 return;
13830 if (RequireCompleteType(Var->getLocation(), Var->getType(),
13831 diag::err_typecheck_decl_incomplete_type)) {
13832 Var->setInvalidDecl();
13833 return;
13835 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13836 if (!RD->hasTrivialDefaultConstructor()) {
13837 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13838 Var->setInvalidDecl();
13839 return;
13842 // The declaration is unitialized, no need for further checks.
13843 return;
13846 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13847 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13848 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13849 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13850 NTCUC_DefaultInitializedObject, NTCUK_Init);
13853 switch (DefKind) {
13854 case VarDecl::Definition:
13855 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13856 break;
13858 // We have an out-of-line definition of a static data member
13859 // that has an in-class initializer, so we type-check this like
13860 // a declaration.
13862 [[fallthrough]];
13864 case VarDecl::DeclarationOnly:
13865 // It's only a declaration.
13867 // Block scope. C99 6.7p7: If an identifier for an object is
13868 // declared with no linkage (C99 6.2.2p6), the type for the
13869 // object shall be complete.
13870 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13871 !Var->hasLinkage() && !Var->isInvalidDecl() &&
13872 RequireCompleteType(Var->getLocation(), Type,
13873 diag::err_typecheck_decl_incomplete_type))
13874 Var->setInvalidDecl();
13876 // Make sure that the type is not abstract.
13877 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13878 RequireNonAbstractType(Var->getLocation(), Type,
13879 diag::err_abstract_type_in_decl,
13880 AbstractVariableType))
13881 Var->setInvalidDecl();
13882 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13883 Var->getStorageClass() == SC_PrivateExtern) {
13884 Diag(Var->getLocation(), diag::warn_private_extern);
13885 Diag(Var->getLocation(), diag::note_private_extern);
13888 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13889 !Var->isInvalidDecl())
13890 ExternalDeclarations.push_back(Var);
13892 return;
13894 case VarDecl::TentativeDefinition:
13895 // File scope. C99 6.9.2p2: A declaration of an identifier for an
13896 // object that has file scope without an initializer, and without a
13897 // storage-class specifier or with the storage-class specifier "static",
13898 // constitutes a tentative definition. Note: A tentative definition with
13899 // external linkage is valid (C99 6.2.2p5).
13900 if (!Var->isInvalidDecl()) {
13901 if (const IncompleteArrayType *ArrayT
13902 = Context.getAsIncompleteArrayType(Type)) {
13903 if (RequireCompleteSizedType(
13904 Var->getLocation(), ArrayT->getElementType(),
13905 diag::err_array_incomplete_or_sizeless_type))
13906 Var->setInvalidDecl();
13907 } else if (Var->getStorageClass() == SC_Static) {
13908 // C99 6.9.2p3: If the declaration of an identifier for an object is
13909 // a tentative definition and has internal linkage (C99 6.2.2p3), the
13910 // declared type shall not be an incomplete type.
13911 // NOTE: code such as the following
13912 // static struct s;
13913 // struct s { int a; };
13914 // is accepted by gcc. Hence here we issue a warning instead of
13915 // an error and we do not invalidate the static declaration.
13916 // NOTE: to avoid multiple warnings, only check the first declaration.
13917 if (Var->isFirstDecl())
13918 RequireCompleteType(Var->getLocation(), Type,
13919 diag::ext_typecheck_decl_incomplete_type);
13923 // Record the tentative definition; we're done.
13924 if (!Var->isInvalidDecl())
13925 TentativeDefinitions.push_back(Var);
13926 return;
13929 // Provide a specific diagnostic for uninitialized variable
13930 // definitions with incomplete array type.
13931 if (Type->isIncompleteArrayType()) {
13932 if (Var->isConstexpr())
13933 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
13934 << Var;
13935 else
13936 Diag(Var->getLocation(),
13937 diag::err_typecheck_incomplete_array_needs_initializer);
13938 Var->setInvalidDecl();
13939 return;
13942 // Provide a specific diagnostic for uninitialized variable
13943 // definitions with reference type.
13944 if (Type->isReferenceType()) {
13945 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13946 << Var << SourceRange(Var->getLocation(), Var->getLocation());
13947 return;
13950 // Do not attempt to type-check the default initializer for a
13951 // variable with dependent type.
13952 if (Type->isDependentType())
13953 return;
13955 if (Var->isInvalidDecl())
13956 return;
13958 if (!Var->hasAttr<AliasAttr>()) {
13959 if (RequireCompleteType(Var->getLocation(),
13960 Context.getBaseElementType(Type),
13961 diag::err_typecheck_decl_incomplete_type)) {
13962 Var->setInvalidDecl();
13963 return;
13965 } else {
13966 return;
13969 // The variable can not have an abstract class type.
13970 if (RequireNonAbstractType(Var->getLocation(), Type,
13971 diag::err_abstract_type_in_decl,
13972 AbstractVariableType)) {
13973 Var->setInvalidDecl();
13974 return;
13977 // Check for jumps past the implicit initializer. C++0x
13978 // clarifies that this applies to a "variable with automatic
13979 // storage duration", not a "local variable".
13980 // C++11 [stmt.dcl]p3
13981 // A program that jumps from a point where a variable with automatic
13982 // storage duration is not in scope to a point where it is in scope is
13983 // ill-formed unless the variable has scalar type, class type with a
13984 // trivial default constructor and a trivial destructor, a cv-qualified
13985 // version of one of these types, or an array of one of the preceding
13986 // types and is declared without an initializer.
13987 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13988 if (const RecordType *Record
13989 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13990 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13991 // Mark the function (if we're in one) for further checking even if the
13992 // looser rules of C++11 do not require such checks, so that we can
13993 // diagnose incompatibilities with C++98.
13994 if (!CXXRecord->isPOD())
13995 setFunctionHasBranchProtectedScope();
13998 // In OpenCL, we can't initialize objects in the __local address space,
13999 // even implicitly, so don't synthesize an implicit initializer.
14000 if (getLangOpts().OpenCL &&
14001 Var->getType().getAddressSpace() == LangAS::opencl_local)
14002 return;
14003 // C++03 [dcl.init]p9:
14004 // If no initializer is specified for an object, and the
14005 // object is of (possibly cv-qualified) non-POD class type (or
14006 // array thereof), the object shall be default-initialized; if
14007 // the object is of const-qualified type, the underlying class
14008 // type shall have a user-declared default
14009 // constructor. Otherwise, if no initializer is specified for
14010 // a non- static object, the object and its subobjects, if
14011 // any, have an indeterminate initial value); if the object
14012 // or any of its subobjects are of const-qualified type, the
14013 // program is ill-formed.
14014 // C++0x [dcl.init]p11:
14015 // If no initializer is specified for an object, the object is
14016 // default-initialized; [...].
14017 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14018 InitializationKind Kind
14019 = InitializationKind::CreateDefault(Var->getLocation());
14021 InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
14022 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
14024 if (Init.get()) {
14025 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14026 // This is important for template substitution.
14027 Var->setInitStyle(VarDecl::CallInit);
14028 } else if (Init.isInvalid()) {
14029 // If default-init fails, attach a recovery-expr initializer to track
14030 // that initialization was attempted and failed.
14031 auto RecoveryExpr =
14032 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14033 if (RecoveryExpr.get())
14034 Var->setInit(RecoveryExpr.get());
14037 CheckCompleteVariableDeclaration(Var);
14041 void Sema::ActOnCXXForRangeDecl(Decl *D) {
14042 // If there is no declaration, there was an error parsing it. Ignore it.
14043 if (!D)
14044 return;
14046 VarDecl *VD = dyn_cast<VarDecl>(D);
14047 if (!VD) {
14048 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14049 D->setInvalidDecl();
14050 return;
14053 VD->setCXXForRangeDecl(true);
14055 // for-range-declaration cannot be given a storage class specifier.
14056 int Error = -1;
14057 switch (VD->getStorageClass()) {
14058 case SC_None:
14059 break;
14060 case SC_Extern:
14061 Error = 0;
14062 break;
14063 case SC_Static:
14064 Error = 1;
14065 break;
14066 case SC_PrivateExtern:
14067 Error = 2;
14068 break;
14069 case SC_Auto:
14070 Error = 3;
14071 break;
14072 case SC_Register:
14073 Error = 4;
14074 break;
14077 // for-range-declaration cannot be given a storage class specifier con't.
14078 switch (VD->getTSCSpec()) {
14079 case TSCS_thread_local:
14080 Error = 6;
14081 break;
14082 case TSCS___thread:
14083 case TSCS__Thread_local:
14084 case TSCS_unspecified:
14085 break;
14088 if (Error != -1) {
14089 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14090 << VD << Error;
14091 D->setInvalidDecl();
14095 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
14096 IdentifierInfo *Ident,
14097 ParsedAttributes &Attrs) {
14098 // C++1y [stmt.iter]p1:
14099 // A range-based for statement of the form
14100 // for ( for-range-identifier : for-range-initializer ) statement
14101 // is equivalent to
14102 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14103 DeclSpec DS(Attrs.getPool().getFactory());
14105 const char *PrevSpec;
14106 unsigned DiagID;
14107 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14108 getPrintingPolicy());
14110 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14111 D.SetIdentifier(Ident, IdentLoc);
14112 D.takeAttributes(Attrs);
14114 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14115 IdentLoc);
14116 Decl *Var = ActOnDeclarator(S, D);
14117 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14118 FinalizeDeclaration(Var);
14119 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14120 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14121 : IdentLoc);
14124 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14125 if (var->isInvalidDecl()) return;
14127 MaybeAddCUDAConstantAttr(var);
14129 if (getLangOpts().OpenCL) {
14130 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14131 // initialiser
14132 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14133 !var->hasInit()) {
14134 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14135 << 1 /*Init*/;
14136 var->setInvalidDecl();
14137 return;
14141 // In Objective-C, don't allow jumps past the implicit initialization of a
14142 // local retaining variable.
14143 if (getLangOpts().ObjC &&
14144 var->hasLocalStorage()) {
14145 switch (var->getType().getObjCLifetime()) {
14146 case Qualifiers::OCL_None:
14147 case Qualifiers::OCL_ExplicitNone:
14148 case Qualifiers::OCL_Autoreleasing:
14149 break;
14151 case Qualifiers::OCL_Weak:
14152 case Qualifiers::OCL_Strong:
14153 setFunctionHasBranchProtectedScope();
14154 break;
14158 if (var->hasLocalStorage() &&
14159 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14160 setFunctionHasBranchProtectedScope();
14162 // Warn about externally-visible variables being defined without a
14163 // prior declaration. We only want to do this for global
14164 // declarations, but we also specifically need to avoid doing it for
14165 // class members because the linkage of an anonymous class can
14166 // change if it's later given a typedef name.
14167 if (var->isThisDeclarationADefinition() &&
14168 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14169 var->isExternallyVisible() && var->hasLinkage() &&
14170 !var->isInline() && !var->getDescribedVarTemplate() &&
14171 var->getStorageClass() != SC_Register &&
14172 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14173 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14174 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14175 var->getLocation())) {
14176 // Find a previous declaration that's not a definition.
14177 VarDecl *prev = var->getPreviousDecl();
14178 while (prev && prev->isThisDeclarationADefinition())
14179 prev = prev->getPreviousDecl();
14181 if (!prev) {
14182 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14183 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14184 << /* variable */ 0;
14188 // Cache the result of checking for constant initialization.
14189 std::optional<bool> CacheHasConstInit;
14190 const Expr *CacheCulprit = nullptr;
14191 auto checkConstInit = [&]() mutable {
14192 if (!CacheHasConstInit)
14193 CacheHasConstInit = var->getInit()->isConstantInitializer(
14194 Context, var->getType()->isReferenceType(), &CacheCulprit);
14195 return *CacheHasConstInit;
14198 if (var->getTLSKind() == VarDecl::TLS_Static) {
14199 if (var->getType().isDestructedType()) {
14200 // GNU C++98 edits for __thread, [basic.start.term]p3:
14201 // The type of an object with thread storage duration shall not
14202 // have a non-trivial destructor.
14203 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14204 if (getLangOpts().CPlusPlus11)
14205 Diag(var->getLocation(), diag::note_use_thread_local);
14206 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14207 if (!checkConstInit()) {
14208 // GNU C++98 edits for __thread, [basic.start.init]p4:
14209 // An object of thread storage duration shall not require dynamic
14210 // initialization.
14211 // FIXME: Need strict checking here.
14212 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14213 << CacheCulprit->getSourceRange();
14214 if (getLangOpts().CPlusPlus11)
14215 Diag(var->getLocation(), diag::note_use_thread_local);
14221 if (!var->getType()->isStructureType() && var->hasInit() &&
14222 isa<InitListExpr>(var->getInit())) {
14223 const auto *ILE = cast<InitListExpr>(var->getInit());
14224 unsigned NumInits = ILE->getNumInits();
14225 if (NumInits > 2)
14226 for (unsigned I = 0; I < NumInits; ++I) {
14227 const auto *Init = ILE->getInit(I);
14228 if (!Init)
14229 break;
14230 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14231 if (!SL)
14232 break;
14234 unsigned NumConcat = SL->getNumConcatenated();
14235 // Diagnose missing comma in string array initialization.
14236 // Do not warn when all the elements in the initializer are concatenated
14237 // together. Do not warn for macros too.
14238 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14239 bool OnlyOneMissingComma = true;
14240 for (unsigned J = I + 1; J < NumInits; ++J) {
14241 const auto *Init = ILE->getInit(J);
14242 if (!Init)
14243 break;
14244 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14245 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14246 OnlyOneMissingComma = false;
14247 break;
14251 if (OnlyOneMissingComma) {
14252 SmallVector<FixItHint, 1> Hints;
14253 for (unsigned i = 0; i < NumConcat - 1; ++i)
14254 Hints.push_back(FixItHint::CreateInsertion(
14255 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14257 Diag(SL->getStrTokenLoc(1),
14258 diag::warn_concatenated_literal_array_init)
14259 << Hints;
14260 Diag(SL->getBeginLoc(),
14261 diag::note_concatenated_string_literal_silence);
14263 // In any case, stop now.
14264 break;
14270 QualType type = var->getType();
14272 if (var->hasAttr<BlocksAttr>())
14273 getCurFunction()->addByrefBlockVar(var);
14275 Expr *Init = var->getInit();
14276 bool GlobalStorage = var->hasGlobalStorage();
14277 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14278 QualType baseType = Context.getBaseElementType(type);
14279 bool HasConstInit = true;
14281 // Check whether the initializer is sufficiently constant.
14282 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
14283 !Init->isValueDependent() &&
14284 (GlobalStorage || var->isConstexpr() ||
14285 var->mightBeUsableInConstantExpressions(Context))) {
14286 // If this variable might have a constant initializer or might be usable in
14287 // constant expressions, check whether or not it actually is now. We can't
14288 // do this lazily, because the result might depend on things that change
14289 // later, such as which constexpr functions happen to be defined.
14290 SmallVector<PartialDiagnosticAt, 8> Notes;
14291 if (!getLangOpts().CPlusPlus11) {
14292 // Prior to C++11, in contexts where a constant initializer is required,
14293 // the set of valid constant initializers is described by syntactic rules
14294 // in [expr.const]p2-6.
14295 // FIXME: Stricter checking for these rules would be useful for constinit /
14296 // -Wglobal-constructors.
14297 HasConstInit = checkConstInit();
14299 // Compute and cache the constant value, and remember that we have a
14300 // constant initializer.
14301 if (HasConstInit) {
14302 (void)var->checkForConstantInitialization(Notes);
14303 Notes.clear();
14304 } else if (CacheCulprit) {
14305 Notes.emplace_back(CacheCulprit->getExprLoc(),
14306 PDiag(diag::note_invalid_subexpr_in_const_expr));
14307 Notes.back().second << CacheCulprit->getSourceRange();
14309 } else {
14310 // Evaluate the initializer to see if it's a constant initializer.
14311 HasConstInit = var->checkForConstantInitialization(Notes);
14314 if (HasConstInit) {
14315 // FIXME: Consider replacing the initializer with a ConstantExpr.
14316 } else if (var->isConstexpr()) {
14317 SourceLocation DiagLoc = var->getLocation();
14318 // If the note doesn't add any useful information other than a source
14319 // location, fold it into the primary diagnostic.
14320 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14321 diag::note_invalid_subexpr_in_const_expr) {
14322 DiagLoc = Notes[0].first;
14323 Notes.clear();
14325 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14326 << var << Init->getSourceRange();
14327 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14328 Diag(Notes[I].first, Notes[I].second);
14329 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14330 auto *Attr = var->getAttr<ConstInitAttr>();
14331 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14332 << Init->getSourceRange();
14333 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14334 << Attr->getRange() << Attr->isConstinit();
14335 for (auto &it : Notes)
14336 Diag(it.first, it.second);
14337 } else if (IsGlobal &&
14338 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14339 var->getLocation())) {
14340 // Warn about globals which don't have a constant initializer. Don't
14341 // warn about globals with a non-trivial destructor because we already
14342 // warned about them.
14343 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14344 if (!(RD && !RD->hasTrivialDestructor())) {
14345 // checkConstInit() here permits trivial default initialization even in
14346 // C++11 onwards, where such an initializer is not a constant initializer
14347 // but nonetheless doesn't require a global constructor.
14348 if (!checkConstInit())
14349 Diag(var->getLocation(), diag::warn_global_constructor)
14350 << Init->getSourceRange();
14355 // Apply section attributes and pragmas to global variables.
14356 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14357 !inTemplateInstantiation()) {
14358 PragmaStack<StringLiteral *> *Stack = nullptr;
14359 int SectionFlags = ASTContext::PSF_Read;
14360 bool MSVCEnv =
14361 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14362 std::optional<QualType::NonConstantStorageReason> Reason;
14363 if (HasConstInit &&
14364 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14365 Stack = &ConstSegStack;
14366 } else {
14367 SectionFlags |= ASTContext::PSF_Write;
14368 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14370 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14371 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14372 SectionFlags |= ASTContext::PSF_Implicit;
14373 UnifySection(SA->getName(), SectionFlags, var);
14374 } else if (Stack->CurrentValue) {
14375 if (Stack != &ConstSegStack && MSVCEnv &&
14376 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14377 var->getType().isConstQualified()) {
14378 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14379 NonConstNonReferenceType) &&
14380 "This case should've already been handled elsewhere");
14381 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14382 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14383 ? QualType::NonConstantStorageReason::NonTrivialCtor
14384 : *Reason);
14386 SectionFlags |= ASTContext::PSF_Implicit;
14387 auto SectionName = Stack->CurrentValue->getString();
14388 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14389 Stack->CurrentPragmaLocation,
14390 SectionAttr::Declspec_allocate));
14391 if (UnifySection(SectionName, SectionFlags, var))
14392 var->dropAttr<SectionAttr>();
14395 // Apply the init_seg attribute if this has an initializer. If the
14396 // initializer turns out to not be dynamic, we'll end up ignoring this
14397 // attribute.
14398 if (CurInitSeg && var->getInit())
14399 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14400 CurInitSegLoc));
14403 // All the following checks are C++ only.
14404 if (!getLangOpts().CPlusPlus) {
14405 // If this variable must be emitted, add it as an initializer for the
14406 // current module.
14407 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14408 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14409 return;
14412 // Require the destructor.
14413 if (!type->isDependentType())
14414 if (const RecordType *recordType = baseType->getAs<RecordType>())
14415 FinalizeVarWithDestructor(var, recordType);
14417 // If this variable must be emitted, add it as an initializer for the current
14418 // module.
14419 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14420 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14422 // Build the bindings if this is a structured binding declaration.
14423 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14424 CheckCompleteDecompositionDeclaration(DD);
14427 /// Check if VD needs to be dllexport/dllimport due to being in a
14428 /// dllexport/import function.
14429 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
14430 assert(VD->isStaticLocal());
14432 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14434 // Find outermost function when VD is in lambda function.
14435 while (FD && !getDLLAttr(FD) &&
14436 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14437 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14438 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14441 if (!FD)
14442 return;
14444 // Static locals inherit dll attributes from their function.
14445 if (Attr *A = getDLLAttr(FD)) {
14446 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14447 NewAttr->setInherited(true);
14448 VD->addAttr(NewAttr);
14449 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14450 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14451 NewAttr->setInherited(true);
14452 VD->addAttr(NewAttr);
14454 // Export this function to enforce exporting this static variable even
14455 // if it is not used in this compilation unit.
14456 if (!FD->hasAttr<DLLExportAttr>())
14457 FD->addAttr(NewAttr);
14459 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14460 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14461 NewAttr->setInherited(true);
14462 VD->addAttr(NewAttr);
14466 void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
14467 assert(VD->getTLSKind());
14469 // Perform TLS alignment check here after attributes attached to the variable
14470 // which may affect the alignment have been processed. Only perform the check
14471 // if the target has a maximum TLS alignment (zero means no constraints).
14472 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14473 // Protect the check so that it's not performed on dependent types and
14474 // dependent alignments (we can't determine the alignment in that case).
14475 if (!VD->hasDependentAlignment()) {
14476 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14477 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14478 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14479 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
14480 << (unsigned)MaxAlignChars.getQuantity();
14486 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
14487 /// any semantic actions necessary after any initializer has been attached.
14488 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
14489 // Note that we are no longer parsing the initializer for this declaration.
14490 ParsingInitForAutoVars.erase(ThisDecl);
14492 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14493 if (!VD)
14494 return;
14496 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14497 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
14498 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14499 if (PragmaClangBSSSection.Valid)
14500 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14501 Context, PragmaClangBSSSection.SectionName,
14502 PragmaClangBSSSection.PragmaLocation));
14503 if (PragmaClangDataSection.Valid)
14504 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14505 Context, PragmaClangDataSection.SectionName,
14506 PragmaClangDataSection.PragmaLocation));
14507 if (PragmaClangRodataSection.Valid)
14508 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14509 Context, PragmaClangRodataSection.SectionName,
14510 PragmaClangRodataSection.PragmaLocation));
14511 if (PragmaClangRelroSection.Valid)
14512 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14513 Context, PragmaClangRelroSection.SectionName,
14514 PragmaClangRelroSection.PragmaLocation));
14517 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14518 for (auto *BD : DD->bindings()) {
14519 FinalizeDeclaration(BD);
14523 checkAttributesAfterMerging(*this, *VD);
14525 if (VD->isStaticLocal())
14526 CheckStaticLocalForDllExport(VD);
14528 if (VD->getTLSKind())
14529 CheckThreadLocalForLargeAlignment(VD);
14531 // Perform check for initializers of device-side global variables.
14532 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14533 // 7.5). We must also apply the same checks to all __shared__
14534 // variables whether they are local or not. CUDA also allows
14535 // constant initializers for __constant__ and __device__ variables.
14536 if (getLangOpts().CUDA)
14537 checkAllowedCUDAInitializer(VD);
14539 // Grab the dllimport or dllexport attribute off of the VarDecl.
14540 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14542 // Imported static data members cannot be defined out-of-line.
14543 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14544 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14545 VD->isThisDeclarationADefinition()) {
14546 // We allow definitions of dllimport class template static data members
14547 // with a warning.
14548 CXXRecordDecl *Context =
14549 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14550 bool IsClassTemplateMember =
14551 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14552 Context->getDescribedClassTemplate();
14554 Diag(VD->getLocation(),
14555 IsClassTemplateMember
14556 ? diag::warn_attribute_dllimport_static_field_definition
14557 : diag::err_attribute_dllimport_static_field_definition);
14558 Diag(IA->getLocation(), diag::note_attribute);
14559 if (!IsClassTemplateMember)
14560 VD->setInvalidDecl();
14564 // dllimport/dllexport variables cannot be thread local, their TLS index
14565 // isn't exported with the variable.
14566 if (DLLAttr && VD->getTLSKind()) {
14567 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14568 if (F && getDLLAttr(F)) {
14569 assert(VD->isStaticLocal());
14570 // But if this is a static local in a dlimport/dllexport function, the
14571 // function will never be inlined, which means the var would never be
14572 // imported, so having it marked import/export is safe.
14573 } else {
14574 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14575 << DLLAttr;
14576 VD->setInvalidDecl();
14580 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14581 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14582 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14583 << Attr;
14584 VD->dropAttr<UsedAttr>();
14587 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14588 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14589 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14590 << Attr;
14591 VD->dropAttr<RetainAttr>();
14595 const DeclContext *DC = VD->getDeclContext();
14596 // If there's a #pragma GCC visibility in scope, and this isn't a class
14597 // member, set the visibility of this variable.
14598 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
14599 AddPushedVisibilityAttribute(VD);
14601 // FIXME: Warn on unused var template partial specializations.
14602 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14603 MarkUnusedFileScopedDecl(VD);
14605 // Now we have parsed the initializer and can update the table of magic
14606 // tag values.
14607 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14608 !VD->getType()->isIntegralOrEnumerationType())
14609 return;
14611 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14612 const Expr *MagicValueExpr = VD->getInit();
14613 if (!MagicValueExpr) {
14614 continue;
14616 std::optional<llvm::APSInt> MagicValueInt;
14617 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14618 Diag(I->getRange().getBegin(),
14619 diag::err_type_tag_for_datatype_not_ice)
14620 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14621 continue;
14623 if (MagicValueInt->getActiveBits() > 64) {
14624 Diag(I->getRange().getBegin(),
14625 diag::err_type_tag_for_datatype_too_large)
14626 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14627 continue;
14629 uint64_t MagicValue = MagicValueInt->getZExtValue();
14630 RegisterTypeTagForDatatype(I->getArgumentKind(),
14631 MagicValue,
14632 I->getMatchingCType(),
14633 I->getLayoutCompatible(),
14634 I->getMustBeNull());
14638 static bool hasDeducedAuto(DeclaratorDecl *DD) {
14639 auto *VD = dyn_cast<VarDecl>(DD);
14640 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14643 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
14644 ArrayRef<Decl *> Group) {
14645 SmallVector<Decl*, 8> Decls;
14647 if (DS.isTypeSpecOwned())
14648 Decls.push_back(DS.getRepAsDecl());
14650 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14651 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14652 bool DiagnosedMultipleDecomps = false;
14653 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14654 bool DiagnosedNonDeducedAuto = false;
14656 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14657 if (Decl *D = Group[i]) {
14658 // Check if the Decl has been declared in '#pragma omp declare target'
14659 // directive and has static storage duration.
14660 if (auto *VD = dyn_cast<VarDecl>(D);
14661 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14662 VD->hasGlobalStorage())
14663 ActOnOpenMPDeclareTargetInitializer(D);
14664 // For declarators, there are some additional syntactic-ish checks we need
14665 // to perform.
14666 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14667 if (!FirstDeclaratorInGroup)
14668 FirstDeclaratorInGroup = DD;
14669 if (!FirstDecompDeclaratorInGroup)
14670 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14671 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14672 !hasDeducedAuto(DD))
14673 FirstNonDeducedAutoInGroup = DD;
14675 if (FirstDeclaratorInGroup != DD) {
14676 // A decomposition declaration cannot be combined with any other
14677 // declaration in the same group.
14678 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14679 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14680 diag::err_decomp_decl_not_alone)
14681 << FirstDeclaratorInGroup->getSourceRange()
14682 << DD->getSourceRange();
14683 DiagnosedMultipleDecomps = true;
14686 // A declarator that uses 'auto' in any way other than to declare a
14687 // variable with a deduced type cannot be combined with any other
14688 // declarator in the same group.
14689 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14690 Diag(FirstNonDeducedAutoInGroup->getLocation(),
14691 diag::err_auto_non_deduced_not_alone)
14692 << FirstNonDeducedAutoInGroup->getType()
14693 ->hasAutoForTrailingReturnType()
14694 << FirstDeclaratorInGroup->getSourceRange()
14695 << DD->getSourceRange();
14696 DiagnosedNonDeducedAuto = true;
14701 Decls.push_back(D);
14705 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
14706 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14707 handleTagNumbering(Tag, S);
14708 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14709 getLangOpts().CPlusPlus)
14710 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14714 return BuildDeclaratorGroup(Decls);
14717 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
14718 /// group, performing any necessary semantic checking.
14719 Sema::DeclGroupPtrTy
14720 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
14721 // C++14 [dcl.spec.auto]p7: (DR1347)
14722 // If the type that replaces the placeholder type is not the same in each
14723 // deduction, the program is ill-formed.
14724 if (Group.size() > 1) {
14725 QualType Deduced;
14726 VarDecl *DeducedDecl = nullptr;
14727 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14728 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14729 if (!D || D->isInvalidDecl())
14730 break;
14731 DeducedType *DT = D->getType()->getContainedDeducedType();
14732 if (!DT || DT->getDeducedType().isNull())
14733 continue;
14734 if (Deduced.isNull()) {
14735 Deduced = DT->getDeducedType();
14736 DeducedDecl = D;
14737 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14738 auto *AT = dyn_cast<AutoType>(DT);
14739 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14740 diag::err_auto_different_deductions)
14741 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14742 << DeducedDecl->getDeclName() << DT->getDeducedType()
14743 << D->getDeclName();
14744 if (DeducedDecl->hasInit())
14745 Dia << DeducedDecl->getInit()->getSourceRange();
14746 if (D->getInit())
14747 Dia << D->getInit()->getSourceRange();
14748 D->setInvalidDecl();
14749 break;
14754 ActOnDocumentableDecls(Group);
14756 return DeclGroupPtrTy::make(
14757 DeclGroupRef::Create(Context, Group.data(), Group.size()));
14760 void Sema::ActOnDocumentableDecl(Decl *D) {
14761 ActOnDocumentableDecls(D);
14764 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
14765 // Don't parse the comment if Doxygen diagnostics are ignored.
14766 if (Group.empty() || !Group[0])
14767 return;
14769 if (Diags.isIgnored(diag::warn_doc_param_not_found,
14770 Group[0]->getLocation()) &&
14771 Diags.isIgnored(diag::warn_unknown_comment_command_name,
14772 Group[0]->getLocation()))
14773 return;
14775 if (Group.size() >= 2) {
14776 // This is a decl group. Normally it will contain only declarations
14777 // produced from declarator list. But in case we have any definitions or
14778 // additional declaration references:
14779 // 'typedef struct S {} S;'
14780 // 'typedef struct S *S;'
14781 // 'struct S *pS;'
14782 // FinalizeDeclaratorGroup adds these as separate declarations.
14783 Decl *MaybeTagDecl = Group[0];
14784 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14785 Group = Group.slice(1);
14789 // FIMXE: We assume every Decl in the group is in the same file.
14790 // This is false when preprocessor constructs the group from decls in
14791 // different files (e. g. macros or #include).
14792 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14795 /// Common checks for a parameter-declaration that should apply to both function
14796 /// parameters and non-type template parameters.
14797 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14798 // Check that there are no default arguments inside the type of this
14799 // parameter.
14800 if (getLangOpts().CPlusPlus)
14801 CheckExtraCXXDefaultArguments(D);
14803 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14804 if (D.getCXXScopeSpec().isSet()) {
14805 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14806 << D.getCXXScopeSpec().getRange();
14809 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14810 // simple identifier except [...irrelevant cases...].
14811 switch (D.getName().getKind()) {
14812 case UnqualifiedIdKind::IK_Identifier:
14813 break;
14815 case UnqualifiedIdKind::IK_OperatorFunctionId:
14816 case UnqualifiedIdKind::IK_ConversionFunctionId:
14817 case UnqualifiedIdKind::IK_LiteralOperatorId:
14818 case UnqualifiedIdKind::IK_ConstructorName:
14819 case UnqualifiedIdKind::IK_DestructorName:
14820 case UnqualifiedIdKind::IK_ImplicitSelfParam:
14821 case UnqualifiedIdKind::IK_DeductionGuideName:
14822 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14823 << GetNameForDeclarator(D).getName();
14824 break;
14826 case UnqualifiedIdKind::IK_TemplateId:
14827 case UnqualifiedIdKind::IK_ConstructorTemplateId:
14828 // GetNameForDeclarator would not produce a useful name in this case.
14829 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14830 break;
14834 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14835 /// to introduce parameters into function prototype scope.
14836 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
14837 const DeclSpec &DS = D.getDeclSpec();
14839 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14841 // C++03 [dcl.stc]p2 also permits 'auto'.
14842 StorageClass SC = SC_None;
14843 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14844 SC = SC_Register;
14845 // In C++11, the 'register' storage class specifier is deprecated.
14846 // In C++17, it is not allowed, but we tolerate it as an extension.
14847 if (getLangOpts().CPlusPlus11) {
14848 Diag(DS.getStorageClassSpecLoc(),
14849 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14850 : diag::warn_deprecated_register)
14851 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14853 } else if (getLangOpts().CPlusPlus &&
14854 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14855 SC = SC_Auto;
14856 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14857 Diag(DS.getStorageClassSpecLoc(),
14858 diag::err_invalid_storage_class_in_func_decl);
14859 D.getMutableDeclSpec().ClearStorageClassSpecs();
14862 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14863 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14864 << DeclSpec::getSpecifierName(TSCS);
14865 if (DS.isInlineSpecified())
14866 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14867 << getLangOpts().CPlusPlus17;
14868 if (DS.hasConstexprSpecifier())
14869 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14870 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14872 DiagnoseFunctionSpecifiers(DS);
14874 CheckFunctionOrTemplateParamDeclarator(S, D);
14876 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14877 QualType parmDeclType = TInfo->getType();
14879 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14880 IdentifierInfo *II = D.getIdentifier();
14881 if (II) {
14882 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14883 ForVisibleRedeclaration);
14884 LookupName(R, S);
14885 if (!R.empty()) {
14886 NamedDecl *PrevDecl = *R.begin();
14887 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
14888 // Maybe we will complain about the shadowed template parameter.
14889 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14890 // Just pretend that we didn't see the previous declaration.
14891 PrevDecl = nullptr;
14893 if (PrevDecl && S->isDeclScope(PrevDecl)) {
14894 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14895 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14896 // Recover by removing the name
14897 II = nullptr;
14898 D.SetIdentifier(nullptr, D.getIdentifierLoc());
14899 D.setInvalidType(true);
14904 // Temporarily put parameter variables in the translation unit, not
14905 // the enclosing context. This prevents them from accidentally
14906 // looking like class members in C++.
14907 ParmVarDecl *New =
14908 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14909 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14911 if (D.isInvalidType())
14912 New->setInvalidDecl();
14914 assert(S->isFunctionPrototypeScope());
14915 assert(S->getFunctionPrototypeDepth() >= 1);
14916 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14917 S->getNextFunctionPrototypeIndex());
14919 // Add the parameter declaration into this scope.
14920 S->AddDecl(New);
14921 if (II)
14922 IdResolver.AddDecl(New);
14924 ProcessDeclAttributes(S, New, D);
14926 if (D.getDeclSpec().isModulePrivateSpecified())
14927 Diag(New->getLocation(), diag::err_module_private_local)
14928 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14929 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14931 if (New->hasAttr<BlocksAttr>()) {
14932 Diag(New->getLocation(), diag::err_block_on_nonlocal);
14935 if (getLangOpts().OpenCL)
14936 deduceOpenCLAddressSpace(New);
14938 return New;
14941 /// Synthesizes a variable for a parameter arising from a
14942 /// typedef.
14943 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14944 SourceLocation Loc,
14945 QualType T) {
14946 /* FIXME: setting StartLoc == Loc.
14947 Would it be worth to modify callers so as to provide proper source
14948 location for the unnamed parameters, embedding the parameter's type? */
14949 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14950 T, Context.getTrivialTypeSourceInfo(T, Loc),
14951 SC_None, nullptr);
14952 Param->setImplicit();
14953 return Param;
14956 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14957 // Don't diagnose unused-parameter errors in template instantiations; we
14958 // will already have done so in the template itself.
14959 if (inTemplateInstantiation())
14960 return;
14962 for (const ParmVarDecl *Parameter : Parameters) {
14963 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14964 !Parameter->hasAttr<UnusedAttr>() &&
14965 !Parameter->getIdentifier()->isPlaceholder()) {
14966 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14967 << Parameter->getDeclName();
14972 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14973 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14974 if (LangOpts.NumLargeByValueCopy == 0) // No check.
14975 return;
14977 // Warn if the return value is pass-by-value and larger than the specified
14978 // threshold.
14979 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14980 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14981 if (Size > LangOpts.NumLargeByValueCopy)
14982 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14985 // Warn if any parameter is pass-by-value and larger than the specified
14986 // threshold.
14987 for (const ParmVarDecl *Parameter : Parameters) {
14988 QualType T = Parameter->getType();
14989 if (T->isDependentType() || !T.isPODType(Context))
14990 continue;
14991 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14992 if (Size > LangOpts.NumLargeByValueCopy)
14993 Diag(Parameter->getLocation(), diag::warn_parameter_size)
14994 << Parameter << Size;
14998 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14999 SourceLocation NameLoc, IdentifierInfo *Name,
15000 QualType T, TypeSourceInfo *TSInfo,
15001 StorageClass SC) {
15002 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15003 if (getLangOpts().ObjCAutoRefCount &&
15004 T.getObjCLifetime() == Qualifiers::OCL_None &&
15005 T->isObjCLifetimeType()) {
15007 Qualifiers::ObjCLifetime lifetime;
15009 // Special cases for arrays:
15010 // - if it's const, use __unsafe_unretained
15011 // - otherwise, it's an error
15012 if (T->isArrayType()) {
15013 if (!T.isConstQualified()) {
15014 if (DelayedDiagnostics.shouldDelayDiagnostics())
15015 DelayedDiagnostics.add(
15016 sema::DelayedDiagnostic::makeForbiddenType(
15017 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15018 else
15019 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15020 << TSInfo->getTypeLoc().getSourceRange();
15022 lifetime = Qualifiers::OCL_ExplicitNone;
15023 } else {
15024 lifetime = T->getObjCARCImplicitLifetime();
15026 T = Context.getLifetimeQualifiedType(T, lifetime);
15029 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15030 Context.getAdjustedParameterType(T),
15031 TSInfo, SC, nullptr);
15033 // Make a note if we created a new pack in the scope of a lambda, so that
15034 // we know that references to that pack must also be expanded within the
15035 // lambda scope.
15036 if (New->isParameterPack())
15037 if (auto *LSI = getEnclosingLambda())
15038 LSI->LocalPacks.push_back(New);
15040 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15041 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15042 checkNonTrivialCUnion(New->getType(), New->getLocation(),
15043 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
15045 // Parameter declarators cannot be interface types. All ObjC objects are
15046 // passed by reference.
15047 if (T->isObjCObjectType()) {
15048 SourceLocation TypeEndLoc =
15049 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
15050 Diag(NameLoc,
15051 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15052 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15053 T = Context.getObjCObjectPointerType(T);
15054 New->setType(T);
15057 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15058 // duration shall not be qualified by an address-space qualifier."
15059 // Since all parameters have automatic store duration, they can not have
15060 // an address space.
15061 if (T.getAddressSpace() != LangAS::Default &&
15062 // OpenCL allows function arguments declared to be an array of a type
15063 // to be qualified with an address space.
15064 !(getLangOpts().OpenCL &&
15065 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15066 // WebAssembly allows reference types as parameters. Funcref in particular
15067 // lives in a different address space.
15068 !(T->isFunctionPointerType() &&
15069 T.getAddressSpace() == LangAS::wasm_funcref)) {
15070 Diag(NameLoc, diag::err_arg_with_address_space);
15071 New->setInvalidDecl();
15074 // PPC MMA non-pointer types are not allowed as function argument types.
15075 if (Context.getTargetInfo().getTriple().isPPC64() &&
15076 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15077 New->setInvalidDecl();
15080 return New;
15083 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
15084 SourceLocation LocAfterDecls) {
15085 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15087 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15088 // in the declaration list shall have at least one declarator, those
15089 // declarators shall only declare identifiers from the identifier list, and
15090 // every identifier in the identifier list shall be declared.
15092 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15093 // identifiers it names shall be declared in the declaration list."
15095 // This is why we only diagnose in C99 and later. Note, the other conditions
15096 // listed are checked elsewhere.
15097 if (!FTI.hasPrototype) {
15098 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15099 --i;
15100 if (FTI.Params[i].Param == nullptr) {
15101 if (getLangOpts().C99) {
15102 SmallString<256> Code;
15103 llvm::raw_svector_ostream(Code)
15104 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15105 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15106 << FTI.Params[i].Ident
15107 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15110 // Implicitly declare the argument as type 'int' for lack of a better
15111 // type.
15112 AttributeFactory attrs;
15113 DeclSpec DS(attrs);
15114 const char* PrevSpec; // unused
15115 unsigned DiagID; // unused
15116 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15117 DiagID, Context.getPrintingPolicy());
15118 // Use the identifier location for the type source range.
15119 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15120 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15121 Declarator ParamD(DS, ParsedAttributesView::none(),
15122 DeclaratorContext::KNRTypeList);
15123 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15124 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15130 Decl *
15131 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
15132 MultiTemplateParamsArg TemplateParameterLists,
15133 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15134 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15135 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15136 Scope *ParentScope = FnBodyScope->getParent();
15138 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15139 // we define a non-templated function definition, we will create a declaration
15140 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15141 // The base function declaration will have the equivalent of an `omp declare
15142 // variant` annotation which specifies the mangled definition as a
15143 // specialization function under the OpenMP context defined as part of the
15144 // `omp begin declare variant`.
15145 SmallVector<FunctionDecl *, 4> Bases;
15146 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
15147 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15148 ParentScope, D, TemplateParameterLists, Bases);
15150 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15151 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15152 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15154 if (!Bases.empty())
15155 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
15157 return Dcl;
15160 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
15161 Consumer.HandleInlineFunctionDefinition(D);
15164 static bool FindPossiblePrototype(const FunctionDecl *FD,
15165 const FunctionDecl *&PossiblePrototype) {
15166 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15167 Prev = Prev->getPreviousDecl()) {
15168 // Ignore any declarations that occur in function or method
15169 // scope, because they aren't visible from the header.
15170 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15171 continue;
15173 PossiblePrototype = Prev;
15174 return Prev->getType()->isFunctionProtoType();
15176 return false;
15179 static bool
15180 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
15181 const FunctionDecl *&PossiblePrototype) {
15182 // Don't warn about invalid declarations.
15183 if (FD->isInvalidDecl())
15184 return false;
15186 // Or declarations that aren't global.
15187 if (!FD->isGlobal())
15188 return false;
15190 // Don't warn about C++ member functions.
15191 if (isa<CXXMethodDecl>(FD))
15192 return false;
15194 // Don't warn about 'main'.
15195 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15196 if (IdentifierInfo *II = FD->getIdentifier())
15197 if (II->isStr("main") || II->isStr("efi_main"))
15198 return false;
15200 // Don't warn about inline functions.
15201 if (FD->isInlined())
15202 return false;
15204 // Don't warn about function templates.
15205 if (FD->getDescribedFunctionTemplate())
15206 return false;
15208 // Don't warn about function template specializations.
15209 if (FD->isFunctionTemplateSpecialization())
15210 return false;
15212 // Don't warn for OpenCL kernels.
15213 if (FD->hasAttr<OpenCLKernelAttr>())
15214 return false;
15216 // Don't warn on explicitly deleted functions.
15217 if (FD->isDeleted())
15218 return false;
15220 // Don't warn on implicitly local functions (such as having local-typed
15221 // parameters).
15222 if (!FD->isExternallyVisible())
15223 return false;
15225 // If we were able to find a potential prototype, don't warn.
15226 if (FindPossiblePrototype(FD, PossiblePrototype))
15227 return false;
15229 return true;
15232 void
15233 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
15234 const FunctionDecl *EffectiveDefinition,
15235 SkipBodyInfo *SkipBody) {
15236 const FunctionDecl *Definition = EffectiveDefinition;
15237 if (!Definition &&
15238 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15239 return;
15241 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15242 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15243 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15244 // A merged copy of the same function, instantiated as a member of
15245 // the same class, is OK.
15246 if (declaresSameEntity(OrigFD, OrigDef) &&
15247 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15248 cast<Decl>(FD->getLexicalDeclContext())))
15249 return;
15254 if (canRedefineFunction(Definition, getLangOpts()))
15255 return;
15257 // Don't emit an error when this is redefinition of a typo-corrected
15258 // definition.
15259 if (TypoCorrectedFunctionDefinitions.count(Definition))
15260 return;
15262 // If we don't have a visible definition of the function, and it's inline or
15263 // a template, skip the new definition.
15264 if (SkipBody && !hasVisibleDefinition(Definition) &&
15265 (Definition->getFormalLinkage() == InternalLinkage ||
15266 Definition->isInlined() ||
15267 Definition->getDescribedFunctionTemplate() ||
15268 Definition->getNumTemplateParameterLists())) {
15269 SkipBody->ShouldSkip = true;
15270 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15271 if (auto *TD = Definition->getDescribedFunctionTemplate())
15272 makeMergedDefinitionVisible(TD);
15273 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
15274 return;
15277 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15278 Definition->getStorageClass() == SC_Extern)
15279 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15280 << FD << getLangOpts().CPlusPlus;
15281 else
15282 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15284 Diag(Definition->getLocation(), diag::note_previous_definition);
15285 FD->setInvalidDecl();
15288 LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
15289 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15291 LambdaScopeInfo *LSI = PushLambdaScope();
15292 LSI->CallOperator = CallOperator;
15293 LSI->Lambda = LambdaClass;
15294 LSI->ReturnType = CallOperator->getReturnType();
15295 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15297 if (LCD == LCD_None)
15298 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
15299 else if (LCD == LCD_ByCopy)
15300 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
15301 else if (LCD == LCD_ByRef)
15302 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
15303 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15305 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
15306 LSI->Mutable = !CallOperator->isConst();
15308 // Add the captures to the LSI so they can be noted as already
15309 // captured within tryCaptureVar.
15310 auto I = LambdaClass->field_begin();
15311 for (const auto &C : LambdaClass->captures()) {
15312 if (C.capturesVariable()) {
15313 ValueDecl *VD = C.getCapturedVar();
15314 if (VD->isInitCapture())
15315 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
15316 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15317 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15318 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15319 /*EllipsisLoc*/C.isPackExpansion()
15320 ? C.getEllipsisLoc() : SourceLocation(),
15321 I->getType(), /*Invalid*/false);
15323 } else if (C.capturesThis()) {
15324 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15325 C.getCaptureKind() == LCK_StarThis);
15326 } else {
15327 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15328 I->getType());
15330 ++I;
15332 return LSI;
15335 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
15336 SkipBodyInfo *SkipBody,
15337 FnBodyKind BodyKind) {
15338 if (!D) {
15339 // Parsing the function declaration failed in some way. Push on a fake scope
15340 // anyway so we can try to parse the function body.
15341 PushFunctionScope();
15342 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15343 return D;
15346 FunctionDecl *FD = nullptr;
15348 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15349 FD = FunTmpl->getTemplatedDecl();
15350 else
15351 FD = cast<FunctionDecl>(D);
15353 // Do not push if it is a lambda because one is already pushed when building
15354 // the lambda in ActOnStartOfLambdaDefinition().
15355 if (!isLambdaCallOperator(FD))
15356 // [expr.const]/p14.1
15357 // An expression or conversion is in an immediate function context if it is
15358 // potentially evaluated and either: its innermost enclosing non-block scope
15359 // is a function parameter scope of an immediate function.
15360 PushExpressionEvaluationContext(
15361 FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
15362 : ExprEvalContexts.back().Context);
15364 // Each ExpressionEvaluationContextRecord also keeps track of whether the
15365 // context is nested in an immediate function context, so smaller contexts
15366 // that appear inside immediate functions (like variable initializers) are
15367 // considered to be inside an immediate function context even though by
15368 // themselves they are not immediate function contexts. But when a new
15369 // function is entered, we need to reset this tracking, since the entered
15370 // function might be not an immediate function.
15371 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15372 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15373 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15375 // Check for defining attributes before the check for redefinition.
15376 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15377 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15378 FD->dropAttr<AliasAttr>();
15379 FD->setInvalidDecl();
15381 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15382 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15383 FD->dropAttr<IFuncAttr>();
15384 FD->setInvalidDecl();
15386 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15387 if (!Context.getTargetInfo().hasFeature("fmv") &&
15388 !Attr->isDefaultVersion()) {
15389 // If function multi versioning disabled skip parsing function body
15390 // defined with non-default target_version attribute
15391 if (SkipBody)
15392 SkipBody->ShouldSkip = true;
15393 return nullptr;
15397 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15398 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15399 Ctor->isDefaultConstructor() &&
15400 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15401 // If this is an MS ABI dllexport default constructor, instantiate any
15402 // default arguments.
15403 InstantiateDefaultCtorDefaultArgs(Ctor);
15407 // See if this is a redefinition. If 'will have body' (or similar) is already
15408 // set, then these checks were already performed when it was set.
15409 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15410 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
15411 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15413 // If we're skipping the body, we're done. Don't enter the scope.
15414 if (SkipBody && SkipBody->ShouldSkip)
15415 return D;
15418 // Mark this function as "will have a body eventually". This lets users to
15419 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15420 // this function.
15421 FD->setWillHaveBody();
15423 // If we are instantiating a generic lambda call operator, push
15424 // a LambdaScopeInfo onto the function stack. But use the information
15425 // that's already been calculated (ActOnLambdaExpr) to prime the current
15426 // LambdaScopeInfo.
15427 // When the template operator is being specialized, the LambdaScopeInfo,
15428 // has to be properly restored so that tryCaptureVariable doesn't try
15429 // and capture any new variables. In addition when calculating potential
15430 // captures during transformation of nested lambdas, it is necessary to
15431 // have the LSI properly restored.
15432 if (isGenericLambdaCallOperatorSpecialization(FD)) {
15433 assert(inTemplateInstantiation() &&
15434 "There should be an active template instantiation on the stack "
15435 "when instantiating a generic lambda!");
15436 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
15437 } else {
15438 // Enter a new function scope
15439 PushFunctionScope();
15442 // Builtin functions cannot be defined.
15443 if (unsigned BuiltinID = FD->getBuiltinID()) {
15444 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
15445 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
15446 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15447 FD->setInvalidDecl();
15451 // The return type of a function definition must be complete (C99 6.9.1p3).
15452 // C++23 [dcl.fct.def.general]/p2
15453 // The type of [...] the return for a function definition
15454 // shall not be a (possibly cv-qualified) class type that is incomplete
15455 // or abstract within the function body unless the function is deleted.
15456 QualType ResultType = FD->getReturnType();
15457 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15458 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15459 (RequireCompleteType(FD->getLocation(), ResultType,
15460 diag::err_func_def_incomplete_result) ||
15461 RequireNonAbstractType(FD->getLocation(), FD->getReturnType(),
15462 diag::err_abstract_type_in_decl,
15463 AbstractReturnType)))
15464 FD->setInvalidDecl();
15466 if (FnBodyScope)
15467 PushDeclContext(FnBodyScope, FD);
15469 // Check the validity of our function parameters
15470 if (BodyKind != FnBodyKind::Delete)
15471 CheckParmsForFunctionDef(FD->parameters(),
15472 /*CheckParameterNames=*/true);
15474 // Add non-parameter declarations already in the function to the current
15475 // scope.
15476 if (FnBodyScope) {
15477 for (Decl *NPD : FD->decls()) {
15478 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15479 if (!NonParmDecl)
15480 continue;
15481 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15482 "parameters should not be in newly created FD yet");
15484 // If the decl has a name, make it accessible in the current scope.
15485 if (NonParmDecl->getDeclName())
15486 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15488 // Similarly, dive into enums and fish their constants out, making them
15489 // accessible in this scope.
15490 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15491 for (auto *EI : ED->enumerators())
15492 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15497 // Introduce our parameters into the function scope
15498 for (auto *Param : FD->parameters()) {
15499 Param->setOwningFunction(FD);
15501 // If this has an identifier, add it to the scope stack.
15502 if (Param->getIdentifier() && FnBodyScope) {
15503 CheckShadow(FnBodyScope, Param);
15505 PushOnScopeChains(Param, FnBodyScope);
15509 // C++ [module.import/6] external definitions are not permitted in header
15510 // units. Deleted and Defaulted functions are implicitly inline (but the
15511 // inline state is not set at this point, so check the BodyKind explicitly).
15512 // FIXME: Consider an alternate location for the test where the inlined()
15513 // state is complete.
15514 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15515 !FD->isInvalidDecl() && !FD->isInlined() &&
15516 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15517 FD->getFormalLinkage() == Linkage::ExternalLinkage &&
15518 !FD->isTemplated() && !FD->isTemplateInstantiation()) {
15519 assert(FD->isThisDeclarationADefinition());
15520 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15521 FD->setInvalidDecl();
15524 // Ensure that the function's exception specification is instantiated.
15525 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15526 ResolveExceptionSpec(D->getLocation(), FPT);
15528 // dllimport cannot be applied to non-inline function definitions.
15529 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15530 !FD->isTemplateInstantiation()) {
15531 assert(!FD->hasAttr<DLLExportAttr>());
15532 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15533 FD->setInvalidDecl();
15534 return D;
15536 // We want to attach documentation to original Decl (which might be
15537 // a function template).
15538 ActOnDocumentableDecl(D);
15539 if (getCurLexicalContext()->isObjCContainer() &&
15540 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15541 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15542 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15544 return D;
15547 /// Given the set of return statements within a function body,
15548 /// compute the variables that are subject to the named return value
15549 /// optimization.
15551 /// Each of the variables that is subject to the named return value
15552 /// optimization will be marked as NRVO variables in the AST, and any
15553 /// return statement that has a marked NRVO variable as its NRVO candidate can
15554 /// use the named return value optimization.
15556 /// This function applies a very simplistic algorithm for NRVO: if every return
15557 /// statement in the scope of a variable has the same NRVO candidate, that
15558 /// candidate is an NRVO variable.
15559 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
15560 ReturnStmt **Returns = Scope->Returns.data();
15562 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15563 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15564 if (!NRVOCandidate->isNRVOVariable())
15565 Returns[I]->setNRVOCandidate(nullptr);
15570 bool Sema::canDelayFunctionBody(const Declarator &D) {
15571 // We can't delay parsing the body of a constexpr function template (yet).
15572 if (D.getDeclSpec().hasConstexprSpecifier())
15573 return false;
15575 // We can't delay parsing the body of a function template with a deduced
15576 // return type (yet).
15577 if (D.getDeclSpec().hasAutoTypeSpec()) {
15578 // If the placeholder introduces a non-deduced trailing return type,
15579 // we can still delay parsing it.
15580 if (D.getNumTypeObjects()) {
15581 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15582 if (Outer.Kind == DeclaratorChunk::Function &&
15583 Outer.Fun.hasTrailingReturnType()) {
15584 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15585 return Ty.isNull() || !Ty->isUndeducedType();
15588 return false;
15591 return true;
15594 bool Sema::canSkipFunctionBody(Decl *D) {
15595 // We cannot skip the body of a function (or function template) which is
15596 // constexpr, since we may need to evaluate its body in order to parse the
15597 // rest of the file.
15598 // We cannot skip the body of a function with an undeduced return type,
15599 // because any callers of that function need to know the type.
15600 if (const FunctionDecl *FD = D->getAsFunction()) {
15601 if (FD->isConstexpr())
15602 return false;
15603 // We can't simply call Type::isUndeducedType here, because inside template
15604 // auto can be deduced to a dependent type, which is not considered
15605 // "undeduced".
15606 if (FD->getReturnType()->getContainedDeducedType())
15607 return false;
15609 return Consumer.shouldSkipFunctionBody(D);
15612 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
15613 if (!Decl)
15614 return nullptr;
15615 if (FunctionDecl *FD = Decl->getAsFunction())
15616 FD->setHasSkippedBody();
15617 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15618 MD->setHasSkippedBody();
15619 return Decl;
15622 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
15623 return ActOnFinishFunctionBody(D, BodyArg, false);
15626 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
15627 /// body.
15628 class ExitFunctionBodyRAII {
15629 public:
15630 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15631 ~ExitFunctionBodyRAII() {
15632 if (!IsLambda)
15633 S.PopExpressionEvaluationContext();
15636 private:
15637 Sema &S;
15638 bool IsLambda = false;
15641 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
15642 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15644 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15645 if (EscapeInfo.count(BD))
15646 return EscapeInfo[BD];
15648 bool R = false;
15649 const BlockDecl *CurBD = BD;
15651 do {
15652 R = !CurBD->doesNotEscape();
15653 if (R)
15654 break;
15655 CurBD = CurBD->getParent()->getInnermostBlockDecl();
15656 } while (CurBD);
15658 return EscapeInfo[BD] = R;
15661 // If the location where 'self' is implicitly retained is inside a escaping
15662 // block, emit a diagnostic.
15663 for (const std::pair<SourceLocation, const BlockDecl *> &P :
15664 S.ImplicitlyRetainedSelfLocs)
15665 if (IsOrNestedInEscapingBlock(P.second))
15666 S.Diag(P.first, diag::warn_implicitly_retains_self)
15667 << FixItHint::CreateInsertion(P.first, "self->");
15670 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
15671 bool IsInstantiation) {
15672 FunctionScopeInfo *FSI = getCurFunction();
15673 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15675 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15676 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15678 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15679 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15681 if (getLangOpts().Coroutines && FSI->isCoroutine())
15682 CheckCompletedCoroutineBody(FD, Body);
15685 // Do not call PopExpressionEvaluationContext() if it is a lambda because
15686 // one is already popped when finishing the lambda in BuildLambdaExpr().
15687 // This is meant to pop the context added in ActOnStartOfFunctionDef().
15688 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15689 if (FD) {
15690 FD->setBody(Body);
15691 FD->setWillHaveBody(false);
15692 CheckImmediateEscalatingFunctionDefinition(FD, FSI);
15694 if (getLangOpts().CPlusPlus14) {
15695 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
15696 FD->getReturnType()->isUndeducedType()) {
15697 // For a function with a deduced result type to return void,
15698 // the result type as written must be 'auto' or 'decltype(auto)',
15699 // possibly cv-qualified or constrained, but not ref-qualified.
15700 if (!FD->getReturnType()->getAs<AutoType>()) {
15701 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
15702 << FD->getReturnType();
15703 FD->setInvalidDecl();
15704 } else {
15705 // Falling off the end of the function is the same as 'return;'.
15706 Expr *Dummy = nullptr;
15707 if (DeduceFunctionTypeFromReturnExpr(
15708 FD, dcl->getLocation(), Dummy,
15709 FD->getReturnType()->getAs<AutoType>()))
15710 FD->setInvalidDecl();
15713 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
15714 // In C++11, we don't use 'auto' deduction rules for lambda call
15715 // operators because we don't support return type deduction.
15716 auto *LSI = getCurLambda();
15717 if (LSI->HasImplicitReturnType) {
15718 deduceClosureReturnType(*LSI);
15720 // C++11 [expr.prim.lambda]p4:
15721 // [...] if there are no return statements in the compound-statement
15722 // [the deduced type is] the type void
15723 QualType RetType =
15724 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
15726 // Update the return type to the deduced type.
15727 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
15728 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
15729 Proto->getExtProtoInfo()));
15733 // If the function implicitly returns zero (like 'main') or is naked,
15734 // don't complain about missing return statements.
15735 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
15736 WP.disableCheckFallThrough();
15738 // MSVC permits the use of pure specifier (=0) on function definition,
15739 // defined at class scope, warn about this non-standard construct.
15740 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
15741 Diag(FD->getLocation(), diag::ext_pure_function_definition);
15743 if (!FD->isInvalidDecl()) {
15744 // Don't diagnose unused parameters of defaulted, deleted or naked
15745 // functions.
15746 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
15747 !FD->hasAttr<NakedAttr>())
15748 DiagnoseUnusedParameters(FD->parameters());
15749 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
15750 FD->getReturnType(), FD);
15752 // If this is a structor, we need a vtable.
15753 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
15754 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
15755 else if (CXXDestructorDecl *Destructor =
15756 dyn_cast<CXXDestructorDecl>(FD))
15757 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
15759 // Try to apply the named return value optimization. We have to check
15760 // if we can do this here because lambdas keep return statements around
15761 // to deduce an implicit return type.
15762 if (FD->getReturnType()->isRecordType() &&
15763 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
15764 computeNRVO(Body, FSI);
15767 // GNU warning -Wmissing-prototypes:
15768 // Warn if a global function is defined without a previous
15769 // prototype declaration. This warning is issued even if the
15770 // definition itself provides a prototype. The aim is to detect
15771 // global functions that fail to be declared in header files.
15772 const FunctionDecl *PossiblePrototype = nullptr;
15773 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15774 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15776 if (PossiblePrototype) {
15777 // We found a declaration that is not a prototype,
15778 // but that could be a zero-parameter prototype
15779 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15780 TypeLoc TL = TI->getTypeLoc();
15781 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
15782 Diag(PossiblePrototype->getLocation(),
15783 diag::note_declaration_not_a_prototype)
15784 << (FD->getNumParams() != 0)
15785 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
15786 FTL.getRParenLoc(), "void")
15787 : FixItHint{});
15789 } else {
15790 // Returns true if the token beginning at this Loc is `const`.
15791 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
15792 const LangOptions &LangOpts) {
15793 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
15794 if (LocInfo.first.isInvalid())
15795 return false;
15797 bool Invalid = false;
15798 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
15799 if (Invalid)
15800 return false;
15802 if (LocInfo.second > Buffer.size())
15803 return false;
15805 const char *LexStart = Buffer.data() + LocInfo.second;
15806 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
15808 return StartTok.consume_front("const") &&
15809 (StartTok.empty() || isWhitespace(StartTok[0]) ||
15810 StartTok.startswith("/*") || StartTok.startswith("//"));
15813 auto findBeginLoc = [&]() {
15814 // If the return type has `const` qualifier, we want to insert
15815 // `static` before `const` (and not before the typename).
15816 if ((FD->getReturnType()->isAnyPointerType() &&
15817 FD->getReturnType()->getPointeeType().isConstQualified()) ||
15818 FD->getReturnType().isConstQualified()) {
15819 // But only do this if we can determine where the `const` is.
15821 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15822 getLangOpts()))
15824 return FD->getBeginLoc();
15826 return FD->getTypeSpecStartLoc();
15828 Diag(FD->getTypeSpecStartLoc(),
15829 diag::note_static_for_internal_linkage)
15830 << /* function */ 1
15831 << (FD->getStorageClass() == SC_None
15832 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15833 : FixItHint{});
15837 // We might not have found a prototype because we didn't wish to warn on
15838 // the lack of a missing prototype. Try again without the checks for
15839 // whether we want to warn on the missing prototype.
15840 if (!PossiblePrototype)
15841 (void)FindPossiblePrototype(FD, PossiblePrototype);
15843 // If the function being defined does not have a prototype, then we may
15844 // need to diagnose it as changing behavior in C23 because we now know
15845 // whether the function accepts arguments or not. This only handles the
15846 // case where the definition has no prototype but does have parameters
15847 // and either there is no previous potential prototype, or the previous
15848 // potential prototype also has no actual prototype. This handles cases
15849 // like:
15850 // void f(); void f(a) int a; {}
15851 // void g(a) int a; {}
15852 // See MergeFunctionDecl() for other cases of the behavior change
15853 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15854 // type without a prototype.
15855 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15856 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15857 !PossiblePrototype->isImplicit()))) {
15858 // The function definition has parameters, so this will change behavior
15859 // in C23. If there is a possible prototype, it comes before the
15860 // function definition.
15861 // FIXME: The declaration may have already been diagnosed as being
15862 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15863 // there's no way to test for the "changes behavior" condition in
15864 // SemaType.cpp when forming the declaration's function type. So, we do
15865 // this awkward dance instead.
15867 // If we have a possible prototype and it declares a function with a
15868 // prototype, we don't want to diagnose it; if we have a possible
15869 // prototype and it has no prototype, it may have already been
15870 // diagnosed in SemaType.cpp as deprecated depending on whether
15871 // -Wstrict-prototypes is enabled. If we already warned about it being
15872 // deprecated, add a note that it also changes behavior. If we didn't
15873 // warn about it being deprecated (because the diagnostic is not
15874 // enabled), warn now that it is deprecated and changes behavior.
15876 // This K&R C function definition definitely changes behavior in C23,
15877 // so diagnose it.
15878 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
15879 << /*definition*/ 1 << /* not supported in C23 */ 0;
15881 // If we have a possible prototype for the function which is a user-
15882 // visible declaration, we already tested that it has no prototype.
15883 // This will change behavior in C23. This gets a warning rather than a
15884 // note because it's the same behavior-changing problem as with the
15885 // definition.
15886 if (PossiblePrototype)
15887 Diag(PossiblePrototype->getLocation(),
15888 diag::warn_non_prototype_changes_behavior)
15889 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
15890 << /*definition*/ 1;
15893 // Warn on CPUDispatch with an actual body.
15894 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15895 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15896 if (!CmpndBody->body_empty())
15897 Diag(CmpndBody->body_front()->getBeginLoc(),
15898 diag::warn_dispatch_body_ignored);
15900 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15901 const CXXMethodDecl *KeyFunction;
15902 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15903 MD->isVirtual() &&
15904 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15905 MD == KeyFunction->getCanonicalDecl()) {
15906 // Update the key-function state if necessary for this ABI.
15907 if (FD->isInlined() &&
15908 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15909 Context.setNonKeyFunction(MD);
15911 // If the newly-chosen key function is already defined, then we
15912 // need to mark the vtable as used retroactively.
15913 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15914 const FunctionDecl *Definition;
15915 if (KeyFunction && KeyFunction->isDefined(Definition))
15916 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15917 } else {
15918 // We just defined they key function; mark the vtable as used.
15919 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15924 assert(
15925 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15926 "Function parsing confused");
15927 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15928 assert(MD == getCurMethodDecl() && "Method parsing confused");
15929 MD->setBody(Body);
15930 if (!MD->isInvalidDecl()) {
15931 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15932 MD->getReturnType(), MD);
15934 if (Body)
15935 computeNRVO(Body, FSI);
15937 if (FSI->ObjCShouldCallSuper) {
15938 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15939 << MD->getSelector().getAsString();
15940 FSI->ObjCShouldCallSuper = false;
15942 if (FSI->ObjCWarnForNoDesignatedInitChain) {
15943 const ObjCMethodDecl *InitMethod = nullptr;
15944 bool isDesignated =
15945 MD->isDesignatedInitializerForTheInterface(&InitMethod);
15946 assert(isDesignated && InitMethod);
15947 (void)isDesignated;
15949 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15950 auto IFace = MD->getClassInterface();
15951 if (!IFace)
15952 return false;
15953 auto SuperD = IFace->getSuperClass();
15954 if (!SuperD)
15955 return false;
15956 return SuperD->getIdentifier() ==
15957 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15959 // Don't issue this warning for unavailable inits or direct subclasses
15960 // of NSObject.
15961 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15962 Diag(MD->getLocation(),
15963 diag::warn_objc_designated_init_missing_super_call);
15964 Diag(InitMethod->getLocation(),
15965 diag::note_objc_designated_init_marked_here);
15967 FSI->ObjCWarnForNoDesignatedInitChain = false;
15969 if (FSI->ObjCWarnForNoInitDelegation) {
15970 // Don't issue this warning for unavaialable inits.
15971 if (!MD->isUnavailable())
15972 Diag(MD->getLocation(),
15973 diag::warn_objc_secondary_init_missing_init_call);
15974 FSI->ObjCWarnForNoInitDelegation = false;
15977 diagnoseImplicitlyRetainedSelf(*this);
15978 } else {
15979 // Parsing the function declaration failed in some way. Pop the fake scope
15980 // we pushed on.
15981 PopFunctionScopeInfo(ActivePolicy, dcl);
15982 return nullptr;
15985 if (Body && FSI->HasPotentialAvailabilityViolations)
15986 DiagnoseUnguardedAvailabilityViolations(dcl);
15988 assert(!FSI->ObjCShouldCallSuper &&
15989 "This should only be set for ObjC methods, which should have been "
15990 "handled in the block above.");
15992 // Verify and clean out per-function state.
15993 if (Body && (!FD || !FD->isDefaulted())) {
15994 // C++ constructors that have function-try-blocks can't have return
15995 // statements in the handlers of that block. (C++ [except.handle]p14)
15996 // Verify this.
15997 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15998 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16000 // Verify that gotos and switch cases don't jump into scopes illegally.
16001 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16002 DiagnoseInvalidJumps(Body);
16004 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16005 if (!Destructor->getParent()->isDependentType())
16006 CheckDestructor(Destructor);
16008 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
16009 Destructor->getParent());
16012 // If any errors have occurred, clear out any temporaries that may have
16013 // been leftover. This ensures that these temporaries won't be picked up
16014 // for deletion in some later function.
16015 if (hasUncompilableErrorOccurred() ||
16016 getDiagnostics().getSuppressAllDiagnostics()) {
16017 DiscardCleanupsInEvaluationContext();
16019 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
16020 // Since the body is valid, issue any analysis-based warnings that are
16021 // enabled.
16022 ActivePolicy = &WP;
16025 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
16026 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
16027 FD->setInvalidDecl();
16029 if (FD && FD->hasAttr<NakedAttr>()) {
16030 for (const Stmt *S : Body->children()) {
16031 // Allow local register variables without initializer as they don't
16032 // require prologue.
16033 bool RegisterVariables = false;
16034 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16035 for (const auto *Decl : DS->decls()) {
16036 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16037 RegisterVariables =
16038 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16039 if (!RegisterVariables)
16040 break;
16044 if (RegisterVariables)
16045 continue;
16046 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16047 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16048 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16049 FD->setInvalidDecl();
16050 break;
16055 assert(ExprCleanupObjects.size() ==
16056 ExprEvalContexts.back().NumCleanupObjects &&
16057 "Leftover temporaries in function");
16058 assert(!Cleanup.exprNeedsCleanups() &&
16059 "Unaccounted cleanups in function");
16060 assert(MaybeODRUseExprs.empty() &&
16061 "Leftover expressions for odr-use checking");
16063 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16064 // the declaration context below. Otherwise, we're unable to transform
16065 // 'this' expressions when transforming immediate context functions.
16067 if (!IsInstantiation)
16068 PopDeclContext();
16070 PopFunctionScopeInfo(ActivePolicy, dcl);
16071 // If any errors have occurred, clear out any temporaries that may have
16072 // been leftover. This ensures that these temporaries won't be picked up for
16073 // deletion in some later function.
16074 if (hasUncompilableErrorOccurred()) {
16075 DiscardCleanupsInEvaluationContext();
16078 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
16079 !LangOpts.OMPTargetTriples.empty())) ||
16080 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
16081 auto ES = getEmissionStatus(FD);
16082 if (ES == Sema::FunctionEmissionStatus::Emitted ||
16083 ES == Sema::FunctionEmissionStatus::Unknown)
16084 DeclsToCheckForDeferredDiags.insert(FD);
16087 if (FD && !FD->isDeleted())
16088 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16090 return dcl;
16093 /// When we finish delayed parsing of an attribute, we must attach it to the
16094 /// relevant Decl.
16095 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
16096 ParsedAttributes &Attrs) {
16097 // Always attach attributes to the underlying decl.
16098 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16099 D = TD->getTemplatedDecl();
16100 ProcessDeclAttributeList(S, D, Attrs);
16102 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16103 if (Method->isStatic())
16104 checkThisInStaticMemberFunctionAttributes(Method);
16107 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
16108 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
16109 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
16110 IdentifierInfo &II, Scope *S) {
16111 // It is not valid to implicitly define a function in C23.
16112 assert(LangOpts.implicitFunctionsAllowed() &&
16113 "Implicit function declarations aren't allowed in this language mode");
16115 // Find the scope in which the identifier is injected and the corresponding
16116 // DeclContext.
16117 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16118 // In that case, we inject the declaration into the translation unit scope
16119 // instead.
16120 Scope *BlockScope = S;
16121 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16122 BlockScope = BlockScope->getParent();
16124 // Loop until we find a DeclContext that is either a function/method or the
16125 // translation unit, which are the only two valid places to implicitly define
16126 // a function. This avoids accidentally defining the function within a tag
16127 // declaration, for example.
16128 Scope *ContextScope = BlockScope;
16129 while (!ContextScope->getEntity() ||
16130 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16131 !ContextScope->getEntity()->isTranslationUnit()))
16132 ContextScope = ContextScope->getParent();
16133 ContextRAII SavedContext(*this, ContextScope->getEntity());
16135 // Before we produce a declaration for an implicitly defined
16136 // function, see whether there was a locally-scoped declaration of
16137 // this name as a function or variable. If so, use that
16138 // (non-visible) declaration, and complain about it.
16139 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16140 if (ExternCPrev) {
16141 // We still need to inject the function into the enclosing block scope so
16142 // that later (non-call) uses can see it.
16143 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16145 // C89 footnote 38:
16146 // If in fact it is not defined as having type "function returning int",
16147 // the behavior is undefined.
16148 if (!isa<FunctionDecl>(ExternCPrev) ||
16149 !Context.typesAreCompatible(
16150 cast<FunctionDecl>(ExternCPrev)->getType(),
16151 Context.getFunctionNoProtoType(Context.IntTy))) {
16152 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16153 << ExternCPrev << !getLangOpts().C99;
16154 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16155 return ExternCPrev;
16159 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16160 unsigned diag_id;
16161 if (II.getName().startswith("__builtin_"))
16162 diag_id = diag::warn_builtin_unknown;
16163 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16164 else if (getLangOpts().C99)
16165 diag_id = diag::ext_implicit_function_decl_c99;
16166 else
16167 diag_id = diag::warn_implicit_function_decl;
16169 TypoCorrection Corrected;
16170 // Because typo correction is expensive, only do it if the implicit
16171 // function declaration is going to be treated as an error.
16173 // Perform the correction before issuing the main diagnostic, as some
16174 // consumers use typo-correction callbacks to enhance the main diagnostic.
16175 if (S && !ExternCPrev &&
16176 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
16177 DeclFilterCCC<FunctionDecl> CCC{};
16178 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
16179 S, nullptr, CCC, CTK_NonError);
16182 Diag(Loc, diag_id) << &II;
16183 if (Corrected) {
16184 // If the correction is going to suggest an implicitly defined function,
16185 // skip the correction as not being a particularly good idea.
16186 bool Diagnose = true;
16187 if (const auto *D = Corrected.getCorrectionDecl())
16188 Diagnose = !D->isImplicit();
16189 if (Diagnose)
16190 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16191 /*ErrorRecovery*/ false);
16194 // If we found a prior declaration of this function, don't bother building
16195 // another one. We've already pushed that one into scope, so there's nothing
16196 // more to do.
16197 if (ExternCPrev)
16198 return ExternCPrev;
16200 // Set a Declarator for the implicit definition: int foo();
16201 const char *Dummy;
16202 AttributeFactory attrFactory;
16203 DeclSpec DS(attrFactory);
16204 unsigned DiagID;
16205 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16206 Context.getPrintingPolicy());
16207 (void)Error; // Silence warning.
16208 assert(!Error && "Error setting up implicit decl!");
16209 SourceLocation NoLoc;
16210 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
16211 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16212 /*IsAmbiguous=*/false,
16213 /*LParenLoc=*/NoLoc,
16214 /*Params=*/nullptr,
16215 /*NumParams=*/0,
16216 /*EllipsisLoc=*/NoLoc,
16217 /*RParenLoc=*/NoLoc,
16218 /*RefQualifierIsLvalueRef=*/true,
16219 /*RefQualifierLoc=*/NoLoc,
16220 /*MutableLoc=*/NoLoc, EST_None,
16221 /*ESpecRange=*/SourceRange(),
16222 /*Exceptions=*/nullptr,
16223 /*ExceptionRanges=*/nullptr,
16224 /*NumExceptions=*/0,
16225 /*NoexceptExpr=*/nullptr,
16226 /*ExceptionSpecTokens=*/nullptr,
16227 /*DeclsInPrototype=*/std::nullopt,
16228 Loc, Loc, D),
16229 std::move(DS.getAttributes()), SourceLocation());
16230 D.SetIdentifier(&II, Loc);
16232 // Insert this function into the enclosing block scope.
16233 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16234 FD->setImplicit();
16236 AddKnownFunctionAttributes(FD);
16238 return FD;
16241 /// If this function is a C++ replaceable global allocation function
16242 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
16243 /// adds any function attributes that we know a priori based on the standard.
16245 /// We need to check for duplicate attributes both here and where user-written
16246 /// attributes are applied to declarations.
16247 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
16248 FunctionDecl *FD) {
16249 if (FD->isInvalidDecl())
16250 return;
16252 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16253 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16254 return;
16256 std::optional<unsigned> AlignmentParam;
16257 bool IsNothrow = false;
16258 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16259 return;
16261 // C++2a [basic.stc.dynamic.allocation]p4:
16262 // An allocation function that has a non-throwing exception specification
16263 // indicates failure by returning a null pointer value. Any other allocation
16264 // function never returns a null pointer value and indicates failure only by
16265 // throwing an exception [...]
16267 // However, -fcheck-new invalidates this possible assumption, so don't add
16268 // NonNull when that is enabled.
16269 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16270 !getLangOpts().CheckNew)
16271 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16273 // C++2a [basic.stc.dynamic.allocation]p2:
16274 // An allocation function attempts to allocate the requested amount of
16275 // storage. [...] If the request succeeds, the value returned by a
16276 // replaceable allocation function is a [...] pointer value p0 different
16277 // from any previously returned value p1 [...]
16279 // However, this particular information is being added in codegen,
16280 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16282 // C++2a [basic.stc.dynamic.allocation]p2:
16283 // An allocation function attempts to allocate the requested amount of
16284 // storage. If it is successful, it returns the address of the start of a
16285 // block of storage whose length in bytes is at least as large as the
16286 // requested size.
16287 if (!FD->hasAttr<AllocSizeAttr>()) {
16288 FD->addAttr(AllocSizeAttr::CreateImplicit(
16289 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16290 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16293 // C++2a [basic.stc.dynamic.allocation]p3:
16294 // For an allocation function [...], the pointer returned on a successful
16295 // call shall represent the address of storage that is aligned as follows:
16296 // (3.1) If the allocation function takes an argument of type
16297 // std​::​align_­val_­t, the storage will have the alignment
16298 // specified by the value of this argument.
16299 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16300 FD->addAttr(AllocAlignAttr::CreateImplicit(
16301 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16304 // FIXME:
16305 // C++2a [basic.stc.dynamic.allocation]p3:
16306 // For an allocation function [...], the pointer returned on a successful
16307 // call shall represent the address of storage that is aligned as follows:
16308 // (3.2) Otherwise, if the allocation function is named operator new[],
16309 // the storage is aligned for any object that does not have
16310 // new-extended alignment ([basic.align]) and is no larger than the
16311 // requested size.
16312 // (3.3) Otherwise, the storage is aligned for any object that does not
16313 // have new-extended alignment and is of the requested size.
16316 /// Adds any function attributes that we know a priori based on
16317 /// the declaration of this function.
16319 /// These attributes can apply both to implicitly-declared builtins
16320 /// (like __builtin___printf_chk) or to library-declared functions
16321 /// like NSLog or printf.
16323 /// We need to check for duplicate attributes both here and where user-written
16324 /// attributes are applied to declarations.
16325 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
16326 if (FD->isInvalidDecl())
16327 return;
16329 // If this is a built-in function, map its builtin attributes to
16330 // actual attributes.
16331 if (unsigned BuiltinID = FD->getBuiltinID()) {
16332 // Handle printf-formatting attributes.
16333 unsigned FormatIdx;
16334 bool HasVAListArg;
16335 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16336 if (!FD->hasAttr<FormatAttr>()) {
16337 const char *fmt = "printf";
16338 unsigned int NumParams = FD->getNumParams();
16339 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16340 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16341 fmt = "NSString";
16342 FD->addAttr(FormatAttr::CreateImplicit(Context,
16343 &Context.Idents.get(fmt),
16344 FormatIdx+1,
16345 HasVAListArg ? 0 : FormatIdx+2,
16346 FD->getLocation()));
16349 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16350 HasVAListArg)) {
16351 if (!FD->hasAttr<FormatAttr>())
16352 FD->addAttr(FormatAttr::CreateImplicit(Context,
16353 &Context.Idents.get("scanf"),
16354 FormatIdx+1,
16355 HasVAListArg ? 0 : FormatIdx+2,
16356 FD->getLocation()));
16359 // Handle automatically recognized callbacks.
16360 SmallVector<int, 4> Encoding;
16361 if (!FD->hasAttr<CallbackAttr>() &&
16362 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16363 FD->addAttr(CallbackAttr::CreateImplicit(
16364 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16366 // Mark const if we don't care about errno and/or floating point exceptions
16367 // that are the only thing preventing the function from being const. This
16368 // allows IRgen to use LLVM intrinsics for such functions.
16369 bool NoExceptions =
16370 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
16371 bool ConstWithoutErrnoAndExceptions =
16372 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
16373 bool ConstWithoutExceptions =
16374 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
16375 if (!FD->hasAttr<ConstAttr>() &&
16376 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16377 (!ConstWithoutErrnoAndExceptions ||
16378 (!getLangOpts().MathErrno && NoExceptions)) &&
16379 (!ConstWithoutExceptions || NoExceptions))
16380 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16382 // We make "fma" on GNU or Windows const because we know it does not set
16383 // errno in those environments even though it could set errno based on the
16384 // C standard.
16385 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16386 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16387 !FD->hasAttr<ConstAttr>()) {
16388 switch (BuiltinID) {
16389 case Builtin::BI__builtin_fma:
16390 case Builtin::BI__builtin_fmaf:
16391 case Builtin::BI__builtin_fmal:
16392 case Builtin::BIfma:
16393 case Builtin::BIfmaf:
16394 case Builtin::BIfmal:
16395 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16396 break;
16397 default:
16398 break;
16402 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16403 !FD->hasAttr<ReturnsTwiceAttr>())
16404 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16405 FD->getLocation()));
16406 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16407 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16408 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16409 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16410 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16411 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16412 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16413 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16414 // Add the appropriate attribute, depending on the CUDA compilation mode
16415 // and which target the builtin belongs to. For example, during host
16416 // compilation, aux builtins are __device__, while the rest are __host__.
16417 if (getLangOpts().CUDAIsDevice !=
16418 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
16419 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16420 else
16421 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16424 // Add known guaranteed alignment for allocation functions.
16425 switch (BuiltinID) {
16426 case Builtin::BImemalign:
16427 case Builtin::BIaligned_alloc:
16428 if (!FD->hasAttr<AllocAlignAttr>())
16429 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16430 FD->getLocation()));
16431 break;
16432 default:
16433 break;
16436 // Add allocsize attribute for allocation functions.
16437 switch (BuiltinID) {
16438 case Builtin::BIcalloc:
16439 FD->addAttr(AllocSizeAttr::CreateImplicit(
16440 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16441 break;
16442 case Builtin::BImemalign:
16443 case Builtin::BIaligned_alloc:
16444 case Builtin::BIrealloc:
16445 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16446 ParamIdx(), FD->getLocation()));
16447 break;
16448 case Builtin::BImalloc:
16449 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16450 ParamIdx(), FD->getLocation()));
16451 break;
16452 default:
16453 break;
16456 // Add lifetime attribute to std::move, std::fowrard et al.
16457 switch (BuiltinID) {
16458 case Builtin::BIaddressof:
16459 case Builtin::BI__addressof:
16460 case Builtin::BI__builtin_addressof:
16461 case Builtin::BIas_const:
16462 case Builtin::BIforward:
16463 case Builtin::BIforward_like:
16464 case Builtin::BImove:
16465 case Builtin::BImove_if_noexcept:
16466 if (ParmVarDecl *P = FD->getParamDecl(0u);
16467 !P->hasAttr<LifetimeBoundAttr>())
16468 P->addAttr(
16469 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16470 break;
16471 default:
16472 break;
16476 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
16478 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16479 // throw, add an implicit nothrow attribute to any extern "C" function we come
16480 // across.
16481 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16482 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16483 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16484 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16485 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16488 IdentifierInfo *Name = FD->getIdentifier();
16489 if (!Name)
16490 return;
16491 if ((!getLangOpts().CPlusPlus &&
16492 FD->getDeclContext()->isTranslationUnit()) ||
16493 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16494 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16495 LinkageSpecDecl::lang_c)) {
16496 // Okay: this could be a libc/libm/Objective-C function we know
16497 // about.
16498 } else
16499 return;
16501 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16502 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16503 // target-specific builtins, perhaps?
16504 if (!FD->hasAttr<FormatAttr>())
16505 FD->addAttr(FormatAttr::CreateImplicit(Context,
16506 &Context.Idents.get("printf"), 2,
16507 Name->isStr("vasprintf") ? 0 : 3,
16508 FD->getLocation()));
16511 if (Name->isStr("__CFStringMakeConstantString")) {
16512 // We already have a __builtin___CFStringMakeConstantString,
16513 // but builds that use -fno-constant-cfstrings don't go through that.
16514 if (!FD->hasAttr<FormatArgAttr>())
16515 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16516 FD->getLocation()));
16520 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
16521 TypeSourceInfo *TInfo) {
16522 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16523 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16525 if (!TInfo) {
16526 assert(D.isInvalidType() && "no declarator info for valid type");
16527 TInfo = Context.getTrivialTypeSourceInfo(T);
16530 // Scope manipulation handled by caller.
16531 TypedefDecl *NewTD =
16532 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
16533 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16535 // Bail out immediately if we have an invalid declaration.
16536 if (D.isInvalidType()) {
16537 NewTD->setInvalidDecl();
16538 return NewTD;
16541 if (D.getDeclSpec().isModulePrivateSpecified()) {
16542 if (CurContext->isFunctionOrMethod())
16543 Diag(NewTD->getLocation(), diag::err_module_private_local)
16544 << 2 << NewTD
16545 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16546 << FixItHint::CreateRemoval(
16547 D.getDeclSpec().getModulePrivateSpecLoc());
16548 else
16549 NewTD->setModulePrivate();
16552 // C++ [dcl.typedef]p8:
16553 // If the typedef declaration defines an unnamed class (or
16554 // enum), the first typedef-name declared by the declaration
16555 // to be that class type (or enum type) is used to denote the
16556 // class type (or enum type) for linkage purposes only.
16557 // We need to check whether the type was declared in the declaration.
16558 switch (D.getDeclSpec().getTypeSpecType()) {
16559 case TST_enum:
16560 case TST_struct:
16561 case TST_interface:
16562 case TST_union:
16563 case TST_class: {
16564 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16565 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16566 break;
16569 default:
16570 break;
16573 return NewTD;
16576 /// Check that this is a valid underlying type for an enum declaration.
16577 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
16578 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16579 QualType T = TI->getType();
16581 if (T->isDependentType())
16582 return false;
16584 // This doesn't use 'isIntegralType' despite the error message mentioning
16585 // integral type because isIntegralType would also allow enum types in C.
16586 if (const BuiltinType *BT = T->getAs<BuiltinType>())
16587 if (BT->isInteger())
16588 return false;
16590 if (T->isBitIntType())
16591 return false;
16593 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
16596 /// Check whether this is a valid redeclaration of a previous enumeration.
16597 /// \return true if the redeclaration was invalid.
16598 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
16599 QualType EnumUnderlyingTy, bool IsFixed,
16600 const EnumDecl *Prev) {
16601 if (IsScoped != Prev->isScoped()) {
16602 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16603 << Prev->isScoped();
16604 Diag(Prev->getLocation(), diag::note_previous_declaration);
16605 return true;
16608 if (IsFixed && Prev->isFixed()) {
16609 if (!EnumUnderlyingTy->isDependentType() &&
16610 !Prev->getIntegerType()->isDependentType() &&
16611 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16612 Prev->getIntegerType())) {
16613 // TODO: Highlight the underlying type of the redeclaration.
16614 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16615 << EnumUnderlyingTy << Prev->getIntegerType();
16616 Diag(Prev->getLocation(), diag::note_previous_declaration)
16617 << Prev->getIntegerTypeRange();
16618 return true;
16620 } else if (IsFixed != Prev->isFixed()) {
16621 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16622 << Prev->isFixed();
16623 Diag(Prev->getLocation(), diag::note_previous_declaration);
16624 return true;
16627 return false;
16630 /// Get diagnostic %select index for tag kind for
16631 /// redeclaration diagnostic message.
16632 /// WARNING: Indexes apply to particular diagnostics only!
16634 /// \returns diagnostic %select index.
16635 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
16636 switch (Tag) {
16637 case TTK_Struct: return 0;
16638 case TTK_Interface: return 1;
16639 case TTK_Class: return 2;
16640 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16644 /// Determine if tag kind is a class-key compatible with
16645 /// class for redeclaration (class, struct, or __interface).
16647 /// \returns true iff the tag kind is compatible.
16648 static bool isClassCompatTagKind(TagTypeKind Tag)
16650 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
16653 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
16654 TagTypeKind TTK) {
16655 if (isa<TypedefDecl>(PrevDecl))
16656 return NTK_Typedef;
16657 else if (isa<TypeAliasDecl>(PrevDecl))
16658 return NTK_TypeAlias;
16659 else if (isa<ClassTemplateDecl>(PrevDecl))
16660 return NTK_Template;
16661 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16662 return NTK_TypeAliasTemplate;
16663 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16664 return NTK_TemplateTemplateArgument;
16665 switch (TTK) {
16666 case TTK_Struct:
16667 case TTK_Interface:
16668 case TTK_Class:
16669 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16670 case TTK_Union:
16671 return NTK_NonUnion;
16672 case TTK_Enum:
16673 return NTK_NonEnum;
16675 llvm_unreachable("invalid TTK");
16678 /// Determine whether a tag with a given kind is acceptable
16679 /// as a redeclaration of the given tag declaration.
16681 /// \returns true if the new tag kind is acceptable, false otherwise.
16682 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
16683 TagTypeKind NewTag, bool isDefinition,
16684 SourceLocation NewTagLoc,
16685 const IdentifierInfo *Name) {
16686 // C++ [dcl.type.elab]p3:
16687 // The class-key or enum keyword present in the
16688 // elaborated-type-specifier shall agree in kind with the
16689 // declaration to which the name in the elaborated-type-specifier
16690 // refers. This rule also applies to the form of
16691 // elaborated-type-specifier that declares a class-name or
16692 // friend class since it can be construed as referring to the
16693 // definition of the class. Thus, in any
16694 // elaborated-type-specifier, the enum keyword shall be used to
16695 // refer to an enumeration (7.2), the union class-key shall be
16696 // used to refer to a union (clause 9), and either the class or
16697 // struct class-key shall be used to refer to a class (clause 9)
16698 // declared using the class or struct class-key.
16699 TagTypeKind OldTag = Previous->getTagKind();
16700 if (OldTag != NewTag &&
16701 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
16702 return false;
16704 // Tags are compatible, but we might still want to warn on mismatched tags.
16705 // Non-class tags can't be mismatched at this point.
16706 if (!isClassCompatTagKind(NewTag))
16707 return true;
16709 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16710 // by our warning analysis. We don't want to warn about mismatches with (eg)
16711 // declarations in system headers that are designed to be specialized, but if
16712 // a user asks us to warn, we should warn if their code contains mismatched
16713 // declarations.
16714 auto IsIgnoredLoc = [&](SourceLocation Loc) {
16715 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
16716 Loc);
16718 if (IsIgnoredLoc(NewTagLoc))
16719 return true;
16721 auto IsIgnored = [&](const TagDecl *Tag) {
16722 return IsIgnoredLoc(Tag->getLocation());
16724 while (IsIgnored(Previous)) {
16725 Previous = Previous->getPreviousDecl();
16726 if (!Previous)
16727 return true;
16728 OldTag = Previous->getTagKind();
16731 bool isTemplate = false;
16732 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
16733 isTemplate = Record->getDescribedClassTemplate();
16735 if (inTemplateInstantiation()) {
16736 if (OldTag != NewTag) {
16737 // In a template instantiation, do not offer fix-its for tag mismatches
16738 // since they usually mess up the template instead of fixing the problem.
16739 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16740 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16741 << getRedeclDiagFromTagKind(OldTag);
16742 // FIXME: Note previous location?
16744 return true;
16747 if (isDefinition) {
16748 // On definitions, check all previous tags and issue a fix-it for each
16749 // one that doesn't match the current tag.
16750 if (Previous->getDefinition()) {
16751 // Don't suggest fix-its for redefinitions.
16752 return true;
16755 bool previousMismatch = false;
16756 for (const TagDecl *I : Previous->redecls()) {
16757 if (I->getTagKind() != NewTag) {
16758 // Ignore previous declarations for which the warning was disabled.
16759 if (IsIgnored(I))
16760 continue;
16762 if (!previousMismatch) {
16763 previousMismatch = true;
16764 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
16765 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16766 << getRedeclDiagFromTagKind(I->getTagKind());
16768 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
16769 << getRedeclDiagFromTagKind(NewTag)
16770 << FixItHint::CreateReplacement(I->getInnerLocStart(),
16771 TypeWithKeyword::getTagTypeKindName(NewTag));
16774 return true;
16777 // Identify the prevailing tag kind: this is the kind of the definition (if
16778 // there is a non-ignored definition), or otherwise the kind of the prior
16779 // (non-ignored) declaration.
16780 const TagDecl *PrevDef = Previous->getDefinition();
16781 if (PrevDef && IsIgnored(PrevDef))
16782 PrevDef = nullptr;
16783 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
16784 if (Redecl->getTagKind() != NewTag) {
16785 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16786 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16787 << getRedeclDiagFromTagKind(OldTag);
16788 Diag(Redecl->getLocation(), diag::note_previous_use);
16790 // If there is a previous definition, suggest a fix-it.
16791 if (PrevDef) {
16792 Diag(NewTagLoc, diag::note_struct_class_suggestion)
16793 << getRedeclDiagFromTagKind(Redecl->getTagKind())
16794 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
16795 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
16799 return true;
16802 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
16803 /// from an outer enclosing namespace or file scope inside a friend declaration.
16804 /// This should provide the commented out code in the following snippet:
16805 /// namespace N {
16806 /// struct X;
16807 /// namespace M {
16808 /// struct Y { friend struct /*N::*/ X; };
16809 /// }
16810 /// }
16811 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
16812 SourceLocation NameLoc) {
16813 // While the decl is in a namespace, do repeated lookup of that name and see
16814 // if we get the same namespace back. If we do not, continue until
16815 // translation unit scope, at which point we have a fully qualified NNS.
16816 SmallVector<IdentifierInfo *, 4> Namespaces;
16817 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16818 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
16819 // This tag should be declared in a namespace, which can only be enclosed by
16820 // other namespaces. Bail if there's an anonymous namespace in the chain.
16821 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
16822 if (!Namespace || Namespace->isAnonymousNamespace())
16823 return FixItHint();
16824 IdentifierInfo *II = Namespace->getIdentifier();
16825 Namespaces.push_back(II);
16826 NamedDecl *Lookup = SemaRef.LookupSingleName(
16827 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
16828 if (Lookup == Namespace)
16829 break;
16832 // Once we have all the namespaces, reverse them to go outermost first, and
16833 // build an NNS.
16834 SmallString<64> Insertion;
16835 llvm::raw_svector_ostream OS(Insertion);
16836 if (DC->isTranslationUnit())
16837 OS << "::";
16838 std::reverse(Namespaces.begin(), Namespaces.end());
16839 for (auto *II : Namespaces)
16840 OS << II->getName() << "::";
16841 return FixItHint::CreateInsertion(NameLoc, Insertion);
16844 /// Determine whether a tag originally declared in context \p OldDC can
16845 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16846 /// found a declaration in \p OldDC as a previous decl, perhaps through a
16847 /// using-declaration).
16848 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
16849 DeclContext *NewDC) {
16850 OldDC = OldDC->getRedeclContext();
16851 NewDC = NewDC->getRedeclContext();
16853 if (OldDC->Equals(NewDC))
16854 return true;
16856 // In MSVC mode, we allow a redeclaration if the contexts are related (either
16857 // encloses the other).
16858 if (S.getLangOpts().MSVCCompat &&
16859 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
16860 return true;
16862 return false;
16865 /// This is invoked when we see 'struct foo' or 'struct {'. In the
16866 /// former case, Name will be non-null. In the later case, Name will be null.
16867 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
16868 /// reference/declaration/definition of a tag.
16870 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
16871 /// trailing-type-specifier) other than one in an alias-declaration.
16873 /// \param SkipBody If non-null, will be set to indicate if the caller should
16874 /// skip the definition of this tag and treat it as if it were a declaration.
16875 DeclResult
16876 Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
16877 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
16878 const ParsedAttributesView &Attrs, AccessSpecifier AS,
16879 SourceLocation ModulePrivateLoc,
16880 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
16881 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
16882 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16883 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16884 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
16885 // If this is not a definition, it must have a name.
16886 IdentifierInfo *OrigName = Name;
16887 assert((Name != nullptr || TUK == TUK_Definition) &&
16888 "Nameless record must be a definition!");
16889 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
16891 OwnedDecl = false;
16892 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16893 bool ScopedEnum = ScopedEnumKWLoc.isValid();
16895 // FIXME: Check member specializations more carefully.
16896 bool isMemberSpecialization = false;
16897 bool Invalid = false;
16899 // We only need to do this matching if we have template parameters
16900 // or a scope specifier, which also conveniently avoids this work
16901 // for non-C++ cases.
16902 if (TemplateParameterLists.size() > 0 ||
16903 (SS.isNotEmpty() && TUK != TUK_Reference)) {
16904 if (TemplateParameterList *TemplateParams =
16905 MatchTemplateParametersToScopeSpecifier(
16906 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
16907 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
16908 if (Kind == TTK_Enum) {
16909 Diag(KWLoc, diag::err_enum_template);
16910 return true;
16913 if (TemplateParams->size() > 0) {
16914 // This is a declaration or definition of a class template (which may
16915 // be a member of another template).
16917 if (Invalid)
16918 return true;
16920 OwnedDecl = false;
16921 DeclResult Result = CheckClassTemplate(
16922 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
16923 AS, ModulePrivateLoc,
16924 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
16925 TemplateParameterLists.data(), SkipBody);
16926 return Result.get();
16927 } else {
16928 // The "template<>" header is extraneous.
16929 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16930 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16931 isMemberSpecialization = true;
16935 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16936 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16937 return true;
16940 // Figure out the underlying type if this a enum declaration. We need to do
16941 // this early, because it's needed to detect if this is an incompatible
16942 // redeclaration.
16943 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16944 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16946 if (Kind == TTK_Enum) {
16947 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16948 // No underlying type explicitly specified, or we failed to parse the
16949 // type, default to int.
16950 EnumUnderlying = Context.IntTy.getTypePtr();
16951 } else if (UnderlyingType.get()) {
16952 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16953 // integral type; any cv-qualification is ignored.
16954 TypeSourceInfo *TI = nullptr;
16955 GetTypeFromParser(UnderlyingType.get(), &TI);
16956 EnumUnderlying = TI;
16958 if (CheckEnumUnderlyingType(TI))
16959 // Recover by falling back to int.
16960 EnumUnderlying = Context.IntTy.getTypePtr();
16962 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16963 UPPC_FixedUnderlyingType))
16964 EnumUnderlying = Context.IntTy.getTypePtr();
16966 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16967 // For MSVC ABI compatibility, unfixed enums must use an underlying type
16968 // of 'int'. However, if this is an unfixed forward declaration, don't set
16969 // the underlying type unless the user enables -fms-compatibility. This
16970 // makes unfixed forward declared enums incomplete and is more conforming.
16971 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16972 EnumUnderlying = Context.IntTy.getTypePtr();
16976 DeclContext *SearchDC = CurContext;
16977 DeclContext *DC = CurContext;
16978 bool isStdBadAlloc = false;
16979 bool isStdAlignValT = false;
16981 RedeclarationKind Redecl = forRedeclarationInCurContext();
16982 if (TUK == TUK_Friend || TUK == TUK_Reference)
16983 Redecl = NotForRedeclaration;
16985 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16986 /// implemented asks for structural equivalence checking, the returned decl
16987 /// here is passed back to the parser, allowing the tag body to be parsed.
16988 auto createTagFromNewDecl = [&]() -> TagDecl * {
16989 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16990 // If there is an identifier, use the location of the identifier as the
16991 // location of the decl, otherwise use the location of the struct/union
16992 // keyword.
16993 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16994 TagDecl *New = nullptr;
16996 if (Kind == TTK_Enum) {
16997 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16998 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16999 // If this is an undefined enum, bail.
17000 if (TUK != TUK_Definition && !Invalid)
17001 return nullptr;
17002 if (EnumUnderlying) {
17003 EnumDecl *ED = cast<EnumDecl>(New);
17004 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
17005 ED->setIntegerTypeSourceInfo(TI);
17006 else
17007 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17008 QualType EnumTy = ED->getIntegerType();
17009 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17010 ? Context.getPromotedIntegerType(EnumTy)
17011 : EnumTy);
17013 } else { // struct/union
17014 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17015 nullptr);
17018 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17019 // Add alignment attributes if necessary; these attributes are checked
17020 // when the ASTContext lays out the structure.
17022 // It is important for implementing the correct semantics that this
17023 // happen here (in ActOnTag). The #pragma pack stack is
17024 // maintained as a result of parser callbacks which can occur at
17025 // many points during the parsing of a struct declaration (because
17026 // the #pragma tokens are effectively skipped over during the
17027 // parsing of the struct).
17028 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17029 AddAlignmentAttributesForRecord(RD);
17030 AddMsStructLayoutForRecord(RD);
17033 New->setLexicalDeclContext(CurContext);
17034 return New;
17037 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17038 if (Name && SS.isNotEmpty()) {
17039 // We have a nested-name tag ('struct foo::bar').
17041 // Check for invalid 'foo::'.
17042 if (SS.isInvalid()) {
17043 Name = nullptr;
17044 goto CreateNewDecl;
17047 // If this is a friend or a reference to a class in a dependent
17048 // context, don't try to make a decl for it.
17049 if (TUK == TUK_Friend || TUK == TUK_Reference) {
17050 DC = computeDeclContext(SS, false);
17051 if (!DC) {
17052 IsDependent = true;
17053 return true;
17055 } else {
17056 DC = computeDeclContext(SS, true);
17057 if (!DC) {
17058 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17059 << SS.getRange();
17060 return true;
17064 if (RequireCompleteDeclContext(SS, DC))
17065 return true;
17067 SearchDC = DC;
17068 // Look-up name inside 'foo::'.
17069 LookupQualifiedName(Previous, DC);
17071 if (Previous.isAmbiguous())
17072 return true;
17074 if (Previous.empty()) {
17075 // Name lookup did not find anything. However, if the
17076 // nested-name-specifier refers to the current instantiation,
17077 // and that current instantiation has any dependent base
17078 // classes, we might find something at instantiation time: treat
17079 // this as a dependent elaborated-type-specifier.
17080 // But this only makes any sense for reference-like lookups.
17081 if (Previous.wasNotFoundInCurrentInstantiation() &&
17082 (TUK == TUK_Reference || TUK == TUK_Friend)) {
17083 IsDependent = true;
17084 return true;
17087 // A tag 'foo::bar' must already exist.
17088 Diag(NameLoc, diag::err_not_tag_in_scope)
17089 << Kind << Name << DC << SS.getRange();
17090 Name = nullptr;
17091 Invalid = true;
17092 goto CreateNewDecl;
17094 } else if (Name) {
17095 // C++14 [class.mem]p14:
17096 // If T is the name of a class, then each of the following shall have a
17097 // name different from T:
17098 // -- every member of class T that is itself a type
17099 if (TUK != TUK_Reference && TUK != TUK_Friend &&
17100 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17101 return true;
17103 // If this is a named struct, check to see if there was a previous forward
17104 // declaration or definition.
17105 // FIXME: We're looking into outer scopes here, even when we
17106 // shouldn't be. Doing so can result in ambiguities that we
17107 // shouldn't be diagnosing.
17108 LookupName(Previous, S);
17110 // When declaring or defining a tag, ignore ambiguities introduced
17111 // by types using'ed into this scope.
17112 if (Previous.isAmbiguous() &&
17113 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
17114 LookupResult::Filter F = Previous.makeFilter();
17115 while (F.hasNext()) {
17116 NamedDecl *ND = F.next();
17117 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17118 SearchDC->getRedeclContext()))
17119 F.erase();
17121 F.done();
17124 // C++11 [namespace.memdef]p3:
17125 // If the name in a friend declaration is neither qualified nor
17126 // a template-id and the declaration is a function or an
17127 // elaborated-type-specifier, the lookup to determine whether
17128 // the entity has been previously declared shall not consider
17129 // any scopes outside the innermost enclosing namespace.
17131 // MSVC doesn't implement the above rule for types, so a friend tag
17132 // declaration may be a redeclaration of a type declared in an enclosing
17133 // scope. They do implement this rule for friend functions.
17135 // Does it matter that this should be by scope instead of by
17136 // semantic context?
17137 if (!Previous.empty() && TUK == TUK_Friend) {
17138 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17139 LookupResult::Filter F = Previous.makeFilter();
17140 bool FriendSawTagOutsideEnclosingNamespace = false;
17141 while (F.hasNext()) {
17142 NamedDecl *ND = F.next();
17143 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17144 if (DC->isFileContext() &&
17145 !EnclosingNS->Encloses(ND->getDeclContext())) {
17146 if (getLangOpts().MSVCCompat)
17147 FriendSawTagOutsideEnclosingNamespace = true;
17148 else
17149 F.erase();
17152 F.done();
17154 // Diagnose this MSVC extension in the easy case where lookup would have
17155 // unambiguously found something outside the enclosing namespace.
17156 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17157 NamedDecl *ND = Previous.getFoundDecl();
17158 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17159 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17163 // Note: there used to be some attempt at recovery here.
17164 if (Previous.isAmbiguous())
17165 return true;
17167 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
17168 // FIXME: This makes sure that we ignore the contexts associated
17169 // with C structs, unions, and enums when looking for a matching
17170 // tag declaration or definition. See the similar lookup tweak
17171 // in Sema::LookupName; is there a better way to deal with this?
17172 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17173 SearchDC = SearchDC->getParent();
17174 } else if (getLangOpts().CPlusPlus) {
17175 // Inside ObjCContainer want to keep it as a lexical decl context but go
17176 // past it (most often to TranslationUnit) to find the semantic decl
17177 // context.
17178 while (isa<ObjCContainerDecl>(SearchDC))
17179 SearchDC = SearchDC->getParent();
17181 } else if (getLangOpts().CPlusPlus) {
17182 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17183 // TagDecl the same way as we skip it for named TagDecl.
17184 while (isa<ObjCContainerDecl>(SearchDC))
17185 SearchDC = SearchDC->getParent();
17188 if (Previous.isSingleResult() &&
17189 Previous.getFoundDecl()->isTemplateParameter()) {
17190 // Maybe we will complain about the shadowed template parameter.
17191 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17192 // Just pretend that we didn't see the previous declaration.
17193 Previous.clear();
17196 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17197 DC->Equals(getStdNamespace())) {
17198 if (Name->isStr("bad_alloc")) {
17199 // This is a declaration of or a reference to "std::bad_alloc".
17200 isStdBadAlloc = true;
17202 // If std::bad_alloc has been implicitly declared (but made invisible to
17203 // name lookup), fill in this implicit declaration as the previous
17204 // declaration, so that the declarations get chained appropriately.
17205 if (Previous.empty() && StdBadAlloc)
17206 Previous.addDecl(getStdBadAlloc());
17207 } else if (Name->isStr("align_val_t")) {
17208 isStdAlignValT = true;
17209 if (Previous.empty() && StdAlignValT)
17210 Previous.addDecl(getStdAlignValT());
17214 // If we didn't find a previous declaration, and this is a reference
17215 // (or friend reference), move to the correct scope. In C++, we
17216 // also need to do a redeclaration lookup there, just in case
17217 // there's a shadow friend decl.
17218 if (Name && Previous.empty() &&
17219 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
17220 if (Invalid) goto CreateNewDecl;
17221 assert(SS.isEmpty());
17223 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
17224 // C++ [basic.scope.pdecl]p5:
17225 // -- for an elaborated-type-specifier of the form
17227 // class-key identifier
17229 // if the elaborated-type-specifier is used in the
17230 // decl-specifier-seq or parameter-declaration-clause of a
17231 // function defined in namespace scope, the identifier is
17232 // declared as a class-name in the namespace that contains
17233 // the declaration; otherwise, except as a friend
17234 // declaration, the identifier is declared in the smallest
17235 // non-class, non-function-prototype scope that contains the
17236 // declaration.
17238 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17239 // C structs and unions.
17241 // It is an error in C++ to declare (rather than define) an enum
17242 // type, including via an elaborated type specifier. We'll
17243 // diagnose that later; for now, declare the enum in the same
17244 // scope as we would have picked for any other tag type.
17246 // GNU C also supports this behavior as part of its incomplete
17247 // enum types extension, while GNU C++ does not.
17249 // Find the context where we'll be declaring the tag.
17250 // FIXME: We would like to maintain the current DeclContext as the
17251 // lexical context,
17252 SearchDC = getTagInjectionContext(SearchDC);
17254 // Find the scope where we'll be declaring the tag.
17255 S = getTagInjectionScope(S, getLangOpts());
17256 } else {
17257 assert(TUK == TUK_Friend);
17258 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17260 // C++ [namespace.memdef]p3:
17261 // If a friend declaration in a non-local class first declares a
17262 // class or function, the friend class or function is a member of
17263 // the innermost enclosing namespace.
17264 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17265 : SearchDC->getEnclosingNamespaceContext();
17268 // In C++, we need to do a redeclaration lookup to properly
17269 // diagnose some problems.
17270 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17271 // hidden declaration so that we don't get ambiguity errors when using a
17272 // type declared by an elaborated-type-specifier. In C that is not correct
17273 // and we should instead merge compatible types found by lookup.
17274 if (getLangOpts().CPlusPlus) {
17275 // FIXME: This can perform qualified lookups into function contexts,
17276 // which are meaningless.
17277 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17278 LookupQualifiedName(Previous, SearchDC);
17279 } else {
17280 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17281 LookupName(Previous, S);
17285 // If we have a known previous declaration to use, then use it.
17286 if (Previous.empty() && SkipBody && SkipBody->Previous)
17287 Previous.addDecl(SkipBody->Previous);
17289 if (!Previous.empty()) {
17290 NamedDecl *PrevDecl = Previous.getFoundDecl();
17291 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17293 // It's okay to have a tag decl in the same scope as a typedef
17294 // which hides a tag decl in the same scope. Finding this
17295 // with a redeclaration lookup can only actually happen in C++.
17297 // This is also okay for elaborated-type-specifiers, which is
17298 // technically forbidden by the current standard but which is
17299 // okay according to the likely resolution of an open issue;
17300 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17301 if (getLangOpts().CPlusPlus) {
17302 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17303 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17304 TagDecl *Tag = TT->getDecl();
17305 if (Tag->getDeclName() == Name &&
17306 Tag->getDeclContext()->getRedeclContext()
17307 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17308 PrevDecl = Tag;
17309 Previous.clear();
17310 Previous.addDecl(Tag);
17311 Previous.resolveKind();
17317 // If this is a redeclaration of a using shadow declaration, it must
17318 // declare a tag in the same context. In MSVC mode, we allow a
17319 // redefinition if either context is within the other.
17320 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17321 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17322 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
17323 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17324 !(OldTag && isAcceptableTagRedeclContext(
17325 *this, OldTag->getDeclContext(), SearchDC))) {
17326 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17327 Diag(Shadow->getTargetDecl()->getLocation(),
17328 diag::note_using_decl_target);
17329 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17330 << 0;
17331 // Recover by ignoring the old declaration.
17332 Previous.clear();
17333 goto CreateNewDecl;
17337 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17338 // If this is a use of a previous tag, or if the tag is already declared
17339 // in the same scope (so that the definition/declaration completes or
17340 // rementions the tag), reuse the decl.
17341 if (TUK == TUK_Reference || TUK == TUK_Friend ||
17342 isDeclInScope(DirectPrevDecl, SearchDC, S,
17343 SS.isNotEmpty() || isMemberSpecialization)) {
17344 // Make sure that this wasn't declared as an enum and now used as a
17345 // struct or something similar.
17346 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17347 TUK == TUK_Definition, KWLoc,
17348 Name)) {
17349 bool SafeToContinue
17350 = (PrevTagDecl->getTagKind() != TTK_Enum &&
17351 Kind != TTK_Enum);
17352 if (SafeToContinue)
17353 Diag(KWLoc, diag::err_use_with_wrong_tag)
17354 << Name
17355 << FixItHint::CreateReplacement(SourceRange(KWLoc),
17356 PrevTagDecl->getKindName());
17357 else
17358 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17359 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17361 if (SafeToContinue)
17362 Kind = PrevTagDecl->getTagKind();
17363 else {
17364 // Recover by making this an anonymous redefinition.
17365 Name = nullptr;
17366 Previous.clear();
17367 Invalid = true;
17371 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
17372 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17373 if (TUK == TUK_Reference || TUK == TUK_Friend)
17374 return PrevTagDecl;
17376 QualType EnumUnderlyingTy;
17377 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17378 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17379 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17380 EnumUnderlyingTy = QualType(T, 0);
17382 // All conflicts with previous declarations are recovered by
17383 // returning the previous declaration, unless this is a definition,
17384 // in which case we want the caller to bail out.
17385 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17386 ScopedEnum, EnumUnderlyingTy,
17387 IsFixed, PrevEnum))
17388 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
17391 // C++11 [class.mem]p1:
17392 // A member shall not be declared twice in the member-specification,
17393 // except that a nested class or member class template can be declared
17394 // and then later defined.
17395 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
17396 S->isDeclScope(PrevDecl)) {
17397 Diag(NameLoc, diag::ext_member_redeclared);
17398 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17401 if (!Invalid) {
17402 // If this is a use, just return the declaration we found, unless
17403 // we have attributes.
17404 if (TUK == TUK_Reference || TUK == TUK_Friend) {
17405 if (!Attrs.empty()) {
17406 // FIXME: Diagnose these attributes. For now, we create a new
17407 // declaration to hold them.
17408 } else if (TUK == TUK_Reference &&
17409 (PrevTagDecl->getFriendObjectKind() ==
17410 Decl::FOK_Undeclared ||
17411 PrevDecl->getOwningModule() != getCurrentModule()) &&
17412 SS.isEmpty()) {
17413 // This declaration is a reference to an existing entity, but
17414 // has different visibility from that entity: it either makes
17415 // a friend visible or it makes a type visible in a new module.
17416 // In either case, create a new declaration. We only do this if
17417 // the declaration would have meant the same thing if no prior
17418 // declaration were found, that is, if it was found in the same
17419 // scope where we would have injected a declaration.
17420 if (!getTagInjectionContext(CurContext)->getRedeclContext()
17421 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17422 return PrevTagDecl;
17423 // This is in the injected scope, create a new declaration in
17424 // that scope.
17425 S = getTagInjectionScope(S, getLangOpts());
17426 } else {
17427 return PrevTagDecl;
17431 // Diagnose attempts to redefine a tag.
17432 if (TUK == TUK_Definition) {
17433 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17434 // If we're defining a specialization and the previous definition
17435 // is from an implicit instantiation, don't emit an error
17436 // here; we'll catch this in the general case below.
17437 bool IsExplicitSpecializationAfterInstantiation = false;
17438 if (isMemberSpecialization) {
17439 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17440 IsExplicitSpecializationAfterInstantiation =
17441 RD->getTemplateSpecializationKind() !=
17442 TSK_ExplicitSpecialization;
17443 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17444 IsExplicitSpecializationAfterInstantiation =
17445 ED->getTemplateSpecializationKind() !=
17446 TSK_ExplicitSpecialization;
17449 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17450 // not keep more that one definition around (merge them). However,
17451 // ensure the decl passes the structural compatibility check in
17452 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17453 NamedDecl *Hidden = nullptr;
17454 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17455 // There is a definition of this tag, but it is not visible. We
17456 // explicitly make use of C++'s one definition rule here, and
17457 // assume that this definition is identical to the hidden one
17458 // we already have. Make the existing definition visible and
17459 // use it in place of this one.
17460 if (!getLangOpts().CPlusPlus) {
17461 // Postpone making the old definition visible until after we
17462 // complete parsing the new one and do the structural
17463 // comparison.
17464 SkipBody->CheckSameAsPrevious = true;
17465 SkipBody->New = createTagFromNewDecl();
17466 SkipBody->Previous = Def;
17467 return Def;
17468 } else {
17469 SkipBody->ShouldSkip = true;
17470 SkipBody->Previous = Def;
17471 makeMergedDefinitionVisible(Hidden);
17472 // Carry on and handle it like a normal definition. We'll
17473 // skip starting the definitiion later.
17475 } else if (!IsExplicitSpecializationAfterInstantiation) {
17476 // A redeclaration in function prototype scope in C isn't
17477 // visible elsewhere, so merely issue a warning.
17478 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17479 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17480 else
17481 Diag(NameLoc, diag::err_redefinition) << Name;
17482 notePreviousDefinition(Def,
17483 NameLoc.isValid() ? NameLoc : KWLoc);
17484 // If this is a redefinition, recover by making this
17485 // struct be anonymous, which will make any later
17486 // references get the previous definition.
17487 Name = nullptr;
17488 Previous.clear();
17489 Invalid = true;
17491 } else {
17492 // If the type is currently being defined, complain
17493 // about a nested redefinition.
17494 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17495 if (TD->isBeingDefined()) {
17496 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17497 Diag(PrevTagDecl->getLocation(),
17498 diag::note_previous_definition);
17499 Name = nullptr;
17500 Previous.clear();
17501 Invalid = true;
17505 // Okay, this is definition of a previously declared or referenced
17506 // tag. We're going to create a new Decl for it.
17509 // Okay, we're going to make a redeclaration. If this is some kind
17510 // of reference, make sure we build the redeclaration in the same DC
17511 // as the original, and ignore the current access specifier.
17512 if (TUK == TUK_Friend || TUK == TUK_Reference) {
17513 SearchDC = PrevTagDecl->getDeclContext();
17514 AS = AS_none;
17517 // If we get here we have (another) forward declaration or we
17518 // have a definition. Just create a new decl.
17520 } else {
17521 // If we get here, this is a definition of a new tag type in a nested
17522 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17523 // new decl/type. We set PrevDecl to NULL so that the entities
17524 // have distinct types.
17525 Previous.clear();
17527 // If we get here, we're going to create a new Decl. If PrevDecl
17528 // is non-NULL, it's a definition of the tag declared by
17529 // PrevDecl. If it's NULL, we have a new definition.
17531 // Otherwise, PrevDecl is not a tag, but was found with tag
17532 // lookup. This is only actually possible in C++, where a few
17533 // things like templates still live in the tag namespace.
17534 } else {
17535 // Use a better diagnostic if an elaborated-type-specifier
17536 // found the wrong kind of type on the first
17537 // (non-redeclaration) lookup.
17538 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
17539 !Previous.isForRedeclaration()) {
17540 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17541 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
17542 << Kind;
17543 Diag(PrevDecl->getLocation(), diag::note_declared_at);
17544 Invalid = true;
17546 // Otherwise, only diagnose if the declaration is in scope.
17547 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17548 SS.isNotEmpty() || isMemberSpecialization)) {
17549 // do nothing
17551 // Diagnose implicit declarations introduced by elaborated types.
17552 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
17553 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17554 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17555 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17556 Invalid = true;
17558 // Otherwise it's a declaration. Call out a particularly common
17559 // case here.
17560 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17561 unsigned Kind = 0;
17562 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17563 Diag(NameLoc, diag::err_tag_definition_of_typedef)
17564 << Name << Kind << TND->getUnderlyingType();
17565 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17566 Invalid = true;
17568 // Otherwise, diagnose.
17569 } else {
17570 // The tag name clashes with something else in the target scope,
17571 // issue an error and recover by making this tag be anonymous.
17572 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17573 notePreviousDefinition(PrevDecl, NameLoc);
17574 Name = nullptr;
17575 Invalid = true;
17578 // The existing declaration isn't relevant to us; we're in a
17579 // new scope, so clear out the previous declaration.
17580 Previous.clear();
17584 CreateNewDecl:
17586 TagDecl *PrevDecl = nullptr;
17587 if (Previous.isSingleResult())
17588 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17590 // If there is an identifier, use the location of the identifier as the
17591 // location of the decl, otherwise use the location of the struct/union
17592 // keyword.
17593 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17595 // Otherwise, create a new declaration. If there is a previous
17596 // declaration of the same entity, the two will be linked via
17597 // PrevDecl.
17598 TagDecl *New;
17600 if (Kind == TTK_Enum) {
17601 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17602 // enum X { A, B, C } D; D should chain to X.
17603 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17604 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17605 ScopedEnumUsesClassTag, IsFixed);
17607 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17608 StdAlignValT = cast<EnumDecl>(New);
17610 // If this is an undefined enum, warn.
17611 if (TUK != TUK_Definition && !Invalid) {
17612 TagDecl *Def;
17613 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17614 // C++0x: 7.2p2: opaque-enum-declaration.
17615 // Conflicts are diagnosed above. Do nothing.
17617 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17618 Diag(Loc, diag::ext_forward_ref_enum_def)
17619 << New;
17620 Diag(Def->getLocation(), diag::note_previous_definition);
17621 } else {
17622 unsigned DiagID = diag::ext_forward_ref_enum;
17623 if (getLangOpts().MSVCCompat)
17624 DiagID = diag::ext_ms_forward_ref_enum;
17625 else if (getLangOpts().CPlusPlus)
17626 DiagID = diag::err_forward_ref_enum;
17627 Diag(Loc, DiagID);
17631 if (EnumUnderlying) {
17632 EnumDecl *ED = cast<EnumDecl>(New);
17633 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17634 ED->setIntegerTypeSourceInfo(TI);
17635 else
17636 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17637 QualType EnumTy = ED->getIntegerType();
17638 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17639 ? Context.getPromotedIntegerType(EnumTy)
17640 : EnumTy);
17641 assert(ED->isComplete() && "enum with type should be complete");
17643 } else {
17644 // struct/union/class
17646 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17647 // struct X { int A; } D; D should chain to X.
17648 if (getLangOpts().CPlusPlus) {
17649 // FIXME: Look for a way to use RecordDecl for simple structs.
17650 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17651 cast_or_null<CXXRecordDecl>(PrevDecl));
17653 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17654 StdBadAlloc = cast<CXXRecordDecl>(New);
17655 } else
17656 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17657 cast_or_null<RecordDecl>(PrevDecl));
17660 if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus)
17661 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17662 << (OOK == OOK_Macro) << New->getSourceRange();
17664 // C++11 [dcl.type]p3:
17665 // A type-specifier-seq shall not define a class or enumeration [...].
17666 if (!Invalid && getLangOpts().CPlusPlus &&
17667 (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) {
17668 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
17669 << Context.getTagDeclType(New);
17670 Invalid = true;
17673 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
17674 DC->getDeclKind() == Decl::Enum) {
17675 Diag(New->getLocation(), diag::err_type_defined_in_enum)
17676 << Context.getTagDeclType(New);
17677 Invalid = true;
17680 // Maybe add qualifier info.
17681 if (SS.isNotEmpty()) {
17682 if (SS.isSet()) {
17683 // If this is either a declaration or a definition, check the
17684 // nested-name-specifier against the current context.
17685 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
17686 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
17687 isMemberSpecialization))
17688 Invalid = true;
17690 New->setQualifierInfo(SS.getWithLocInContext(Context));
17691 if (TemplateParameterLists.size() > 0) {
17692 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
17695 else
17696 Invalid = true;
17699 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17700 // Add alignment attributes if necessary; these attributes are checked when
17701 // the ASTContext lays out the structure.
17703 // It is important for implementing the correct semantics that this
17704 // happen here (in ActOnTag). The #pragma pack stack is
17705 // maintained as a result of parser callbacks which can occur at
17706 // many points during the parsing of a struct declaration (because
17707 // the #pragma tokens are effectively skipped over during the
17708 // parsing of the struct).
17709 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17710 AddAlignmentAttributesForRecord(RD);
17711 AddMsStructLayoutForRecord(RD);
17715 if (ModulePrivateLoc.isValid()) {
17716 if (isMemberSpecialization)
17717 Diag(New->getLocation(), diag::err_module_private_specialization)
17718 << 2
17719 << FixItHint::CreateRemoval(ModulePrivateLoc);
17720 // __module_private__ does not apply to local classes. However, we only
17721 // diagnose this as an error when the declaration specifiers are
17722 // freestanding. Here, we just ignore the __module_private__.
17723 else if (!SearchDC->isFunctionOrMethod())
17724 New->setModulePrivate();
17727 // If this is a specialization of a member class (of a class template),
17728 // check the specialization.
17729 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
17730 Invalid = true;
17732 // If we're declaring or defining a tag in function prototype scope in C,
17733 // note that this type can only be used within the function and add it to
17734 // the list of decls to inject into the function definition scope.
17735 if ((Name || Kind == TTK_Enum) &&
17736 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
17737 if (getLangOpts().CPlusPlus) {
17738 // C++ [dcl.fct]p6:
17739 // Types shall not be defined in return or parameter types.
17740 if (TUK == TUK_Definition && !IsTypeSpecifier) {
17741 Diag(Loc, diag::err_type_defined_in_param_type)
17742 << Name;
17743 Invalid = true;
17745 } else if (!PrevDecl) {
17746 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
17750 if (Invalid)
17751 New->setInvalidDecl();
17753 // Set the lexical context. If the tag has a C++ scope specifier, the
17754 // lexical context will be different from the semantic context.
17755 New->setLexicalDeclContext(CurContext);
17757 // Mark this as a friend decl if applicable.
17758 // In Microsoft mode, a friend declaration also acts as a forward
17759 // declaration so we always pass true to setObjectOfFriendDecl to make
17760 // the tag name visible.
17761 if (TUK == TUK_Friend)
17762 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
17764 // Set the access specifier.
17765 if (!Invalid && SearchDC->isRecord())
17766 SetMemberAccessSpecifier(New, PrevDecl, AS);
17768 if (PrevDecl)
17769 CheckRedeclarationInModule(New, PrevDecl);
17771 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
17772 New->startDefinition();
17774 ProcessDeclAttributeList(S, New, Attrs);
17775 AddPragmaAttributes(S, New);
17777 // If this has an identifier, add it to the scope stack.
17778 if (TUK == TUK_Friend) {
17779 // We might be replacing an existing declaration in the lookup tables;
17780 // if so, borrow its access specifier.
17781 if (PrevDecl)
17782 New->setAccess(PrevDecl->getAccess());
17784 DeclContext *DC = New->getDeclContext()->getRedeclContext();
17785 DC->makeDeclVisibleInContext(New);
17786 if (Name) // can be null along some error paths
17787 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17788 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
17789 } else if (Name) {
17790 S = getNonFieldDeclScope(S);
17791 PushOnScopeChains(New, S, true);
17792 } else {
17793 CurContext->addDecl(New);
17796 // If this is the C FILE type, notify the AST context.
17797 if (IdentifierInfo *II = New->getIdentifier())
17798 if (!New->isInvalidDecl() &&
17799 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
17800 II->isStr("FILE"))
17801 Context.setFILEDecl(New);
17803 if (PrevDecl)
17804 mergeDeclAttributes(New, PrevDecl);
17806 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
17807 inferGslOwnerPointerAttribute(CXXRD);
17809 // If there's a #pragma GCC visibility in scope, set the visibility of this
17810 // record.
17811 AddPushedVisibilityAttribute(New);
17813 if (isMemberSpecialization && !New->isInvalidDecl())
17814 CompleteMemberSpecialization(New, Previous);
17816 OwnedDecl = true;
17817 // In C++, don't return an invalid declaration. We can't recover well from
17818 // the cases where we make the type anonymous.
17819 if (Invalid && getLangOpts().CPlusPlus) {
17820 if (New->isBeingDefined())
17821 if (auto RD = dyn_cast<RecordDecl>(New))
17822 RD->completeDefinition();
17823 return true;
17824 } else if (SkipBody && SkipBody->ShouldSkip) {
17825 return SkipBody->Previous;
17826 } else {
17827 return New;
17831 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
17832 AdjustDeclIfTemplate(TagD);
17833 TagDecl *Tag = cast<TagDecl>(TagD);
17835 // Enter the tag context.
17836 PushDeclContext(S, Tag);
17838 ActOnDocumentableDecl(TagD);
17840 // If there's a #pragma GCC visibility in scope, set the visibility of this
17841 // record.
17842 AddPushedVisibilityAttribute(Tag);
17845 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
17846 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
17847 return false;
17849 // Make the previous decl visible.
17850 makeMergedDefinitionVisible(SkipBody.Previous);
17851 return true;
17854 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
17855 assert(IDecl->getLexicalParent() == CurContext &&
17856 "The next DeclContext should be lexically contained in the current one.");
17857 CurContext = IDecl;
17860 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
17861 SourceLocation FinalLoc,
17862 bool IsFinalSpelledSealed,
17863 bool IsAbstract,
17864 SourceLocation LBraceLoc) {
17865 AdjustDeclIfTemplate(TagD);
17866 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
17868 FieldCollector->StartClass();
17870 if (!Record->getIdentifier())
17871 return;
17873 if (IsAbstract)
17874 Record->markAbstract();
17876 if (FinalLoc.isValid()) {
17877 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
17878 IsFinalSpelledSealed
17879 ? FinalAttr::Keyword_sealed
17880 : FinalAttr::Keyword_final));
17882 // C++ [class]p2:
17883 // [...] The class-name is also inserted into the scope of the
17884 // class itself; this is known as the injected-class-name. For
17885 // purposes of access checking, the injected-class-name is treated
17886 // as if it were a public member name.
17887 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
17888 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
17889 Record->getLocation(), Record->getIdentifier(),
17890 /*PrevDecl=*/nullptr,
17891 /*DelayTypeCreation=*/true);
17892 Context.getTypeDeclType(InjectedClassName, Record);
17893 InjectedClassName->setImplicit();
17894 InjectedClassName->setAccess(AS_public);
17895 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
17896 InjectedClassName->setDescribedClassTemplate(Template);
17897 PushOnScopeChains(InjectedClassName, S);
17898 assert(InjectedClassName->isInjectedClassName() &&
17899 "Broken injected-class-name");
17902 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
17903 SourceRange BraceRange) {
17904 AdjustDeclIfTemplate(TagD);
17905 TagDecl *Tag = cast<TagDecl>(TagD);
17906 Tag->setBraceRange(BraceRange);
17908 // Make sure we "complete" the definition even it is invalid.
17909 if (Tag->isBeingDefined()) {
17910 assert(Tag->isInvalidDecl() && "We should already have completed it");
17911 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17912 RD->completeDefinition();
17915 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
17916 FieldCollector->FinishClass();
17917 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
17918 auto *Def = RD->getDefinition();
17919 assert(Def && "The record is expected to have a completed definition");
17920 unsigned NumInitMethods = 0;
17921 for (auto *Method : Def->methods()) {
17922 if (!Method->getIdentifier())
17923 continue;
17924 if (Method->getName() == "__init")
17925 NumInitMethods++;
17927 if (NumInitMethods > 1 || !Def->hasInitMethod())
17928 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
17932 // Exit this scope of this tag's definition.
17933 PopDeclContext();
17935 if (getCurLexicalContext()->isObjCContainer() &&
17936 Tag->getDeclContext()->isFileContext())
17937 Tag->setTopLevelDeclInObjCContainer();
17939 // Notify the consumer that we've defined a tag.
17940 if (!Tag->isInvalidDecl())
17941 Consumer.HandleTagDeclDefinition(Tag);
17943 // Clangs implementation of #pragma align(packed) differs in bitfield layout
17944 // from XLs and instead matches the XL #pragma pack(1) behavior.
17945 if (Context.getTargetInfo().getTriple().isOSAIX() &&
17946 AlignPackStack.hasValue()) {
17947 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17948 // Only diagnose #pragma align(packed).
17949 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17950 return;
17951 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17952 if (!RD)
17953 return;
17954 // Only warn if there is at least 1 bitfield member.
17955 if (llvm::any_of(RD->fields(),
17956 [](const FieldDecl *FD) { return FD->isBitField(); }))
17957 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17961 void Sema::ActOnObjCContainerFinishDefinition() {
17962 // Exit this scope of this interface definition.
17963 PopDeclContext();
17966 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
17967 assert(ObjCCtx == CurContext && "Mismatch of container contexts");
17968 OriginalLexicalContext = ObjCCtx;
17969 ActOnObjCContainerFinishDefinition();
17972 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
17973 ActOnObjCContainerStartDefinition(ObjCCtx);
17974 OriginalLexicalContext = nullptr;
17977 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
17978 AdjustDeclIfTemplate(TagD);
17979 TagDecl *Tag = cast<TagDecl>(TagD);
17980 Tag->setInvalidDecl();
17982 // Make sure we "complete" the definition even it is invalid.
17983 if (Tag->isBeingDefined()) {
17984 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17985 RD->completeDefinition();
17988 // We're undoing ActOnTagStartDefinition here, not
17989 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17990 // the FieldCollector.
17992 PopDeclContext();
17995 // Note that FieldName may be null for anonymous bitfields.
17996 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
17997 IdentifierInfo *FieldName, QualType FieldTy,
17998 bool IsMsStruct, Expr *BitWidth) {
17999 assert(BitWidth);
18000 if (BitWidth->containsErrors())
18001 return ExprError();
18003 // C99 6.7.2.1p4 - verify the field type.
18004 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18005 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18006 // Handle incomplete and sizeless types with a specific error.
18007 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18008 diag::err_field_incomplete_or_sizeless))
18009 return ExprError();
18010 if (FieldName)
18011 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18012 << FieldName << FieldTy << BitWidth->getSourceRange();
18013 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18014 << FieldTy << BitWidth->getSourceRange();
18015 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
18016 UPPC_BitFieldWidth))
18017 return ExprError();
18019 // If the bit-width is type- or value-dependent, don't try to check
18020 // it now.
18021 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18022 return BitWidth;
18024 llvm::APSInt Value;
18025 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
18026 if (ICE.isInvalid())
18027 return ICE;
18028 BitWidth = ICE.get();
18030 // Zero-width bitfield is ok for anonymous field.
18031 if (Value == 0 && FieldName)
18032 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
18034 if (Value.isSigned() && Value.isNegative()) {
18035 if (FieldName)
18036 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18037 << FieldName << toString(Value, 10);
18038 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18039 << toString(Value, 10);
18042 // The size of the bit-field must not exceed our maximum permitted object
18043 // size.
18044 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18045 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18046 << !FieldName << FieldName << toString(Value, 10);
18049 if (!FieldTy->isDependentType()) {
18050 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18051 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18052 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18054 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18055 // ABI.
18056 bool CStdConstraintViolation =
18057 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18058 bool MSBitfieldViolation =
18059 Value.ugt(TypeStorageSize) &&
18060 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18061 if (CStdConstraintViolation || MSBitfieldViolation) {
18062 unsigned DiagWidth =
18063 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18064 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18065 << (bool)FieldName << FieldName << toString(Value, 10)
18066 << !CStdConstraintViolation << DiagWidth;
18069 // Warn on types where the user might conceivably expect to get all
18070 // specified bits as value bits: that's all integral types other than
18071 // 'bool'.
18072 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18073 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18074 << FieldName << toString(Value, 10)
18075 << (unsigned)TypeWidth;
18079 return BitWidth;
18082 /// ActOnField - Each field of a C struct/union is passed into this in order
18083 /// to create a FieldDecl object for it.
18084 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
18085 Declarator &D, Expr *BitfieldWidth) {
18086 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
18087 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
18088 /*InitStyle=*/ICIS_NoInit, AS_public);
18089 return Res;
18092 /// HandleField - Analyze a field of a C struct or a C++ data member.
18094 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
18095 SourceLocation DeclStart,
18096 Declarator &D, Expr *BitWidth,
18097 InClassInitStyle InitStyle,
18098 AccessSpecifier AS) {
18099 if (D.isDecompositionDeclarator()) {
18100 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18101 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18102 << Decomp.getSourceRange();
18103 return nullptr;
18106 IdentifierInfo *II = D.getIdentifier();
18107 SourceLocation Loc = DeclStart;
18108 if (II) Loc = D.getIdentifierLoc();
18110 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18111 QualType T = TInfo->getType();
18112 if (getLangOpts().CPlusPlus) {
18113 CheckExtraCXXDefaultArguments(D);
18115 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18116 UPPC_DataMemberType)) {
18117 D.setInvalidType();
18118 T = Context.IntTy;
18119 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18123 DiagnoseFunctionSpecifiers(D.getDeclSpec());
18125 if (D.getDeclSpec().isInlineSpecified())
18126 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18127 << getLangOpts().CPlusPlus17;
18128 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18129 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18130 diag::err_invalid_thread)
18131 << DeclSpec::getSpecifierName(TSCS);
18133 // Check to see if this name was declared as a member previously
18134 NamedDecl *PrevDecl = nullptr;
18135 LookupResult Previous(*this, II, Loc, LookupMemberName,
18136 ForVisibleRedeclaration);
18137 LookupName(Previous, S);
18138 switch (Previous.getResultKind()) {
18139 case LookupResult::Found:
18140 case LookupResult::FoundUnresolvedValue:
18141 PrevDecl = Previous.getAsSingle<NamedDecl>();
18142 break;
18144 case LookupResult::FoundOverloaded:
18145 PrevDecl = Previous.getRepresentativeDecl();
18146 break;
18148 case LookupResult::NotFound:
18149 case LookupResult::NotFoundInCurrentInstantiation:
18150 case LookupResult::Ambiguous:
18151 break;
18153 Previous.suppressDiagnostics();
18155 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18156 // Maybe we will complain about the shadowed template parameter.
18157 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18158 // Just pretend that we didn't see the previous declaration.
18159 PrevDecl = nullptr;
18162 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18163 PrevDecl = nullptr;
18165 bool Mutable
18166 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18167 SourceLocation TSSL = D.getBeginLoc();
18168 FieldDecl *NewFD
18169 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18170 TSSL, AS, PrevDecl, &D);
18172 if (NewFD->isInvalidDecl())
18173 Record->setInvalidDecl();
18175 if (D.getDeclSpec().isModulePrivateSpecified())
18176 NewFD->setModulePrivate();
18178 if (NewFD->isInvalidDecl() && PrevDecl) {
18179 // Don't introduce NewFD into scope; there's already something
18180 // with the same name in the same scope.
18181 } else if (II) {
18182 PushOnScopeChains(NewFD, S);
18183 } else
18184 Record->addDecl(NewFD);
18186 return NewFD;
18189 /// Build a new FieldDecl and check its well-formedness.
18191 /// This routine builds a new FieldDecl given the fields name, type,
18192 /// record, etc. \p PrevDecl should refer to any previous declaration
18193 /// with the same name and in the same scope as the field to be
18194 /// created.
18196 /// \returns a new FieldDecl.
18198 /// \todo The Declarator argument is a hack. It will be removed once
18199 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
18200 TypeSourceInfo *TInfo,
18201 RecordDecl *Record, SourceLocation Loc,
18202 bool Mutable, Expr *BitWidth,
18203 InClassInitStyle InitStyle,
18204 SourceLocation TSSL,
18205 AccessSpecifier AS, NamedDecl *PrevDecl,
18206 Declarator *D) {
18207 IdentifierInfo *II = Name.getAsIdentifierInfo();
18208 bool InvalidDecl = false;
18209 if (D) InvalidDecl = D->isInvalidType();
18211 // If we receive a broken type, recover by assuming 'int' and
18212 // marking this declaration as invalid.
18213 if (T.isNull() || T->containsErrors()) {
18214 InvalidDecl = true;
18215 T = Context.IntTy;
18218 QualType EltTy = Context.getBaseElementType(T);
18219 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18220 if (RequireCompleteSizedType(Loc, EltTy,
18221 diag::err_field_incomplete_or_sizeless)) {
18222 // Fields of incomplete type force their record to be invalid.
18223 Record->setInvalidDecl();
18224 InvalidDecl = true;
18225 } else {
18226 NamedDecl *Def;
18227 EltTy->isIncompleteType(&Def);
18228 if (Def && Def->isInvalidDecl()) {
18229 Record->setInvalidDecl();
18230 InvalidDecl = true;
18235 // TR 18037 does not allow fields to be declared with address space
18236 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18237 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
18238 Diag(Loc, diag::err_field_with_address_space);
18239 Record->setInvalidDecl();
18240 InvalidDecl = true;
18243 if (LangOpts.OpenCL) {
18244 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18245 // used as structure or union field: image, sampler, event or block types.
18246 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18247 T->isBlockPointerType()) {
18248 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18249 Record->setInvalidDecl();
18250 InvalidDecl = true;
18252 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18253 // is enabled.
18254 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18255 "__cl_clang_bitfields", LangOpts)) {
18256 Diag(Loc, diag::err_opencl_bitfields);
18257 InvalidDecl = true;
18261 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18262 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18263 T.hasQualifiers()) {
18264 InvalidDecl = true;
18265 Diag(Loc, diag::err_anon_bitfield_qualifiers);
18268 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18269 // than a variably modified type.
18270 if (!InvalidDecl && T->isVariablyModifiedType()) {
18271 if (!tryToFixVariablyModifiedVarType(
18272 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18273 InvalidDecl = true;
18276 // Fields can not have abstract class types
18277 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18278 diag::err_abstract_type_in_decl,
18279 AbstractFieldType))
18280 InvalidDecl = true;
18282 if (InvalidDecl)
18283 BitWidth = nullptr;
18284 // If this is declared as a bit-field, check the bit-field.
18285 if (BitWidth) {
18286 BitWidth =
18287 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18288 if (!BitWidth) {
18289 InvalidDecl = true;
18290 BitWidth = nullptr;
18294 // Check that 'mutable' is consistent with the type of the declaration.
18295 if (!InvalidDecl && Mutable) {
18296 unsigned DiagID = 0;
18297 if (T->isReferenceType())
18298 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18299 : diag::err_mutable_reference;
18300 else if (T.isConstQualified())
18301 DiagID = diag::err_mutable_const;
18303 if (DiagID) {
18304 SourceLocation ErrLoc = Loc;
18305 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18306 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18307 Diag(ErrLoc, DiagID);
18308 if (DiagID != diag::ext_mutable_reference) {
18309 Mutable = false;
18310 InvalidDecl = true;
18315 // C++11 [class.union]p8 (DR1460):
18316 // At most one variant member of a union may have a
18317 // brace-or-equal-initializer.
18318 if (InitStyle != ICIS_NoInit)
18319 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18321 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18322 BitWidth, Mutable, InitStyle);
18323 if (InvalidDecl)
18324 NewFD->setInvalidDecl();
18326 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
18327 !PrevDecl->isPlaceholderVar(getLangOpts())) {
18328 Diag(Loc, diag::err_duplicate_member) << II;
18329 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18330 NewFD->setInvalidDecl();
18333 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18334 if (Record->isUnion()) {
18335 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18336 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18337 if (RDecl->getDefinition()) {
18338 // C++ [class.union]p1: An object of a class with a non-trivial
18339 // constructor, a non-trivial copy constructor, a non-trivial
18340 // destructor, or a non-trivial copy assignment operator
18341 // cannot be a member of a union, nor can an array of such
18342 // objects.
18343 if (CheckNontrivialField(NewFD))
18344 NewFD->setInvalidDecl();
18348 // C++ [class.union]p1: If a union contains a member of reference type,
18349 // the program is ill-formed, except when compiling with MSVC extensions
18350 // enabled.
18351 if (EltTy->isReferenceType()) {
18352 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18353 diag::ext_union_member_of_reference_type :
18354 diag::err_union_member_of_reference_type)
18355 << NewFD->getDeclName() << EltTy;
18356 if (!getLangOpts().MicrosoftExt)
18357 NewFD->setInvalidDecl();
18362 // FIXME: We need to pass in the attributes given an AST
18363 // representation, not a parser representation.
18364 if (D) {
18365 // FIXME: The current scope is almost... but not entirely... correct here.
18366 ProcessDeclAttributes(getCurScope(), NewFD, *D);
18368 if (NewFD->hasAttrs())
18369 CheckAlignasUnderalignment(NewFD);
18372 // In auto-retain/release, infer strong retension for fields of
18373 // retainable type.
18374 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
18375 NewFD->setInvalidDecl();
18377 if (T.isObjCGCWeak())
18378 Diag(Loc, diag::warn_attribute_weak_on_field);
18380 // PPC MMA non-pointer types are not allowed as field types.
18381 if (Context.getTargetInfo().getTriple().isPPC64() &&
18382 CheckPPCMMAType(T, NewFD->getLocation()))
18383 NewFD->setInvalidDecl();
18385 NewFD->setAccess(AS);
18386 return NewFD;
18389 bool Sema::CheckNontrivialField(FieldDecl *FD) {
18390 assert(FD);
18391 assert(getLangOpts().CPlusPlus && "valid check only for C++");
18393 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18394 return false;
18396 QualType EltTy = Context.getBaseElementType(FD->getType());
18397 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18398 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18399 if (RDecl->getDefinition()) {
18400 // We check for copy constructors before constructors
18401 // because otherwise we'll never get complaints about
18402 // copy constructors.
18404 CXXSpecialMember member = CXXInvalid;
18405 // We're required to check for any non-trivial constructors. Since the
18406 // implicit default constructor is suppressed if there are any
18407 // user-declared constructors, we just need to check that there is a
18408 // trivial default constructor and a trivial copy constructor. (We don't
18409 // worry about move constructors here, since this is a C++98 check.)
18410 if (RDecl->hasNonTrivialCopyConstructor())
18411 member = CXXCopyConstructor;
18412 else if (!RDecl->hasTrivialDefaultConstructor())
18413 member = CXXDefaultConstructor;
18414 else if (RDecl->hasNonTrivialCopyAssignment())
18415 member = CXXCopyAssignment;
18416 else if (RDecl->hasNonTrivialDestructor())
18417 member = CXXDestructor;
18419 if (member != CXXInvalid) {
18420 if (!getLangOpts().CPlusPlus11 &&
18421 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18422 // Objective-C++ ARC: it is an error to have a non-trivial field of
18423 // a union. However, system headers in Objective-C programs
18424 // occasionally have Objective-C lifetime objects within unions,
18425 // and rather than cause the program to fail, we make those
18426 // members unavailable.
18427 SourceLocation Loc = FD->getLocation();
18428 if (getSourceManager().isInSystemHeader(Loc)) {
18429 if (!FD->hasAttr<UnavailableAttr>())
18430 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18431 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18432 return false;
18436 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
18437 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
18438 diag::err_illegal_union_or_anon_struct_member)
18439 << FD->getParent()->isUnion() << FD->getDeclName() << member;
18440 DiagnoseNontrivial(RDecl, member);
18441 return !getLangOpts().CPlusPlus11;
18446 return false;
18449 /// TranslateIvarVisibility - Translate visibility from a token ID to an
18450 /// AST enum value.
18451 static ObjCIvarDecl::AccessControl
18452 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
18453 switch (ivarVisibility) {
18454 default: llvm_unreachable("Unknown visitibility kind");
18455 case tok::objc_private: return ObjCIvarDecl::Private;
18456 case tok::objc_public: return ObjCIvarDecl::Public;
18457 case tok::objc_protected: return ObjCIvarDecl::Protected;
18458 case tok::objc_package: return ObjCIvarDecl::Package;
18462 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
18463 /// in order to create an IvarDecl object for it.
18464 Decl *Sema::ActOnIvar(Scope *S,
18465 SourceLocation DeclStart,
18466 Declarator &D, Expr *BitfieldWidth,
18467 tok::ObjCKeywordKind Visibility) {
18469 IdentifierInfo *II = D.getIdentifier();
18470 Expr *BitWidth = (Expr*)BitfieldWidth;
18471 SourceLocation Loc = DeclStart;
18472 if (II) Loc = D.getIdentifierLoc();
18474 // FIXME: Unnamed fields can be handled in various different ways, for
18475 // example, unnamed unions inject all members into the struct namespace!
18477 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18478 QualType T = TInfo->getType();
18480 if (BitWidth) {
18481 // 6.7.2.1p3, 6.7.2.1p4
18482 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
18483 if (!BitWidth)
18484 D.setInvalidType();
18485 } else {
18486 // Not a bitfield.
18488 // validate II.
18491 if (T->isReferenceType()) {
18492 Diag(Loc, diag::err_ivar_reference_type);
18493 D.setInvalidType();
18495 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18496 // than a variably modified type.
18497 else if (T->isVariablyModifiedType()) {
18498 if (!tryToFixVariablyModifiedVarType(
18499 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
18500 D.setInvalidType();
18503 // Get the visibility (access control) for this ivar.
18504 ObjCIvarDecl::AccessControl ac =
18505 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
18506 : ObjCIvarDecl::None;
18507 // Must set ivar's DeclContext to its enclosing interface.
18508 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
18509 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
18510 return nullptr;
18511 ObjCContainerDecl *EnclosingContext;
18512 if (ObjCImplementationDecl *IMPDecl =
18513 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18514 if (LangOpts.ObjCRuntime.isFragile()) {
18515 // Case of ivar declared in an implementation. Context is that of its class.
18516 EnclosingContext = IMPDecl->getClassInterface();
18517 assert(EnclosingContext && "Implementation has no class interface!");
18519 else
18520 EnclosingContext = EnclosingDecl;
18521 } else {
18522 if (ObjCCategoryDecl *CDecl =
18523 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18524 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
18525 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
18526 return nullptr;
18529 EnclosingContext = EnclosingDecl;
18532 // Construct the decl.
18533 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
18534 DeclStart, Loc, II, T,
18535 TInfo, ac, (Expr *)BitfieldWidth);
18537 if (II) {
18538 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
18539 ForVisibleRedeclaration);
18540 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
18541 && !isa<TagDecl>(PrevDecl)) {
18542 Diag(Loc, diag::err_duplicate_member) << II;
18543 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18544 NewID->setInvalidDecl();
18548 // Process attributes attached to the ivar.
18549 ProcessDeclAttributes(S, NewID, D);
18551 if (D.isInvalidType())
18552 NewID->setInvalidDecl();
18554 // In ARC, infer 'retaining' for ivars of retainable type.
18555 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
18556 NewID->setInvalidDecl();
18558 if (D.getDeclSpec().isModulePrivateSpecified())
18559 NewID->setModulePrivate();
18561 if (II) {
18562 // FIXME: When interfaces are DeclContexts, we'll need to add
18563 // these to the interface.
18564 S->AddDecl(NewID);
18565 IdResolver.AddDecl(NewID);
18568 if (LangOpts.ObjCRuntime.isNonFragile() &&
18569 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
18570 Diag(Loc, diag::warn_ivars_in_interface);
18572 return NewID;
18575 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
18576 /// class and class extensions. For every class \@interface and class
18577 /// extension \@interface, if the last ivar is a bitfield of any type,
18578 /// then add an implicit `char :0` ivar to the end of that interface.
18579 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
18580 SmallVectorImpl<Decl *> &AllIvarDecls) {
18581 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18582 return;
18584 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18585 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18587 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
18588 return;
18589 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18590 if (!ID) {
18591 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18592 if (!CD->IsClassExtension())
18593 return;
18595 // No need to add this to end of @implementation.
18596 else
18597 return;
18599 // All conditions are met. Add a new bitfield to the tail end of ivars.
18600 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18601 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18603 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
18604 DeclLoc, DeclLoc, nullptr,
18605 Context.CharTy,
18606 Context.getTrivialTypeSourceInfo(Context.CharTy,
18607 DeclLoc),
18608 ObjCIvarDecl::Private, BW,
18609 true);
18610 AllIvarDecls.push_back(Ivar);
18613 /// [class.dtor]p4:
18614 /// At the end of the definition of a class, overload resolution is
18615 /// performed among the prospective destructors declared in that class with
18616 /// an empty argument list to select the destructor for the class, also
18617 /// known as the selected destructor.
18619 /// We do the overload resolution here, then mark the selected constructor in the AST.
18620 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18621 static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
18622 if (!Record->hasUserDeclaredDestructor()) {
18623 return;
18626 SourceLocation Loc = Record->getLocation();
18627 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
18629 for (auto *Decl : Record->decls()) {
18630 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18631 if (DD->isInvalidDecl())
18632 continue;
18633 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18634 OCS);
18635 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18639 if (OCS.empty()) {
18640 return;
18642 OverloadCandidateSet::iterator Best;
18643 unsigned Msg = 0;
18644 OverloadCandidateDisplayKind DisplayKind;
18646 switch (OCS.BestViableFunction(S, Loc, Best)) {
18647 case OR_Success:
18648 case OR_Deleted:
18649 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18650 break;
18652 case OR_Ambiguous:
18653 Msg = diag::err_ambiguous_destructor;
18654 DisplayKind = OCD_AmbiguousCandidates;
18655 break;
18657 case OR_No_Viable_Function:
18658 Msg = diag::err_no_viable_destructor;
18659 DisplayKind = OCD_AllCandidates;
18660 break;
18663 if (Msg) {
18664 // OpenCL have got their own thing going with destructors. It's slightly broken,
18665 // but we allow it.
18666 if (!S.LangOpts.OpenCL) {
18667 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18668 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18669 Record->setInvalidDecl();
18671 // It's a bit hacky: At this point we've raised an error but we want the
18672 // rest of the compiler to continue somehow working. However almost
18673 // everything we'll try to do with the class will depend on there being a
18674 // destructor. So let's pretend the first one is selected and hope for the
18675 // best.
18676 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18680 /// [class.mem.special]p5
18681 /// Two special member functions are of the same kind if:
18682 /// - they are both default constructors,
18683 /// - they are both copy or move constructors with the same first parameter
18684 /// type, or
18685 /// - they are both copy or move assignment operators with the same first
18686 /// parameter type and the same cv-qualifiers and ref-qualifier, if any.
18687 static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
18688 CXXMethodDecl *M1,
18689 CXXMethodDecl *M2,
18690 Sema::CXXSpecialMember CSM) {
18691 // We don't want to compare templates to non-templates: See
18692 // https://github.com/llvm/llvm-project/issues/59206
18693 if (CSM == Sema::CXXDefaultConstructor)
18694 return bool(M1->getDescribedFunctionTemplate()) ==
18695 bool(M2->getDescribedFunctionTemplate());
18696 if (!Context.hasSameType(M1->getParamDecl(0)->getType(),
18697 M2->getParamDecl(0)->getType()))
18698 return false;
18699 if (!Context.hasSameType(M1->getThisType(), M2->getThisType()))
18700 return false;
18702 return true;
18705 /// [class.mem.special]p6:
18706 /// An eligible special member function is a special member function for which:
18707 /// - the function is not deleted,
18708 /// - the associated constraints, if any, are satisfied, and
18709 /// - no special member function of the same kind whose associated constraints
18710 /// [CWG2595], if any, are satisfied is more constrained.
18711 static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
18712 ArrayRef<CXXMethodDecl *> Methods,
18713 Sema::CXXSpecialMember CSM) {
18714 SmallVector<bool, 4> SatisfactionStatus;
18716 for (CXXMethodDecl *Method : Methods) {
18717 const Expr *Constraints = Method->getTrailingRequiresClause();
18718 if (!Constraints)
18719 SatisfactionStatus.push_back(true);
18720 else {
18721 ConstraintSatisfaction Satisfaction;
18722 if (S.CheckFunctionConstraints(Method, Satisfaction))
18723 SatisfactionStatus.push_back(false);
18724 else
18725 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18729 for (size_t i = 0; i < Methods.size(); i++) {
18730 if (!SatisfactionStatus[i])
18731 continue;
18732 CXXMethodDecl *Method = Methods[i];
18733 CXXMethodDecl *OrigMethod = Method;
18734 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18735 OrigMethod = cast<CXXMethodDecl>(MF);
18737 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18738 bool AnotherMethodIsMoreConstrained = false;
18739 for (size_t j = 0; j < Methods.size(); j++) {
18740 if (i == j || !SatisfactionStatus[j])
18741 continue;
18742 CXXMethodDecl *OtherMethod = Methods[j];
18743 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18744 OtherMethod = cast<CXXMethodDecl>(MF);
18746 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18747 CSM))
18748 continue;
18750 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18751 if (!OtherConstraints)
18752 continue;
18753 if (!Constraints) {
18754 AnotherMethodIsMoreConstrained = true;
18755 break;
18757 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18758 {Constraints},
18759 AnotherMethodIsMoreConstrained)) {
18760 // There was an error with the constraints comparison. Exit the loop
18761 // and don't consider this function eligible.
18762 AnotherMethodIsMoreConstrained = true;
18764 if (AnotherMethodIsMoreConstrained)
18765 break;
18767 // FIXME: Do not consider deleted methods as eligible after implementing
18768 // DR1734 and DR1496.
18769 if (!AnotherMethodIsMoreConstrained) {
18770 Method->setIneligibleOrNotSelected(false);
18771 Record->addedEligibleSpecialMemberFunction(Method, 1 << CSM);
18776 static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
18777 CXXRecordDecl *Record) {
18778 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
18779 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
18780 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
18781 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
18782 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
18784 for (auto *Decl : Record->decls()) {
18785 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
18786 if (!MD) {
18787 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
18788 if (FTD)
18789 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18791 if (!MD)
18792 continue;
18793 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
18794 if (CD->isInvalidDecl())
18795 continue;
18796 if (CD->isDefaultConstructor())
18797 DefaultConstructors.push_back(MD);
18798 else if (CD->isCopyConstructor())
18799 CopyConstructors.push_back(MD);
18800 else if (CD->isMoveConstructor())
18801 MoveConstructors.push_back(MD);
18802 } else if (MD->isCopyAssignmentOperator()) {
18803 CopyAssignmentOperators.push_back(MD);
18804 } else if (MD->isMoveAssignmentOperator()) {
18805 MoveAssignmentOperators.push_back(MD);
18809 SetEligibleMethods(S, Record, DefaultConstructors,
18810 Sema::CXXDefaultConstructor);
18811 SetEligibleMethods(S, Record, CopyConstructors, Sema::CXXCopyConstructor);
18812 SetEligibleMethods(S, Record, MoveConstructors, Sema::CXXMoveConstructor);
18813 SetEligibleMethods(S, Record, CopyAssignmentOperators,
18814 Sema::CXXCopyAssignment);
18815 SetEligibleMethods(S, Record, MoveAssignmentOperators,
18816 Sema::CXXMoveAssignment);
18819 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
18820 ArrayRef<Decl *> Fields, SourceLocation LBrac,
18821 SourceLocation RBrac,
18822 const ParsedAttributesView &Attrs) {
18823 assert(EnclosingDecl && "missing record or interface decl");
18825 // If this is an Objective-C @implementation or category and we have
18826 // new fields here we should reset the layout of the interface since
18827 // it will now change.
18828 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
18829 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
18830 switch (DC->getKind()) {
18831 default: break;
18832 case Decl::ObjCCategory:
18833 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
18834 break;
18835 case Decl::ObjCImplementation:
18836 Context.
18837 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
18838 break;
18842 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
18843 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
18845 // Start counting up the number of named members; make sure to include
18846 // members of anonymous structs and unions in the total.
18847 unsigned NumNamedMembers = 0;
18848 if (Record) {
18849 for (const auto *I : Record->decls()) {
18850 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
18851 if (IFD->getDeclName())
18852 ++NumNamedMembers;
18856 // Verify that all the fields are okay.
18857 SmallVector<FieldDecl*, 32> RecFields;
18859 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
18860 i != end; ++i) {
18861 FieldDecl *FD = cast<FieldDecl>(*i);
18863 // Get the type for the field.
18864 const Type *FDTy = FD->getType().getTypePtr();
18866 if (!FD->isAnonymousStructOrUnion()) {
18867 // Remember all fields written by the user.
18868 RecFields.push_back(FD);
18871 // If the field is already invalid for some reason, don't emit more
18872 // diagnostics about it.
18873 if (FD->isInvalidDecl()) {
18874 EnclosingDecl->setInvalidDecl();
18875 continue;
18878 // C99 6.7.2.1p2:
18879 // A structure or union shall not contain a member with
18880 // incomplete or function type (hence, a structure shall not
18881 // contain an instance of itself, but may contain a pointer to
18882 // an instance of itself), except that the last member of a
18883 // structure with more than one named member may have incomplete
18884 // array type; such a structure (and any union containing,
18885 // possibly recursively, a member that is such a structure)
18886 // shall not be a member of a structure or an element of an
18887 // array.
18888 bool IsLastField = (i + 1 == Fields.end());
18889 if (FDTy->isFunctionType()) {
18890 // Field declared as a function.
18891 Diag(FD->getLocation(), diag::err_field_declared_as_function)
18892 << FD->getDeclName();
18893 FD->setInvalidDecl();
18894 EnclosingDecl->setInvalidDecl();
18895 continue;
18896 } else if (FDTy->isIncompleteArrayType() &&
18897 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
18898 if (Record) {
18899 // Flexible array member.
18900 // Microsoft and g++ is more permissive regarding flexible array.
18901 // It will accept flexible array in union and also
18902 // as the sole element of a struct/class.
18903 unsigned DiagID = 0;
18904 if (!Record->isUnion() && !IsLastField) {
18905 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
18906 << FD->getDeclName() << FD->getType() << Record->getTagKind();
18907 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
18908 FD->setInvalidDecl();
18909 EnclosingDecl->setInvalidDecl();
18910 continue;
18911 } else if (Record->isUnion())
18912 DiagID = getLangOpts().MicrosoftExt
18913 ? diag::ext_flexible_array_union_ms
18914 : getLangOpts().CPlusPlus
18915 ? diag::ext_flexible_array_union_gnu
18916 : diag::err_flexible_array_union;
18917 else if (NumNamedMembers < 1)
18918 DiagID = getLangOpts().MicrosoftExt
18919 ? diag::ext_flexible_array_empty_aggregate_ms
18920 : getLangOpts().CPlusPlus
18921 ? diag::ext_flexible_array_empty_aggregate_gnu
18922 : diag::err_flexible_array_empty_aggregate;
18924 if (DiagID)
18925 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
18926 << Record->getTagKind();
18927 // While the layout of types that contain virtual bases is not specified
18928 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
18929 // virtual bases after the derived members. This would make a flexible
18930 // array member declared at the end of an object not adjacent to the end
18931 // of the type.
18932 if (CXXRecord && CXXRecord->getNumVBases() != 0)
18933 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
18934 << FD->getDeclName() << Record->getTagKind();
18935 if (!getLangOpts().C99)
18936 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
18937 << FD->getDeclName() << Record->getTagKind();
18939 // If the element type has a non-trivial destructor, we would not
18940 // implicitly destroy the elements, so disallow it for now.
18942 // FIXME: GCC allows this. We should probably either implicitly delete
18943 // the destructor of the containing class, or just allow this.
18944 QualType BaseElem = Context.getBaseElementType(FD->getType());
18945 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
18946 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
18947 << FD->getDeclName() << FD->getType();
18948 FD->setInvalidDecl();
18949 EnclosingDecl->setInvalidDecl();
18950 continue;
18952 // Okay, we have a legal flexible array member at the end of the struct.
18953 Record->setHasFlexibleArrayMember(true);
18954 } else {
18955 // In ObjCContainerDecl ivars with incomplete array type are accepted,
18956 // unless they are followed by another ivar. That check is done
18957 // elsewhere, after synthesized ivars are known.
18959 } else if (!FDTy->isDependentType() &&
18960 RequireCompleteSizedType(
18961 FD->getLocation(), FD->getType(),
18962 diag::err_field_incomplete_or_sizeless)) {
18963 // Incomplete type
18964 FD->setInvalidDecl();
18965 EnclosingDecl->setInvalidDecl();
18966 continue;
18967 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
18968 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
18969 // A type which contains a flexible array member is considered to be a
18970 // flexible array member.
18971 Record->setHasFlexibleArrayMember(true);
18972 if (!Record->isUnion()) {
18973 // If this is a struct/class and this is not the last element, reject
18974 // it. Note that GCC supports variable sized arrays in the middle of
18975 // structures.
18976 if (!IsLastField)
18977 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
18978 << FD->getDeclName() << FD->getType();
18979 else {
18980 // We support flexible arrays at the end of structs in
18981 // other structs as an extension.
18982 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
18983 << FD->getDeclName();
18987 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
18988 RequireNonAbstractType(FD->getLocation(), FD->getType(),
18989 diag::err_abstract_type_in_decl,
18990 AbstractIvarType)) {
18991 // Ivars can not have abstract class types
18992 FD->setInvalidDecl();
18994 if (Record && FDTTy->getDecl()->hasObjectMember())
18995 Record->setHasObjectMember(true);
18996 if (Record && FDTTy->getDecl()->hasVolatileMember())
18997 Record->setHasVolatileMember(true);
18998 } else if (FDTy->isObjCObjectType()) {
18999 /// A field cannot be an Objective-c object
19000 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19001 << FixItHint::CreateInsertion(FD->getLocation(), "*");
19002 QualType T = Context.getObjCObjectPointerType(FD->getType());
19003 FD->setType(T);
19004 } else if (Record && Record->isUnion() &&
19005 FD->getType().hasNonTrivialObjCLifetime() &&
19006 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19007 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19008 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
19009 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
19010 // For backward compatibility, fields of C unions declared in system
19011 // headers that have non-trivial ObjC ownership qualifications are marked
19012 // as unavailable unless the qualifier is explicit and __strong. This can
19013 // break ABI compatibility between programs compiled with ARC and MRR, but
19014 // is a better option than rejecting programs using those unions under
19015 // ARC.
19016 FD->addAttr(UnavailableAttr::CreateImplicit(
19017 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19018 FD->getLocation()));
19019 } else if (getLangOpts().ObjC &&
19020 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19021 !Record->hasObjectMember()) {
19022 if (FD->getType()->isObjCObjectPointerType() ||
19023 FD->getType().isObjCGCStrong())
19024 Record->setHasObjectMember(true);
19025 else if (Context.getAsArrayType(FD->getType())) {
19026 QualType BaseType = Context.getBaseElementType(FD->getType());
19027 if (BaseType->isRecordType() &&
19028 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19029 Record->setHasObjectMember(true);
19030 else if (BaseType->isObjCObjectPointerType() ||
19031 BaseType.isObjCGCStrong())
19032 Record->setHasObjectMember(true);
19036 if (Record && !getLangOpts().CPlusPlus &&
19037 !shouldIgnoreForRecordTriviality(FD)) {
19038 QualType FT = FD->getType();
19039 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
19040 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19041 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
19042 Record->isUnion())
19043 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19045 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
19046 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
19047 Record->setNonTrivialToPrimitiveCopy(true);
19048 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19049 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19051 if (FT.isDestructedType()) {
19052 Record->setNonTrivialToPrimitiveDestroy(true);
19053 Record->setParamDestroyedInCallee(true);
19054 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19055 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19058 if (const auto *RT = FT->getAs<RecordType>()) {
19059 if (RT->getDecl()->getArgPassingRestrictions() ==
19060 RecordDecl::APK_CanNeverPassInRegs)
19061 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
19062 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
19063 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
19066 if (Record && FD->getType().isVolatileQualified())
19067 Record->setHasVolatileMember(true);
19068 // Keep track of the number of named members.
19069 if (FD->getIdentifier())
19070 ++NumNamedMembers;
19073 // Okay, we successfully defined 'Record'.
19074 if (Record) {
19075 bool Completed = false;
19076 if (CXXRecord) {
19077 if (!CXXRecord->isInvalidDecl()) {
19078 // Set access bits correctly on the directly-declared conversions.
19079 for (CXXRecordDecl::conversion_iterator
19080 I = CXXRecord->conversion_begin(),
19081 E = CXXRecord->conversion_end(); I != E; ++I)
19082 I.setAccess((*I)->getAccess());
19085 // Add any implicitly-declared members to this class.
19086 AddImplicitlyDeclaredMembersToClass(CXXRecord);
19088 if (!CXXRecord->isDependentType()) {
19089 if (!CXXRecord->isInvalidDecl()) {
19090 // If we have virtual base classes, we may end up finding multiple
19091 // final overriders for a given virtual function. Check for this
19092 // problem now.
19093 if (CXXRecord->getNumVBases()) {
19094 CXXFinalOverriderMap FinalOverriders;
19095 CXXRecord->getFinalOverriders(FinalOverriders);
19097 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19098 MEnd = FinalOverriders.end();
19099 M != MEnd; ++M) {
19100 for (OverridingMethods::iterator SO = M->second.begin(),
19101 SOEnd = M->second.end();
19102 SO != SOEnd; ++SO) {
19103 assert(SO->second.size() > 0 &&
19104 "Virtual function without overriding functions?");
19105 if (SO->second.size() == 1)
19106 continue;
19108 // C++ [class.virtual]p2:
19109 // In a derived class, if a virtual member function of a base
19110 // class subobject has more than one final overrider the
19111 // program is ill-formed.
19112 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19113 << (const NamedDecl *)M->first << Record;
19114 Diag(M->first->getLocation(),
19115 diag::note_overridden_virtual_function);
19116 for (OverridingMethods::overriding_iterator
19117 OM = SO->second.begin(),
19118 OMEnd = SO->second.end();
19119 OM != OMEnd; ++OM)
19120 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19121 << (const NamedDecl *)M->first << OM->Method->getParent();
19123 Record->setInvalidDecl();
19126 CXXRecord->completeDefinition(&FinalOverriders);
19127 Completed = true;
19130 ComputeSelectedDestructor(*this, CXXRecord);
19131 ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord);
19135 if (!Completed)
19136 Record->completeDefinition();
19138 // Handle attributes before checking the layout.
19139 ProcessDeclAttributeList(S, Record, Attrs);
19141 // Check to see if a FieldDecl is a pointer to a function.
19142 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19143 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19144 if (!FD) {
19145 // Check whether this is a forward declaration that was inserted by
19146 // Clang. This happens when a non-forward declared / defined type is
19147 // used, e.g.:
19149 // struct foo {
19150 // struct bar *(*f)();
19151 // struct bar *(*g)();
19152 // };
19154 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19155 // incomplete definition.
19156 if (const auto *TD = dyn_cast<TagDecl>(D))
19157 return !TD->isCompleteDefinition();
19158 return false;
19160 QualType FieldType = FD->getType().getDesugaredType(Context);
19161 if (isa<PointerType>(FieldType)) {
19162 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19163 return PointeeType.getDesugaredType(Context)->isFunctionType();
19165 return false;
19168 // Maybe randomize the record's decls. We automatically randomize a record
19169 // of function pointers, unless it has the "no_randomize_layout" attribute.
19170 if (!getLangOpts().CPlusPlus &&
19171 (Record->hasAttr<RandomizeLayoutAttr>() ||
19172 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19173 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19174 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19175 !Record->isRandomized()) {
19176 SmallVector<Decl *, 32> NewDeclOrdering;
19177 if (randstruct::randomizeStructureLayout(Context, Record,
19178 NewDeclOrdering))
19179 Record->reorderDecls(NewDeclOrdering);
19182 // We may have deferred checking for a deleted destructor. Check now.
19183 if (CXXRecord) {
19184 auto *Dtor = CXXRecord->getDestructor();
19185 if (Dtor && Dtor->isImplicit() &&
19186 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
19187 CXXRecord->setImplicitDestructorIsDeleted();
19188 SetDeclDeleted(Dtor, CXXRecord->getLocation());
19192 if (Record->hasAttrs()) {
19193 CheckAlignasUnderalignment(Record);
19195 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19196 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19197 IA->getRange(), IA->getBestCase(),
19198 IA->getInheritanceModel());
19201 // Check if the structure/union declaration is a type that can have zero
19202 // size in C. For C this is a language extension, for C++ it may cause
19203 // compatibility problems.
19204 bool CheckForZeroSize;
19205 if (!getLangOpts().CPlusPlus) {
19206 CheckForZeroSize = true;
19207 } else {
19208 // For C++ filter out types that cannot be referenced in C code.
19209 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19210 CheckForZeroSize =
19211 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19212 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19213 CXXRecord->isCLike();
19215 if (CheckForZeroSize) {
19216 bool ZeroSize = true;
19217 bool IsEmpty = true;
19218 unsigned NonBitFields = 0;
19219 for (RecordDecl::field_iterator I = Record->field_begin(),
19220 E = Record->field_end();
19221 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19222 IsEmpty = false;
19223 if (I->isUnnamedBitfield()) {
19224 if (!I->isZeroLengthBitField(Context))
19225 ZeroSize = false;
19226 } else {
19227 ++NonBitFields;
19228 QualType FieldType = I->getType();
19229 if (FieldType->isIncompleteType() ||
19230 !Context.getTypeSizeInChars(FieldType).isZero())
19231 ZeroSize = false;
19235 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19236 // allowed in C++, but warn if its declaration is inside
19237 // extern "C" block.
19238 if (ZeroSize) {
19239 Diag(RecLoc, getLangOpts().CPlusPlus ?
19240 diag::warn_zero_size_struct_union_in_extern_c :
19241 diag::warn_zero_size_struct_union_compat)
19242 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19245 // Structs without named members are extension in C (C99 6.7.2.1p7),
19246 // but are accepted by GCC.
19247 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
19248 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
19249 diag::ext_no_named_members_in_struct_union)
19250 << Record->isUnion();
19253 } else {
19254 ObjCIvarDecl **ClsFields =
19255 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19256 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19257 ID->setEndOfDefinitionLoc(RBrac);
19258 // Add ivar's to class's DeclContext.
19259 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19260 ClsFields[i]->setLexicalDeclContext(ID);
19261 ID->addDecl(ClsFields[i]);
19263 // Must enforce the rule that ivars in the base classes may not be
19264 // duplicates.
19265 if (ID->getSuperClass())
19266 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19267 } else if (ObjCImplementationDecl *IMPDecl =
19268 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19269 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19270 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19271 // Ivar declared in @implementation never belongs to the implementation.
19272 // Only it is in implementation's lexical context.
19273 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19274 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
19275 IMPDecl->setIvarLBraceLoc(LBrac);
19276 IMPDecl->setIvarRBraceLoc(RBrac);
19277 } else if (ObjCCategoryDecl *CDecl =
19278 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19279 // case of ivars in class extension; all other cases have been
19280 // reported as errors elsewhere.
19281 // FIXME. Class extension does not have a LocEnd field.
19282 // CDecl->setLocEnd(RBrac);
19283 // Add ivar's to class extension's DeclContext.
19284 // Diagnose redeclaration of private ivars.
19285 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19286 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19287 if (IDecl) {
19288 if (const ObjCIvarDecl *ClsIvar =
19289 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19290 Diag(ClsFields[i]->getLocation(),
19291 diag::err_duplicate_ivar_declaration);
19292 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19293 continue;
19295 for (const auto *Ext : IDecl->known_extensions()) {
19296 if (const ObjCIvarDecl *ClsExtIvar
19297 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19298 Diag(ClsFields[i]->getLocation(),
19299 diag::err_duplicate_ivar_declaration);
19300 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19301 continue;
19305 ClsFields[i]->setLexicalDeclContext(CDecl);
19306 CDecl->addDecl(ClsFields[i]);
19308 CDecl->setIvarLBraceLoc(LBrac);
19309 CDecl->setIvarRBraceLoc(RBrac);
19314 /// Determine whether the given integral value is representable within
19315 /// the given type T.
19316 static bool isRepresentableIntegerValue(ASTContext &Context,
19317 llvm::APSInt &Value,
19318 QualType T) {
19319 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19320 "Integral type required!");
19321 unsigned BitWidth = Context.getIntWidth(T);
19323 if (Value.isUnsigned() || Value.isNonNegative()) {
19324 if (T->isSignedIntegerOrEnumerationType())
19325 --BitWidth;
19326 return Value.getActiveBits() <= BitWidth;
19328 return Value.getSignificantBits() <= BitWidth;
19331 // Given an integral type, return the next larger integral type
19332 // (or a NULL type of no such type exists).
19333 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
19334 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19335 // enum checking below.
19336 assert((T->isIntegralType(Context) ||
19337 T->isEnumeralType()) && "Integral type required!");
19338 const unsigned NumTypes = 4;
19339 QualType SignedIntegralTypes[NumTypes] = {
19340 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19342 QualType UnsignedIntegralTypes[NumTypes] = {
19343 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19344 Context.UnsignedLongLongTy
19347 unsigned BitWidth = Context.getTypeSize(T);
19348 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19349 : UnsignedIntegralTypes;
19350 for (unsigned I = 0; I != NumTypes; ++I)
19351 if (Context.getTypeSize(Types[I]) > BitWidth)
19352 return Types[I];
19354 return QualType();
19357 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
19358 EnumConstantDecl *LastEnumConst,
19359 SourceLocation IdLoc,
19360 IdentifierInfo *Id,
19361 Expr *Val) {
19362 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19363 llvm::APSInt EnumVal(IntWidth);
19364 QualType EltTy;
19366 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
19367 Val = nullptr;
19369 if (Val)
19370 Val = DefaultLvalueConversion(Val).get();
19372 if (Val) {
19373 if (Enum->isDependentType() || Val->isTypeDependent() ||
19374 Val->containsErrors())
19375 EltTy = Context.DependentTy;
19376 else {
19377 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19378 // underlying type, but do allow it in all other contexts.
19379 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19380 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19381 // constant-expression in the enumerator-definition shall be a converted
19382 // constant expression of the underlying type.
19383 EltTy = Enum->getIntegerType();
19384 ExprResult Converted =
19385 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19386 CCEK_Enumerator);
19387 if (Converted.isInvalid())
19388 Val = nullptr;
19389 else
19390 Val = Converted.get();
19391 } else if (!Val->isValueDependent() &&
19392 !(Val =
19393 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
19394 .get())) {
19395 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19396 } else {
19397 if (Enum->isComplete()) {
19398 EltTy = Enum->getIntegerType();
19400 // In Obj-C and Microsoft mode, require the enumeration value to be
19401 // representable in the underlying type of the enumeration. In C++11,
19402 // we perform a non-narrowing conversion as part of converted constant
19403 // expression checking.
19404 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19405 if (Context.getTargetInfo()
19406 .getTriple()
19407 .isWindowsMSVCEnvironment()) {
19408 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19409 } else {
19410 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19414 // Cast to the underlying type.
19415 Val = ImpCastExprToType(Val, EltTy,
19416 EltTy->isBooleanType() ? CK_IntegralToBoolean
19417 : CK_IntegralCast)
19418 .get();
19419 } else if (getLangOpts().CPlusPlus) {
19420 // C++11 [dcl.enum]p5:
19421 // If the underlying type is not fixed, the type of each enumerator
19422 // is the type of its initializing value:
19423 // - If an initializer is specified for an enumerator, the
19424 // initializing value has the same type as the expression.
19425 EltTy = Val->getType();
19426 } else {
19427 // C99 6.7.2.2p2:
19428 // The expression that defines the value of an enumeration constant
19429 // shall be an integer constant expression that has a value
19430 // representable as an int.
19432 // Complain if the value is not representable in an int.
19433 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
19434 Diag(IdLoc, diag::ext_enum_value_not_int)
19435 << toString(EnumVal, 10) << Val->getSourceRange()
19436 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19437 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19438 // Force the type of the expression to 'int'.
19439 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19441 EltTy = Val->getType();
19447 if (!Val) {
19448 if (Enum->isDependentType())
19449 EltTy = Context.DependentTy;
19450 else if (!LastEnumConst) {
19451 // C++0x [dcl.enum]p5:
19452 // If the underlying type is not fixed, the type of each enumerator
19453 // is the type of its initializing value:
19454 // - If no initializer is specified for the first enumerator, the
19455 // initializing value has an unspecified integral type.
19457 // GCC uses 'int' for its unspecified integral type, as does
19458 // C99 6.7.2.2p3.
19459 if (Enum->isFixed()) {
19460 EltTy = Enum->getIntegerType();
19462 else {
19463 EltTy = Context.IntTy;
19465 } else {
19466 // Assign the last value + 1.
19467 EnumVal = LastEnumConst->getInitVal();
19468 ++EnumVal;
19469 EltTy = LastEnumConst->getType();
19471 // Check for overflow on increment.
19472 if (EnumVal < LastEnumConst->getInitVal()) {
19473 // C++0x [dcl.enum]p5:
19474 // If the underlying type is not fixed, the type of each enumerator
19475 // is the type of its initializing value:
19477 // - Otherwise the type of the initializing value is the same as
19478 // the type of the initializing value of the preceding enumerator
19479 // unless the incremented value is not representable in that type,
19480 // in which case the type is an unspecified integral type
19481 // sufficient to contain the incremented value. If no such type
19482 // exists, the program is ill-formed.
19483 QualType T = getNextLargerIntegralType(Context, EltTy);
19484 if (T.isNull() || Enum->isFixed()) {
19485 // There is no integral type larger enough to represent this
19486 // value. Complain, then allow the value to wrap around.
19487 EnumVal = LastEnumConst->getInitVal();
19488 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19489 ++EnumVal;
19490 if (Enum->isFixed())
19491 // When the underlying type is fixed, this is ill-formed.
19492 Diag(IdLoc, diag::err_enumerator_wrapped)
19493 << toString(EnumVal, 10)
19494 << EltTy;
19495 else
19496 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19497 << toString(EnumVal, 10);
19498 } else {
19499 EltTy = T;
19502 // Retrieve the last enumerator's value, extent that type to the
19503 // type that is supposed to be large enough to represent the incremented
19504 // value, then increment.
19505 EnumVal = LastEnumConst->getInitVal();
19506 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19507 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19508 ++EnumVal;
19510 // If we're not in C++, diagnose the overflow of enumerator values,
19511 // which in C99 means that the enumerator value is not representable in
19512 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19513 // permits enumerator values that are representable in some larger
19514 // integral type.
19515 if (!getLangOpts().CPlusPlus && !T.isNull())
19516 Diag(IdLoc, diag::warn_enum_value_overflow);
19517 } else if (!getLangOpts().CPlusPlus &&
19518 !EltTy->isDependentType() &&
19519 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19520 // Enforce C99 6.7.2.2p2 even when we compute the next value.
19521 Diag(IdLoc, diag::ext_enum_value_not_int)
19522 << toString(EnumVal, 10) << 1;
19527 if (!EltTy->isDependentType()) {
19528 // Make the enumerator value match the signedness and size of the
19529 // enumerator's type.
19530 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19531 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19534 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19535 Val, EnumVal);
19538 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
19539 SourceLocation IILoc) {
19540 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19541 !getLangOpts().CPlusPlus)
19542 return SkipBodyInfo();
19544 // We have an anonymous enum definition. Look up the first enumerator to
19545 // determine if we should merge the definition with an existing one and
19546 // skip the body.
19547 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19548 forRedeclarationInCurContext());
19549 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19550 if (!PrevECD)
19551 return SkipBodyInfo();
19553 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19554 NamedDecl *Hidden;
19555 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19556 SkipBodyInfo Skip;
19557 Skip.Previous = Hidden;
19558 return Skip;
19561 return SkipBodyInfo();
19564 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19565 SourceLocation IdLoc, IdentifierInfo *Id,
19566 const ParsedAttributesView &Attrs,
19567 SourceLocation EqualLoc, Expr *Val) {
19568 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19569 EnumConstantDecl *LastEnumConst =
19570 cast_or_null<EnumConstantDecl>(lastEnumConst);
19572 // The scope passed in may not be a decl scope. Zip up the scope tree until
19573 // we find one that is.
19574 S = getNonFieldDeclScope(S);
19576 // Verify that there isn't already something declared with this name in this
19577 // scope.
19578 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
19579 LookupName(R, S);
19580 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19582 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19583 // Maybe we will complain about the shadowed template parameter.
19584 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19585 // Just pretend that we didn't see the previous declaration.
19586 PrevDecl = nullptr;
19589 // C++ [class.mem]p15:
19590 // If T is the name of a class, then each of the following shall have a name
19591 // different from T:
19592 // - every enumerator of every member of class T that is an unscoped
19593 // enumerated type
19594 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19595 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
19596 DeclarationNameInfo(Id, IdLoc));
19598 EnumConstantDecl *New =
19599 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19600 if (!New)
19601 return nullptr;
19603 if (PrevDecl) {
19604 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19605 // Check for other kinds of shadowing not already handled.
19606 CheckShadow(New, PrevDecl, R);
19609 // When in C++, we may get a TagDecl with the same name; in this case the
19610 // enum constant will 'hide' the tag.
19611 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19612 "Received TagDecl when not in C++!");
19613 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19614 if (isa<EnumConstantDecl>(PrevDecl))
19615 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19616 else
19617 Diag(IdLoc, diag::err_redefinition) << Id;
19618 notePreviousDefinition(PrevDecl, IdLoc);
19619 return nullptr;
19623 // Process attributes.
19624 ProcessDeclAttributeList(S, New, Attrs);
19625 AddPragmaAttributes(S, New);
19627 // Register this decl in the current scope stack.
19628 New->setAccess(TheEnumDecl->getAccess());
19629 PushOnScopeChains(New, S);
19631 ActOnDocumentableDecl(New);
19633 return New;
19636 // Returns true when the enum initial expression does not trigger the
19637 // duplicate enum warning. A few common cases are exempted as follows:
19638 // Element2 = Element1
19639 // Element2 = Element1 + 1
19640 // Element2 = Element1 - 1
19641 // Where Element2 and Element1 are from the same enum.
19642 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
19643 Expr *InitExpr = ECD->getInitExpr();
19644 if (!InitExpr)
19645 return true;
19646 InitExpr = InitExpr->IgnoreImpCasts();
19648 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19649 if (!BO->isAdditiveOp())
19650 return true;
19651 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19652 if (!IL)
19653 return true;
19654 if (IL->getValue() != 1)
19655 return true;
19657 InitExpr = BO->getLHS();
19660 // This checks if the elements are from the same enum.
19661 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19662 if (!DRE)
19663 return true;
19665 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19666 if (!EnumConstant)
19667 return true;
19669 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19670 Enum)
19671 return true;
19673 return false;
19676 // Emits a warning when an element is implicitly set a value that
19677 // a previous element has already been set to.
19678 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
19679 EnumDecl *Enum, QualType EnumType) {
19680 // Avoid anonymous enums
19681 if (!Enum->getIdentifier())
19682 return;
19684 // Only check for small enums.
19685 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19686 return;
19688 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19689 return;
19691 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19692 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19694 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19696 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19697 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19699 // Use int64_t as a key to avoid needing special handling for map keys.
19700 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19701 llvm::APSInt Val = D->getInitVal();
19702 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19705 DuplicatesVector DupVector;
19706 ValueToVectorMap EnumMap;
19708 // Populate the EnumMap with all values represented by enum constants without
19709 // an initializer.
19710 for (auto *Element : Elements) {
19711 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19713 // Null EnumConstantDecl means a previous diagnostic has been emitted for
19714 // this constant. Skip this enum since it may be ill-formed.
19715 if (!ECD) {
19716 return;
19719 // Constants with initializers are handled in the next loop.
19720 if (ECD->getInitExpr())
19721 continue;
19723 // Duplicate values are handled in the next loop.
19724 EnumMap.insert({EnumConstantToKey(ECD), ECD});
19727 if (EnumMap.size() == 0)
19728 return;
19730 // Create vectors for any values that has duplicates.
19731 for (auto *Element : Elements) {
19732 // The last loop returned if any constant was null.
19733 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
19734 if (!ValidDuplicateEnum(ECD, Enum))
19735 continue;
19737 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19738 if (Iter == EnumMap.end())
19739 continue;
19741 DeclOrVector& Entry = Iter->second;
19742 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
19743 // Ensure constants are different.
19744 if (D == ECD)
19745 continue;
19747 // Create new vector and push values onto it.
19748 auto Vec = std::make_unique<ECDVector>();
19749 Vec->push_back(D);
19750 Vec->push_back(ECD);
19752 // Update entry to point to the duplicates vector.
19753 Entry = Vec.get();
19755 // Store the vector somewhere we can consult later for quick emission of
19756 // diagnostics.
19757 DupVector.emplace_back(std::move(Vec));
19758 continue;
19761 ECDVector *Vec = Entry.get<ECDVector*>();
19762 // Make sure constants are not added more than once.
19763 if (*Vec->begin() == ECD)
19764 continue;
19766 Vec->push_back(ECD);
19769 // Emit diagnostics.
19770 for (const auto &Vec : DupVector) {
19771 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
19773 // Emit warning for one enum constant.
19774 auto *FirstECD = Vec->front();
19775 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
19776 << FirstECD << toString(FirstECD->getInitVal(), 10)
19777 << FirstECD->getSourceRange();
19779 // Emit one note for each of the remaining enum constants with
19780 // the same value.
19781 for (auto *ECD : llvm::drop_begin(*Vec))
19782 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
19783 << ECD << toString(ECD->getInitVal(), 10)
19784 << ECD->getSourceRange();
19788 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
19789 bool AllowMask) const {
19790 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
19791 assert(ED->isCompleteDefinition() && "expected enum definition");
19793 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
19794 llvm::APInt &FlagBits = R.first->second;
19796 if (R.second) {
19797 for (auto *E : ED->enumerators()) {
19798 const auto &EVal = E->getInitVal();
19799 // Only single-bit enumerators introduce new flag values.
19800 if (EVal.isPowerOf2())
19801 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
19805 // A value is in a flag enum if either its bits are a subset of the enum's
19806 // flag bits (the first condition) or we are allowing masks and the same is
19807 // true of its complement (the second condition). When masks are allowed, we
19808 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
19810 // While it's true that any value could be used as a mask, the assumption is
19811 // that a mask will have all of the insignificant bits set. Anything else is
19812 // likely a logic error.
19813 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
19814 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
19817 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
19818 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
19819 const ParsedAttributesView &Attrs) {
19820 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
19821 QualType EnumType = Context.getTypeDeclType(Enum);
19823 ProcessDeclAttributeList(S, Enum, Attrs);
19825 if (Enum->isDependentType()) {
19826 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19827 EnumConstantDecl *ECD =
19828 cast_or_null<EnumConstantDecl>(Elements[i]);
19829 if (!ECD) continue;
19831 ECD->setType(EnumType);
19834 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
19835 return;
19838 // TODO: If the result value doesn't fit in an int, it must be a long or long
19839 // long value. ISO C does not support this, but GCC does as an extension,
19840 // emit a warning.
19841 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19842 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
19843 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
19845 // Verify that all the values are okay, compute the size of the values, and
19846 // reverse the list.
19847 unsigned NumNegativeBits = 0;
19848 unsigned NumPositiveBits = 0;
19850 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19851 EnumConstantDecl *ECD =
19852 cast_or_null<EnumConstantDecl>(Elements[i]);
19853 if (!ECD) continue; // Already issued a diagnostic.
19855 const llvm::APSInt &InitVal = ECD->getInitVal();
19857 // Keep track of the size of positive and negative values.
19858 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
19859 // If the enumerator is zero that should still be counted as a positive
19860 // bit since we need a bit to store the value zero.
19861 unsigned ActiveBits = InitVal.getActiveBits();
19862 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
19863 } else {
19864 NumNegativeBits =
19865 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
19869 // If we have an empty set of enumerators we still need one bit.
19870 // From [dcl.enum]p8
19871 // If the enumerator-list is empty, the values of the enumeration are as if
19872 // the enumeration had a single enumerator with value 0
19873 if (!NumPositiveBits && !NumNegativeBits)
19874 NumPositiveBits = 1;
19876 // Figure out the type that should be used for this enum.
19877 QualType BestType;
19878 unsigned BestWidth;
19880 // C++0x N3000 [conv.prom]p3:
19881 // An rvalue of an unscoped enumeration type whose underlying
19882 // type is not fixed can be converted to an rvalue of the first
19883 // of the following types that can represent all the values of
19884 // the enumeration: int, unsigned int, long int, unsigned long
19885 // int, long long int, or unsigned long long int.
19886 // C99 6.4.4.3p2:
19887 // An identifier declared as an enumeration constant has type int.
19888 // The C99 rule is modified by a gcc extension
19889 QualType BestPromotionType;
19891 bool Packed = Enum->hasAttr<PackedAttr>();
19892 // -fshort-enums is the equivalent to specifying the packed attribute on all
19893 // enum definitions.
19894 if (LangOpts.ShortEnums)
19895 Packed = true;
19897 // If the enum already has a type because it is fixed or dictated by the
19898 // target, promote that type instead of analyzing the enumerators.
19899 if (Enum->isComplete()) {
19900 BestType = Enum->getIntegerType();
19901 if (Context.isPromotableIntegerType(BestType))
19902 BestPromotionType = Context.getPromotedIntegerType(BestType);
19903 else
19904 BestPromotionType = BestType;
19906 BestWidth = Context.getIntWidth(BestType);
19908 else if (NumNegativeBits) {
19909 // If there is a negative value, figure out the smallest integer type (of
19910 // int/long/longlong) that fits.
19911 // If it's packed, check also if it fits a char or a short.
19912 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
19913 BestType = Context.SignedCharTy;
19914 BestWidth = CharWidth;
19915 } else if (Packed && NumNegativeBits <= ShortWidth &&
19916 NumPositiveBits < ShortWidth) {
19917 BestType = Context.ShortTy;
19918 BestWidth = ShortWidth;
19919 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
19920 BestType = Context.IntTy;
19921 BestWidth = IntWidth;
19922 } else {
19923 BestWidth = Context.getTargetInfo().getLongWidth();
19925 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
19926 BestType = Context.LongTy;
19927 } else {
19928 BestWidth = Context.getTargetInfo().getLongLongWidth();
19930 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
19931 Diag(Enum->getLocation(), diag::ext_enum_too_large);
19932 BestType = Context.LongLongTy;
19935 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
19936 } else {
19937 // If there is no negative value, figure out the smallest type that fits
19938 // all of the enumerator values.
19939 // If it's packed, check also if it fits a char or a short.
19940 if (Packed && NumPositiveBits <= CharWidth) {
19941 BestType = Context.UnsignedCharTy;
19942 BestPromotionType = Context.IntTy;
19943 BestWidth = CharWidth;
19944 } else if (Packed && NumPositiveBits <= ShortWidth) {
19945 BestType = Context.UnsignedShortTy;
19946 BestPromotionType = Context.IntTy;
19947 BestWidth = ShortWidth;
19948 } else if (NumPositiveBits <= IntWidth) {
19949 BestType = Context.UnsignedIntTy;
19950 BestWidth = IntWidth;
19951 BestPromotionType
19952 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19953 ? Context.UnsignedIntTy : Context.IntTy;
19954 } else if (NumPositiveBits <=
19955 (BestWidth = Context.getTargetInfo().getLongWidth())) {
19956 BestType = Context.UnsignedLongTy;
19957 BestPromotionType
19958 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19959 ? Context.UnsignedLongTy : Context.LongTy;
19960 } else {
19961 BestWidth = Context.getTargetInfo().getLongLongWidth();
19962 assert(NumPositiveBits <= BestWidth &&
19963 "How could an initializer get larger than ULL?");
19964 BestType = Context.UnsignedLongLongTy;
19965 BestPromotionType
19966 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19967 ? Context.UnsignedLongLongTy : Context.LongLongTy;
19971 // Loop over all of the enumerator constants, changing their types to match
19972 // the type of the enum if needed.
19973 for (auto *D : Elements) {
19974 auto *ECD = cast_or_null<EnumConstantDecl>(D);
19975 if (!ECD) continue; // Already issued a diagnostic.
19977 // Standard C says the enumerators have int type, but we allow, as an
19978 // extension, the enumerators to be larger than int size. If each
19979 // enumerator value fits in an int, type it as an int, otherwise type it the
19980 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
19981 // that X has type 'int', not 'unsigned'.
19983 // Determine whether the value fits into an int.
19984 llvm::APSInt InitVal = ECD->getInitVal();
19986 // If it fits into an integer type, force it. Otherwise force it to match
19987 // the enum decl type.
19988 QualType NewTy;
19989 unsigned NewWidth;
19990 bool NewSign;
19991 if (!getLangOpts().CPlusPlus &&
19992 !Enum->isFixed() &&
19993 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
19994 NewTy = Context.IntTy;
19995 NewWidth = IntWidth;
19996 NewSign = true;
19997 } else if (ECD->getType() == BestType) {
19998 // Already the right type!
19999 if (getLangOpts().CPlusPlus)
20000 // C++ [dcl.enum]p4: Following the closing brace of an
20001 // enum-specifier, each enumerator has the type of its
20002 // enumeration.
20003 ECD->setType(EnumType);
20004 continue;
20005 } else {
20006 NewTy = BestType;
20007 NewWidth = BestWidth;
20008 NewSign = BestType->isSignedIntegerOrEnumerationType();
20011 // Adjust the APSInt value.
20012 InitVal = InitVal.extOrTrunc(NewWidth);
20013 InitVal.setIsSigned(NewSign);
20014 ECD->setInitVal(InitVal);
20016 // Adjust the Expr initializer and type.
20017 if (ECD->getInitExpr() &&
20018 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20019 ECD->setInitExpr(ImplicitCastExpr::Create(
20020 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20021 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20022 if (getLangOpts().CPlusPlus)
20023 // C++ [dcl.enum]p4: Following the closing brace of an
20024 // enum-specifier, each enumerator has the type of its
20025 // enumeration.
20026 ECD->setType(EnumType);
20027 else
20028 ECD->setType(NewTy);
20031 Enum->completeDefinition(BestType, BestPromotionType,
20032 NumPositiveBits, NumNegativeBits);
20034 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20036 if (Enum->isClosedFlag()) {
20037 for (Decl *D : Elements) {
20038 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20039 if (!ECD) continue; // Already issued a diagnostic.
20041 llvm::APSInt InitVal = ECD->getInitVal();
20042 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20043 !IsValueInFlagEnum(Enum, InitVal, true))
20044 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20045 << ECD << Enum;
20049 // Now that the enum type is defined, ensure it's not been underaligned.
20050 if (Enum->hasAttrs())
20051 CheckAlignasUnderalignment(Enum);
20054 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
20055 SourceLocation StartLoc,
20056 SourceLocation EndLoc) {
20057 StringLiteral *AsmString = cast<StringLiteral>(expr);
20059 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
20060 AsmString, StartLoc,
20061 EndLoc);
20062 CurContext->addDecl(New);
20063 return New;
20066 Decl *Sema::ActOnTopLevelStmtDecl(Stmt *Statement) {
20067 auto *New = TopLevelStmtDecl::Create(Context, Statement);
20068 Context.getTranslationUnitDecl()->addDecl(New);
20069 return New;
20072 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
20073 IdentifierInfo* AliasName,
20074 SourceLocation PragmaLoc,
20075 SourceLocation NameLoc,
20076 SourceLocation AliasNameLoc) {
20077 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20078 LookupOrdinaryName);
20079 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20080 AttributeCommonInfo::Form::Pragma());
20081 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20082 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20084 // If a declaration that:
20085 // 1) declares a function or a variable
20086 // 2) has external linkage
20087 // already exists, add a label attribute to it.
20088 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20089 if (isDeclExternC(PrevDecl))
20090 PrevDecl->addAttr(Attr);
20091 else
20092 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20093 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20094 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20095 } else
20096 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20099 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
20100 SourceLocation PragmaLoc,
20101 SourceLocation NameLoc) {
20102 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20104 if (PrevDecl) {
20105 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20106 } else {
20107 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20111 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
20112 IdentifierInfo* AliasName,
20113 SourceLocation PragmaLoc,
20114 SourceLocation NameLoc,
20115 SourceLocation AliasNameLoc) {
20116 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20117 LookupOrdinaryName);
20118 WeakInfo W = WeakInfo(Name, NameLoc);
20120 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20121 if (!PrevDecl->hasAttr<AliasAttr>())
20122 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20123 DeclApplyPragmaWeak(TUScope, ND, W);
20124 } else {
20125 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20129 ObjCContainerDecl *Sema::getObjCDeclContext() const {
20130 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
20133 Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
20134 bool Final) {
20135 assert(FD && "Expected non-null FunctionDecl");
20137 // SYCL functions can be template, so we check if they have appropriate
20138 // attribute prior to checking if it is a template.
20139 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20140 return FunctionEmissionStatus::Emitted;
20142 // Templates are emitted when they're instantiated.
20143 if (FD->isDependentContext())
20144 return FunctionEmissionStatus::TemplateDiscarded;
20146 // Check whether this function is an externally visible definition.
20147 auto IsEmittedForExternalSymbol = [this, FD]() {
20148 // We have to check the GVA linkage of the function's *definition* -- if we
20149 // only have a declaration, we don't know whether or not the function will
20150 // be emitted, because (say) the definition could include "inline".
20151 const FunctionDecl *Def = FD->getDefinition();
20153 return Def && !isDiscardableGVALinkage(
20154 getASTContext().GetGVALinkageForFunction(Def));
20157 if (LangOpts.OpenMPIsTargetDevice) {
20158 // In OpenMP device mode we will not emit host only functions, or functions
20159 // we don't need due to their linkage.
20160 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20161 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20162 // DevTy may be changed later by
20163 // #pragma omp declare target to(*) device_type(*).
20164 // Therefore DevTy having no value does not imply host. The emission status
20165 // will be checked again at the end of compilation unit with Final = true.
20166 if (DevTy)
20167 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20168 return FunctionEmissionStatus::OMPDiscarded;
20169 // If we have an explicit value for the device type, or we are in a target
20170 // declare context, we need to emit all extern and used symbols.
20171 if (isInOpenMPDeclareTargetContext() || DevTy)
20172 if (IsEmittedForExternalSymbol())
20173 return FunctionEmissionStatus::Emitted;
20174 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20175 // we'll omit it.
20176 if (Final)
20177 return FunctionEmissionStatus::OMPDiscarded;
20178 } else if (LangOpts.OpenMP > 45) {
20179 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20180 // function. In 5.0, no_host was introduced which might cause a function to
20181 // be ommitted.
20182 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20183 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20184 if (DevTy)
20185 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20186 return FunctionEmissionStatus::OMPDiscarded;
20189 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20190 return FunctionEmissionStatus::Emitted;
20192 if (LangOpts.CUDA) {
20193 // When compiling for device, host functions are never emitted. Similarly,
20194 // when compiling for host, device and global functions are never emitted.
20195 // (Technically, we do emit a host-side stub for global functions, but this
20196 // doesn't count for our purposes here.)
20197 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
20198 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
20199 return FunctionEmissionStatus::CUDADiscarded;
20200 if (!LangOpts.CUDAIsDevice &&
20201 (T == Sema::CFT_Device || T == Sema::CFT_Global))
20202 return FunctionEmissionStatus::CUDADiscarded;
20204 if (IsEmittedForExternalSymbol())
20205 return FunctionEmissionStatus::Emitted;
20208 // Otherwise, the function is known-emitted if it's in our set of
20209 // known-emitted functions.
20210 return FunctionEmissionStatus::Unknown;
20213 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
20214 // Host-side references to a __global__ function refer to the stub, so the
20215 // function itself is never emitted and therefore should not be marked.
20216 // If we have host fn calls kernel fn calls host+device, the HD function
20217 // does not get instantiated on the host. We model this by omitting at the
20218 // call to the kernel from the callgraph. This ensures that, when compiling
20219 // for host, only HD functions actually called from the host get marked as
20220 // known-emitted.
20221 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20222 IdentifyCUDATarget(Callee) == CFT_Global;