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.
10//
11//===----------------------------------------------------------------------===//
12
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/Decl.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/EvaluatedExprVisitor.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/NonTrivialTypeVisitor.h"
28#include "clang/AST/Randstruct.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/Type.h"
31#include "clang/Basic/Builtins.h"
32#include "clang/Basic/HLSLRuntime.h"
33#include "clang/Basic/PartialDiagnostic.h"
34#include "clang/Basic/SourceManager.h"
35#include "clang/Basic/TargetInfo.h"
36#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
37#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
38#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
40#include "clang/Sema/CXXFieldCollector.h"
41#include "clang/Sema/DeclSpec.h"
42#include "clang/Sema/DelayedDiagnostic.h"
43#include "clang/Sema/Initialization.h"
44#include "clang/Sema/Lookup.h"
45#include "clang/Sema/ParsedTemplate.h"
46#include "clang/Sema/Scope.h"
47#include "clang/Sema/ScopeInfo.h"
48#include "clang/Sema/SemaCUDA.h"
49#include "clang/Sema/SemaHLSL.h"
50#include "clang/Sema/SemaInternal.h"
51#include "clang/Sema/SemaOpenMP.h"
52#include "clang/Sema/Template.h"
53#include "llvm/ADT/STLForwardCompat.h"
54#include "llvm/ADT/SmallString.h"
55#include "llvm/ADT/StringExtras.h"
56#include "llvm/TargetParser/Triple.h"
57#include <algorithm>
58#include <cstring>
59#include <functional>
60#include <optional>
61#include <unordered_map>
62
63using namespace clang;
64using namespace sema;
65
66Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
67 if (OwnedType) {
68 Decl *Group[2] = { OwnedType, Ptr };
69 return DeclGroupPtrTy::make(P: DeclGroupRef::Create(C&: Context, Decls: Group, NumDecls: 2));
70 }
71
72 return DeclGroupPtrTy::make(P: DeclGroupRef(Ptr));
73}
74
75namespace {
76
77class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
78 public:
79 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
80 bool AllowTemplates = false,
81 bool AllowNonTemplates = true)
82 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
83 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
84 WantExpressionKeywords = false;
85 WantCXXNamedCasts = false;
86 WantRemainingKeywords = false;
87 }
88
89 bool ValidateCandidate(const TypoCorrection &candidate) override {
90 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
91 if (!AllowInvalidDecl && ND->isInvalidDecl())
92 return false;
93
94 if (getAsTypeTemplateDecl(ND))
95 return AllowTemplates;
96
97 bool IsType = isa<TypeDecl>(Val: ND) || isa<ObjCInterfaceDecl>(Val: ND);
98 if (!IsType)
99 return false;
100
101 if (AllowNonTemplates)
102 return true;
103
104 // An injected-class-name of a class template (specialization) is valid
105 // as a template or as a non-template.
106 if (AllowTemplates) {
107 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
108 if (!RD || !RD->isInjectedClassName())
109 return false;
110 RD = cast<CXXRecordDecl>(RD->getDeclContext());
111 return RD->getDescribedClassTemplate() ||
112 isa<ClassTemplateSpecializationDecl>(Val: RD);
113 }
114
115 return false;
116 }
117
118 return !WantClassName && candidate.isKeyword();
119 }
120
121 std::unique_ptr<CorrectionCandidateCallback> clone() override {
122 return std::make_unique<TypeNameValidatorCCC>(args&: *this);
123 }
124
125 private:
126 bool AllowInvalidDecl;
127 bool WantClassName;
128 bool AllowTemplates;
129 bool AllowNonTemplates;
130};
131
132} // end anonymous namespace
133
134namespace {
135enum class UnqualifiedTypeNameLookupResult {
136 NotFound,
137 FoundNonType,
138 FoundType
139};
140} // end anonymous namespace
141
142/// Tries to perform unqualified lookup of the type decls in bases for
143/// dependent class.
144/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
145/// type decl, \a FoundType if only type decls are found.
146static UnqualifiedTypeNameLookupResult
147lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
148 SourceLocation NameLoc,
149 const CXXRecordDecl *RD) {
150 if (!RD->hasDefinition())
151 return UnqualifiedTypeNameLookupResult::NotFound;
152 // Look for type decls in base classes.
153 UnqualifiedTypeNameLookupResult FoundTypeDecl =
154 UnqualifiedTypeNameLookupResult::NotFound;
155 for (const auto &Base : RD->bases()) {
156 const CXXRecordDecl *BaseRD = nullptr;
157 if (auto *BaseTT = Base.getType()->getAs<TagType>())
158 BaseRD = BaseTT->getAsCXXRecordDecl();
159 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
160 // Look for type decls in dependent base classes that have known primary
161 // templates.
162 if (!TST || !TST->isDependentType())
163 continue;
164 auto *TD = TST->getTemplateName().getAsTemplateDecl();
165 if (!TD)
166 continue;
167 if (auto *BasePrimaryTemplate =
168 dyn_cast_or_null<CXXRecordDecl>(Val: TD->getTemplatedDecl())) {
169 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
170 BaseRD = BasePrimaryTemplate;
171 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: TD)) {
172 if (const ClassTemplatePartialSpecializationDecl *PS =
173 CTD->findPartialSpecialization(T: Base.getType()))
174 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
175 BaseRD = PS;
176 }
177 }
178 }
179 if (BaseRD) {
180 for (NamedDecl *ND : BaseRD->lookup(&II)) {
181 if (!isa<TypeDecl>(ND))
182 return UnqualifiedTypeNameLookupResult::FoundNonType;
183 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
184 }
185 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
186 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD: BaseRD)) {
187 case UnqualifiedTypeNameLookupResult::FoundNonType:
188 return UnqualifiedTypeNameLookupResult::FoundNonType;
189 case UnqualifiedTypeNameLookupResult::FoundType:
190 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
191 break;
192 case UnqualifiedTypeNameLookupResult::NotFound:
193 break;
194 }
195 }
196 }
197 }
198
199 return FoundTypeDecl;
200}
201
202static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
203 const IdentifierInfo &II,
204 SourceLocation NameLoc) {
205 // Lookup in the parent class template context, if any.
206 const CXXRecordDecl *RD = nullptr;
207 UnqualifiedTypeNameLookupResult FoundTypeDecl =
208 UnqualifiedTypeNameLookupResult::NotFound;
209 for (DeclContext *DC = S.CurContext;
210 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
211 DC = DC->getParent()) {
212 // Look for type decls in dependent base classes that have known primary
213 // templates.
214 RD = dyn_cast<CXXRecordDecl>(Val: DC);
215 if (RD && RD->getDescribedClassTemplate())
216 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
217 }
218 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
219 return nullptr;
220
221 // We found some types in dependent base classes. Recover as if the user
222 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
223 // lookup during template instantiation.
224 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
225
226 ASTContext &Context = S.Context;
227 auto *NNS = NestedNameSpecifier::Create(Context, Prefix: nullptr, Template: false,
228 T: cast<Type>(Val: Context.getRecordType(RD)));
229 QualType T =
230 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::Typename, NNS: NNS, Name: &II);
231
232 CXXScopeSpec SS;
233 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
234
235 TypeLocBuilder Builder;
236 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
237 DepTL.setNameLoc(NameLoc);
238 DepTL.setElaboratedKeywordLoc(SourceLocation());
239 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
240 return S.CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
241}
242
243/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
244static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T,
245 SourceLocation NameLoc,
246 bool WantNontrivialTypeSourceInfo = true) {
247 switch (T->getTypeClass()) {
248 case Type::DeducedTemplateSpecialization:
249 case Type::Enum:
250 case Type::InjectedClassName:
251 case Type::Record:
252 case Type::Typedef:
253 case Type::UnresolvedUsing:
254 case Type::Using:
255 break;
256 // These can never be qualified so an ElaboratedType node
257 // would carry no additional meaning.
258 case Type::ObjCInterface:
259 case Type::ObjCTypeParam:
260 case Type::TemplateTypeParm:
261 return ParsedType::make(P: T);
262 default:
263 llvm_unreachable("Unexpected Type Class");
264 }
265
266 if (!SS || SS->isEmpty())
267 return ParsedType::make(P: S.Context.getElaboratedType(
268 Keyword: ElaboratedTypeKeyword::None, NNS: nullptr, NamedType: T, OwnedTagDecl: nullptr));
269
270 QualType ElTy = S.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, SS: *SS, T);
271 if (!WantNontrivialTypeSourceInfo)
272 return ParsedType::make(P: ElTy);
273
274 TypeLocBuilder Builder;
275 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
276 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T: ElTy);
277 ElabTL.setElaboratedKeywordLoc(SourceLocation());
278 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context&: S.Context));
279 return S.CreateParsedType(T: ElTy, TInfo: Builder.getTypeSourceInfo(Context&: S.Context, T: ElTy));
280}
281
282/// If the identifier refers to a type name within this scope,
283/// return the declaration of that type.
284///
285/// This routine performs ordinary name lookup of the identifier II
286/// within the given scope, with optional C++ scope specifier SS, to
287/// determine whether the name refers to a type. If so, returns an
288/// opaque pointer (actually a QualType) corresponding to that
289/// type. Otherwise, returns NULL.
290ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
291 Scope *S, CXXScopeSpec *SS, bool isClassName,
292 bool HasTrailingDot, ParsedType ObjectTypePtr,
293 bool IsCtorOrDtorName,
294 bool WantNontrivialTypeSourceInfo,
295 bool IsClassTemplateDeductionContext,
296 ImplicitTypenameContext AllowImplicitTypename,
297 IdentifierInfo **CorrectedII) {
298 // FIXME: Consider allowing this outside C++1z mode as an extension.
299 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
300 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
301 !isClassName && !HasTrailingDot;
302
303 // Determine where we will perform name lookup.
304 DeclContext *LookupCtx = nullptr;
305 if (ObjectTypePtr) {
306 QualType ObjectType = ObjectTypePtr.get();
307 if (ObjectType->isRecordType())
308 LookupCtx = computeDeclContext(T: ObjectType);
309 } else if (SS && SS->isNotEmpty()) {
310 LookupCtx = computeDeclContext(SS: *SS, EnteringContext: false);
311
312 if (!LookupCtx) {
313 if (isDependentScopeSpecifier(SS: *SS)) {
314 // C++ [temp.res]p3:
315 // A qualified-id that refers to a type and in which the
316 // nested-name-specifier depends on a template-parameter (14.6.2)
317 // shall be prefixed by the keyword typename to indicate that the
318 // qualified-id denotes a type, forming an
319 // elaborated-type-specifier (7.1.5.3).
320 //
321 // We therefore do not perform any name lookup if the result would
322 // refer to a member of an unknown specialization.
323 // In C++2a, in several contexts a 'typename' is not required. Also
324 // allow this as an extension.
325 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
326 !isClassName && !IsCtorOrDtorName)
327 return nullptr;
328 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
329 if (IsImplicitTypename) {
330 SourceLocation QualifiedLoc = SS->getRange().getBegin();
331 if (getLangOpts().CPlusPlus20)
332 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
333 else
334 Diag(QualifiedLoc, diag::ext_implicit_typename)
335 << SS->getScopeRep() << II.getName()
336 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
337 }
338
339 // We know from the grammar that this name refers to a type,
340 // so build a dependent node to describe the type.
341 if (WantNontrivialTypeSourceInfo)
342 return ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II, IdLoc: NameLoc,
343 IsImplicitTypename: (ImplicitTypenameContext)IsImplicitTypename)
344 .get();
345
346 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
347 QualType T = CheckTypenameType(
348 Keyword: IsImplicitTypename ? ElaboratedTypeKeyword::Typename
349 : ElaboratedTypeKeyword::None,
350 KeywordLoc: SourceLocation(), QualifierLoc, II, IILoc: NameLoc);
351 return ParsedType::make(P: T);
352 }
353
354 return nullptr;
355 }
356
357 if (!LookupCtx->isDependentContext() &&
358 RequireCompleteDeclContext(SS&: *SS, DC: LookupCtx))
359 return nullptr;
360 }
361
362 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
363 // lookup for class-names.
364 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
365 LookupOrdinaryName;
366 LookupResult Result(*this, &II, NameLoc, Kind);
367 if (LookupCtx) {
368 // Perform "qualified" name lookup into the declaration context we
369 // computed, which is either the type of the base of a member access
370 // expression or the declaration context associated with a prior
371 // nested-name-specifier.
372 LookupQualifiedName(R&: Result, LookupCtx);
373
374 if (ObjectTypePtr && Result.empty()) {
375 // C++ [basic.lookup.classref]p3:
376 // If the unqualified-id is ~type-name, the type-name is looked up
377 // in the context of the entire postfix-expression. If the type T of
378 // the object expression is of a class type C, the type-name is also
379 // looked up in the scope of class C. At least one of the lookups shall
380 // find a name that refers to (possibly cv-qualified) T.
381 LookupName(R&: Result, S);
382 }
383 } else {
384 // Perform unqualified name lookup.
385 LookupName(R&: Result, S);
386
387 // For unqualified lookup in a class template in MSVC mode, look into
388 // dependent base classes where the primary class template is known.
389 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
390 if (ParsedType TypeInBase =
391 recoverFromTypeInKnownDependentBase(S&: *this, II, NameLoc))
392 return TypeInBase;
393 }
394 }
395
396 NamedDecl *IIDecl = nullptr;
397 UsingShadowDecl *FoundUsingShadow = nullptr;
398 switch (Result.getResultKind()) {
399 case LookupResult::NotFound:
400 if (CorrectedII) {
401 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
402 AllowDeducedTemplate);
403 TypoCorrection Correction = CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Kind,
404 S, SS, CCC, Mode: CTK_ErrorRecovery);
405 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
406 TemplateTy Template;
407 bool MemberOfUnknownSpecialization;
408 UnqualifiedId TemplateName;
409 TemplateName.setIdentifier(Id: NewII, IdLoc: NameLoc);
410 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
411 CXXScopeSpec NewSS, *NewSSPtr = SS;
412 if (SS && NNS) {
413 NewSS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
414 NewSSPtr = &NewSS;
415 }
416 if (Correction && (NNS || NewII != &II) &&
417 // Ignore a correction to a template type as the to-be-corrected
418 // identifier is not a template (typo correction for template names
419 // is handled elsewhere).
420 !(getLangOpts().CPlusPlus && NewSSPtr &&
421 isTemplateName(S, SS&: *NewSSPtr, hasTemplateKeyword: false, Name: TemplateName, ObjectType: nullptr, EnteringContext: false,
422 Template, MemberOfUnknownSpecialization))) {
423 ParsedType Ty = getTypeName(II: *NewII, NameLoc, S, SS: NewSSPtr,
424 isClassName, HasTrailingDot, ObjectTypePtr,
425 IsCtorOrDtorName,
426 WantNontrivialTypeSourceInfo,
427 IsClassTemplateDeductionContext);
428 if (Ty) {
429 diagnoseTypo(Correction,
430 PDiag(diag::err_unknown_type_or_class_name_suggest)
431 << Result.getLookupName() << isClassName);
432 if (SS && NNS)
433 SS->MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
434 *CorrectedII = NewII;
435 return Ty;
436 }
437 }
438 }
439 Result.suppressDiagnostics();
440 return nullptr;
441 case LookupResult::NotFoundInCurrentInstantiation:
442 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
443 QualType T = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
444 NNS: SS->getScopeRep(), Name: &II);
445 TypeLocBuilder TLB;
446 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T);
447 TL.setElaboratedKeywordLoc(SourceLocation());
448 TL.setQualifierLoc(SS->getWithLocInContext(Context));
449 TL.setNameLoc(NameLoc);
450 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
451 }
452 [[fallthrough]];
453 case LookupResult::FoundOverloaded:
454 case LookupResult::FoundUnresolvedValue:
455 Result.suppressDiagnostics();
456 return nullptr;
457
458 case LookupResult::Ambiguous:
459 // Recover from type-hiding ambiguities by hiding the type. We'll
460 // do the lookup again when looking for an object, and we can
461 // diagnose the error then. If we don't do this, then the error
462 // about hiding the type will be immediately followed by an error
463 // that only makes sense if the identifier was treated like a type.
464 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
465 Result.suppressDiagnostics();
466 return nullptr;
467 }
468
469 // Look to see if we have a type anywhere in the list of results.
470 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
471 Res != ResEnd; ++Res) {
472 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
473 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
474 Val: RealRes) ||
475 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
476 if (!IIDecl ||
477 // Make the selection of the recovery decl deterministic.
478 RealRes->getLocation() < IIDecl->getLocation()) {
479 IIDecl = RealRes;
480 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Res);
481 }
482 }
483 }
484
485 if (!IIDecl) {
486 // None of the entities we found is a type, so there is no way
487 // to even assume that the result is a type. In this case, don't
488 // complain about the ambiguity. The parser will either try to
489 // perform this lookup again (e.g., as an object name), which
490 // will produce the ambiguity, or will complain that it expected
491 // a type name.
492 Result.suppressDiagnostics();
493 return nullptr;
494 }
495
496 // We found a type within the ambiguous lookup; diagnose the
497 // ambiguity and then return that type. This might be the right
498 // answer, or it might not be, but it suppresses any attempt to
499 // perform the name lookup again.
500 break;
501
502 case LookupResult::Found:
503 IIDecl = Result.getFoundDecl();
504 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Result.begin());
505 break;
506 }
507
508 assert(IIDecl && "Didn't find decl");
509
510 QualType T;
511 if (TypeDecl *TD = dyn_cast<TypeDecl>(Val: IIDecl)) {
512 // C++ [class.qual]p2: A lookup that would find the injected-class-name
513 // instead names the constructors of the class, except when naming a class.
514 // This is ill-formed when we're not actually forming a ctor or dtor name.
515 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
516 auto *FoundRD = dyn_cast<CXXRecordDecl>(Val: TD);
517 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
518 FoundRD->isInjectedClassName() &&
519 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
520 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
521 << &II << /*Type*/1;
522
523 DiagnoseUseOfDecl(D: IIDecl, Locs: NameLoc);
524
525 T = Context.getTypeDeclType(Decl: TD);
526 MarkAnyDeclReferenced(Loc: TD->getLocation(), D: TD, /*OdrUse=*/MightBeOdrUse: false);
527 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(Val: IIDecl)) {
528 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
529 if (!HasTrailingDot)
530 T = Context.getObjCInterfaceType(Decl: IDecl);
531 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
532 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: IIDecl)) {
533 (void)DiagnoseUseOfDecl(UD, NameLoc);
534 // Recover with 'int'
535 return ParsedType::make(P: Context.IntTy);
536 } else if (AllowDeducedTemplate) {
537 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
538 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
539 TemplateName Template =
540 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
541 T = Context.getDeducedTemplateSpecializationType(Template, DeducedType: QualType(),
542 IsDependent: false);
543 // Don't wrap in a further UsingType.
544 FoundUsingShadow = nullptr;
545 }
546 }
547
548 if (T.isNull()) {
549 // If it's not plausibly a type, suppress diagnostics.
550 Result.suppressDiagnostics();
551 return nullptr;
552 }
553
554 if (FoundUsingShadow)
555 T = Context.getUsingType(Found: FoundUsingShadow, Underlying: T);
556
557 return buildNamedType(S&: *this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
558}
559
560// Builds a fake NNS for the given decl context.
561static NestedNameSpecifier *
562synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
563 for (;; DC = DC->getLookupParent()) {
564 DC = DC->getPrimaryContext();
565 auto *ND = dyn_cast<NamespaceDecl>(Val: DC);
566 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
567 return NestedNameSpecifier::Create(Context, Prefix: nullptr, NS: ND);
568 else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
569 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
570 RD->getTypeForDecl());
571 else if (isa<TranslationUnitDecl>(Val: DC))
572 return NestedNameSpecifier::GlobalSpecifier(Context);
573 }
574 llvm_unreachable("something isn't in TU scope?");
575}
576
577/// Find the parent class with dependent bases of the innermost enclosing method
578/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
579/// up allowing unqualified dependent type names at class-level, which MSVC
580/// correctly rejects.
581static const CXXRecordDecl *
582findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
583 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
584 DC = DC->getPrimaryContext();
585 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
586 if (MD->getParent()->hasAnyDependentBases())
587 return MD->getParent();
588 }
589 return nullptr;
590}
591
592ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
593 SourceLocation NameLoc,
594 bool IsTemplateTypeArg) {
595 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
596
597 NestedNameSpecifier *NNS = nullptr;
598 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
599 // If we weren't able to parse a default template argument, delay lookup
600 // until instantiation time by making a non-dependent DependentTypeName. We
601 // pretend we saw a NestedNameSpecifier referring to the current scope, and
602 // lookup is retried.
603 // FIXME: This hurts our diagnostic quality, since we get errors like "no
604 // type named 'Foo' in 'current_namespace'" when the user didn't write any
605 // name specifiers.
606 NNS = synthesizeCurrentNestedNameSpecifier(Context, DC: CurContext);
607 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
608 } else if (const CXXRecordDecl *RD =
609 findRecordWithDependentBasesOfEnclosingMethod(DC: CurContext)) {
610 // Build a DependentNameType that will perform lookup into RD at
611 // instantiation time.
612 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
613 RD->getTypeForDecl());
614
615 // Diagnose that this identifier was undeclared, and retry the lookup during
616 // template instantiation.
617 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
618 << RD;
619 } else {
620 // This is not a situation that we should recover from.
621 return ParsedType();
622 }
623
624 QualType T =
625 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
626
627 // Build type location information. We synthesized the qualifier, so we have
628 // to build a fake NestedNameSpecifierLoc.
629 NestedNameSpecifierLocBuilder NNSLocBuilder;
630 NNSLocBuilder.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
631 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
632
633 TypeLocBuilder Builder;
634 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
635 DepTL.setNameLoc(NameLoc);
636 DepTL.setElaboratedKeywordLoc(SourceLocation());
637 DepTL.setQualifierLoc(QualifierLoc);
638 return CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
639}
640
641/// isTagName() - This method is called *for error recovery purposes only*
642/// to determine if the specified name is a valid tag name ("struct foo"). If
643/// so, this returns the TST for the tag corresponding to it (TST_enum,
644/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
645/// cases in C where the user forgot to specify the tag.
646DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
647 // Do a tag name lookup in this scope.
648 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
649 LookupName(R, S, AllowBuiltinCreation: false);
650 R.suppressDiagnostics();
651 if (R.getResultKind() == LookupResult::Found)
652 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
653 switch (TD->getTagKind()) {
654 case TagTypeKind::Struct:
655 return DeclSpec::TST_struct;
656 case TagTypeKind::Interface:
657 return DeclSpec::TST_interface;
658 case TagTypeKind::Union:
659 return DeclSpec::TST_union;
660 case TagTypeKind::Class:
661 return DeclSpec::TST_class;
662 case TagTypeKind::Enum:
663 return DeclSpec::TST_enum;
664 }
665 }
666
667 return DeclSpec::TST_unspecified;
668}
669
670/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
671/// if a CXXScopeSpec's type is equal to the type of one of the base classes
672/// then downgrade the missing typename error to a warning.
673/// This is needed for MSVC compatibility; Example:
674/// @code
675/// template<class T> class A {
676/// public:
677/// typedef int TYPE;
678/// };
679/// template<class T> class B : public A<T> {
680/// public:
681/// A<T>::TYPE a; // no typename required because A<T> is a base class.
682/// };
683/// @endcode
684bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
685 if (CurContext->isRecord()) {
686 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
687 return true;
688
689 const Type *Ty = SS->getScopeRep()->getAsType();
690
691 CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: CurContext);
692 for (const auto &Base : RD->bases())
693 if (Ty && Context.hasSameUnqualifiedType(T1: QualType(Ty, 1), T2: Base.getType()))
694 return true;
695 return S->isFunctionPrototypeScope();
696 }
697 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
698}
699
700void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
701 SourceLocation IILoc,
702 Scope *S,
703 CXXScopeSpec *SS,
704 ParsedType &SuggestedType,
705 bool IsTemplateName) {
706 // Don't report typename errors for editor placeholders.
707 if (II->isEditorPlaceholder())
708 return;
709 // We don't have anything to suggest (yet).
710 SuggestedType = nullptr;
711
712 // There may have been a typo in the name of the type. Look up typo
713 // results, in case we have something that we can suggest.
714 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
715 /*AllowTemplates=*/IsTemplateName,
716 /*AllowNonTemplates=*/!IsTemplateName);
717 if (TypoCorrection Corrected =
718 CorrectTypo(Typo: DeclarationNameInfo(II, IILoc), LookupKind: LookupOrdinaryName, S, SS,
719 CCC, Mode: CTK_ErrorRecovery)) {
720 // FIXME: Support error recovery for the template-name case.
721 bool CanRecover = !IsTemplateName;
722 if (Corrected.isKeyword()) {
723 // We corrected to a keyword.
724 diagnoseTypo(Corrected,
725 PDiag(IsTemplateName ? diag::err_no_template_suggest
726 : diag::err_unknown_typename_suggest)
727 << II);
728 II = Corrected.getCorrectionAsIdentifierInfo();
729 } else {
730 // We found a similarly-named type or interface; suggest that.
731 if (!SS || !SS->isSet()) {
732 diagnoseTypo(Corrected,
733 PDiag(IsTemplateName ? diag::err_no_template_suggest
734 : diag::err_unknown_typename_suggest)
735 << II, CanRecover);
736 } else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false)) {
737 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
738 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
739 II->getName().equals(RHS: CorrectedStr);
740 diagnoseTypo(Corrected,
741 PDiag(IsTemplateName
742 ? diag::err_no_member_template_suggest
743 : diag::err_unknown_nested_typename_suggest)
744 << II << DC << DroppedSpecifier << SS->getRange(),
745 CanRecover);
746 } else {
747 llvm_unreachable("could not have corrected a typo here");
748 }
749
750 if (!CanRecover)
751 return;
752
753 CXXScopeSpec tmpSS;
754 if (Corrected.getCorrectionSpecifier())
755 tmpSS.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
756 R: SourceRange(IILoc));
757 // FIXME: Support class template argument deduction here.
758 SuggestedType =
759 getTypeName(II: *Corrected.getCorrectionAsIdentifierInfo(), NameLoc: IILoc, S,
760 SS: tmpSS.isSet() ? &tmpSS : SS, isClassName: false, HasTrailingDot: false, ObjectTypePtr: nullptr,
761 /*IsCtorOrDtorName=*/false,
762 /*WantNontrivialTypeSourceInfo=*/true);
763 }
764 return;
765 }
766
767 if (getLangOpts().CPlusPlus && !IsTemplateName) {
768 // See if II is a class template that the user forgot to pass arguments to.
769 UnqualifiedId Name;
770 Name.setIdentifier(Id: II, IdLoc: IILoc);
771 CXXScopeSpec EmptySS;
772 TemplateTy TemplateResult;
773 bool MemberOfUnknownSpecialization;
774 if (isTemplateName(S, SS&: SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
775 Name, ObjectType: nullptr, EnteringContext: true, Template&: TemplateResult,
776 MemberOfUnknownSpecialization) == TNK_Type_template) {
777 diagnoseMissingTemplateArguments(Name: TemplateResult.get(), Loc: IILoc);
778 return;
779 }
780 }
781
782 // FIXME: Should we move the logic that tries to recover from a missing tag
783 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
784
785 if (!SS || (!SS->isSet() && !SS->isInvalid()))
786 Diag(IILoc, IsTemplateName ? diag::err_no_template
787 : diag::err_unknown_typename)
788 << II;
789 else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false))
790 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
791 : diag::err_typename_nested_not_found)
792 << II << DC << SS->getRange();
793 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
794 SuggestedType =
795 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
796 } else if (isDependentScopeSpecifier(SS: *SS)) {
797 unsigned DiagID = diag::err_typename_missing;
798 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
799 DiagID = diag::ext_typename_missing;
800
801 Diag(SS->getRange().getBegin(), DiagID)
802 << SS->getScopeRep() << II->getName()
803 << SourceRange(SS->getRange().getBegin(), IILoc)
804 << FixItHint::CreateInsertion(InsertionLoc: SS->getRange().getBegin(), Code: "typename ");
805 SuggestedType = ActOnTypenameType(S, TypenameLoc: SourceLocation(),
806 SS: *SS, II: *II, IdLoc: IILoc).get();
807 } else {
808 assert(SS && SS->isInvalid() &&
809 "Invalid scope specifier has already been diagnosed");
810 }
811}
812
813/// Determine whether the given result set contains either a type name
814/// or
815static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
816 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
817 NextToken.is(K: tok::less);
818
819 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
820 if (isa<TypeDecl>(Val: *I) || isa<ObjCInterfaceDecl>(Val: *I))
821 return true;
822
823 if (CheckTemplate && isa<TemplateDecl>(Val: *I))
824 return true;
825 }
826
827 return false;
828}
829
830static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
831 Scope *S, CXXScopeSpec &SS,
832 IdentifierInfo *&Name,
833 SourceLocation NameLoc) {
834 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
835 SemaRef.LookupParsedName(R, S, SS: &SS);
836 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
837 StringRef FixItTagName;
838 switch (Tag->getTagKind()) {
839 case TagTypeKind::Class:
840 FixItTagName = "class ";
841 break;
842
843 case TagTypeKind::Enum:
844 FixItTagName = "enum ";
845 break;
846
847 case TagTypeKind::Struct:
848 FixItTagName = "struct ";
849 break;
850
851 case TagTypeKind::Interface:
852 FixItTagName = "__interface ";
853 break;
854
855 case TagTypeKind::Union:
856 FixItTagName = "union ";
857 break;
858 }
859
860 StringRef TagName = FixItTagName.drop_back();
861 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
862 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
863 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
864
865 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
866 I != IEnd; ++I)
867 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
868 << Name << TagName;
869
870 // Replace lookup results with just the tag decl.
871 Result.clear(Kind: Sema::LookupTagName);
872 SemaRef.LookupParsedName(R&: Result, S, SS: &SS);
873 return true;
874 }
875
876 return false;
877}
878
879Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
880 IdentifierInfo *&Name,
881 SourceLocation NameLoc,
882 const Token &NextToken,
883 CorrectionCandidateCallback *CCC) {
884 DeclarationNameInfo NameInfo(Name, NameLoc);
885 ObjCMethodDecl *CurMethod = getCurMethodDecl();
886
887 assert(NextToken.isNot(tok::coloncolon) &&
888 "parse nested name specifiers before calling ClassifyName");
889 if (getLangOpts().CPlusPlus && SS.isSet() &&
890 isCurrentClassName(II: *Name, S, SS: &SS)) {
891 // Per [class.qual]p2, this names the constructors of SS, not the
892 // injected-class-name. We don't have a classification for that.
893 // There's not much point caching this result, since the parser
894 // will reject it later.
895 return NameClassification::Unknown();
896 }
897
898 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
899 LookupParsedName(R&: Result, S, SS: &SS, AllowBuiltinCreation: !CurMethod);
900
901 if (SS.isInvalid())
902 return NameClassification::Error();
903
904 // For unqualified lookup in a class template in MSVC mode, look into
905 // dependent base classes where the primary class template is known.
906 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
907 if (ParsedType TypeInBase =
908 recoverFromTypeInKnownDependentBase(S&: *this, II: *Name, NameLoc))
909 return TypeInBase;
910 }
911
912 // Perform lookup for Objective-C instance variables (including automatically
913 // synthesized instance variables), if we're in an Objective-C method.
914 // FIXME: This lookup really, really needs to be folded in to the normal
915 // unqualified lookup mechanism.
916 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(R&: Result, NextToken)) {
917 DeclResult Ivar = LookupIvarInObjCMethod(Lookup&: Result, S, II: Name);
918 if (Ivar.isInvalid())
919 return NameClassification::Error();
920 if (Ivar.isUsable())
921 return NameClassification::NonType(D: cast<NamedDecl>(Val: Ivar.get()));
922
923 // We defer builtin creation until after ivar lookup inside ObjC methods.
924 if (Result.empty())
925 LookupBuiltin(R&: Result);
926 }
927
928 bool SecondTry = false;
929 bool IsFilteredTemplateName = false;
930
931Corrected:
932 switch (Result.getResultKind()) {
933 case LookupResult::NotFound:
934 // If an unqualified-id is followed by a '(', then we have a function
935 // call.
936 if (SS.isEmpty() && NextToken.is(K: tok::l_paren)) {
937 // In C++, this is an ADL-only call.
938 // FIXME: Reference?
939 if (getLangOpts().CPlusPlus)
940 return NameClassification::UndeclaredNonType();
941
942 // C90 6.3.2.2:
943 // If the expression that precedes the parenthesized argument list in a
944 // function call consists solely of an identifier, and if no
945 // declaration is visible for this identifier, the identifier is
946 // implicitly declared exactly as if, in the innermost block containing
947 // the function call, the declaration
948 //
949 // extern int identifier ();
950 //
951 // appeared.
952 //
953 // We also allow this in C99 as an extension. However, this is not
954 // allowed in all language modes as functions without prototypes may not
955 // be supported.
956 if (getLangOpts().implicitFunctionsAllowed()) {
957 if (NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *Name, S))
958 return NameClassification::NonType(D);
959 }
960 }
961
962 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(K: tok::less)) {
963 // In C++20 onwards, this could be an ADL-only call to a function
964 // template, and we're required to assume that this is a template name.
965 //
966 // FIXME: Find a way to still do typo correction in this case.
967 TemplateName Template =
968 Context.getAssumedTemplateName(Name: NameInfo.getName());
969 return NameClassification::UndeclaredTemplate(Name: Template);
970 }
971
972 // In C, we first see whether there is a tag type by the same name, in
973 // which case it's likely that the user just forgot to write "enum",
974 // "struct", or "union".
975 if (!getLangOpts().CPlusPlus && !SecondTry &&
976 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
977 break;
978 }
979
980 // Perform typo correction to determine if there is another name that is
981 // close to this name.
982 if (!SecondTry && CCC) {
983 SecondTry = true;
984 if (TypoCorrection Corrected =
985 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Result.getLookupKind(), S,
986 SS: &SS, CCC&: *CCC, Mode: CTK_ErrorRecovery)) {
987 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
988 unsigned QualifiedDiag = diag::err_no_member_suggest;
989
990 NamedDecl *FirstDecl = Corrected.getFoundDecl();
991 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
992 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
993 UnderlyingFirstDecl && isa<TemplateDecl>(Val: UnderlyingFirstDecl)) {
994 UnqualifiedDiag = diag::err_no_template_suggest;
995 QualifiedDiag = diag::err_no_member_template_suggest;
996 } else if (UnderlyingFirstDecl &&
997 (isa<TypeDecl>(Val: UnderlyingFirstDecl) ||
998 isa<ObjCInterfaceDecl>(Val: UnderlyingFirstDecl) ||
999 isa<ObjCCompatibleAliasDecl>(Val: UnderlyingFirstDecl))) {
1000 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1001 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1002 }
1003
1004 if (SS.isEmpty()) {
1005 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: UnqualifiedDiag) << Name);
1006 } else {// FIXME: is this even reachable? Test it.
1007 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
1008 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1009 Name->getName().equals(RHS: CorrectedStr);
1010 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: QualifiedDiag)
1011 << Name << computeDeclContext(SS, EnteringContext: false)
1012 << DroppedSpecifier << SS.getRange());
1013 }
1014
1015 // Update the name, so that the caller has the new name.
1016 Name = Corrected.getCorrectionAsIdentifierInfo();
1017
1018 // Typo correction corrected to a keyword.
1019 if (Corrected.isKeyword())
1020 return Name;
1021
1022 // Also update the LookupResult...
1023 // FIXME: This should probably go away at some point
1024 Result.clear();
1025 Result.setLookupName(Corrected.getCorrection());
1026 if (FirstDecl)
1027 Result.addDecl(D: FirstDecl);
1028
1029 // If we found an Objective-C instance variable, let
1030 // LookupInObjCMethod build the appropriate expression to
1031 // reference the ivar.
1032 // FIXME: This is a gross hack.
1033 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1034 DeclResult R =
1035 LookupIvarInObjCMethod(Lookup&: Result, S, II: Ivar->getIdentifier());
1036 if (R.isInvalid())
1037 return NameClassification::Error();
1038 if (R.isUsable())
1039 return NameClassification::NonType(Ivar);
1040 }
1041
1042 goto Corrected;
1043 }
1044 }
1045
1046 // We failed to correct; just fall through and let the parser deal with it.
1047 Result.suppressDiagnostics();
1048 return NameClassification::Unknown();
1049
1050 case LookupResult::NotFoundInCurrentInstantiation: {
1051 // We performed name lookup into the current instantiation, and there were
1052 // dependent bases, so we treat this result the same way as any other
1053 // dependent nested-name-specifier.
1054
1055 // C++ [temp.res]p2:
1056 // A name used in a template declaration or definition and that is
1057 // dependent on a template-parameter is assumed not to name a type
1058 // unless the applicable name lookup finds a type name or the name is
1059 // qualified by the keyword typename.
1060 //
1061 // FIXME: If the next token is '<', we might want to ask the parser to
1062 // perform some heroics to see if we actually have a
1063 // template-argument-list, which would indicate a missing 'template'
1064 // keyword here.
1065 return NameClassification::DependentNonType();
1066 }
1067
1068 case LookupResult::Found:
1069 case LookupResult::FoundOverloaded:
1070 case LookupResult::FoundUnresolvedValue:
1071 break;
1072
1073 case LookupResult::Ambiguous:
1074 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1075 hasAnyAcceptableTemplateNames(R&: Result, /*AllowFunctionTemplates=*/true,
1076 /*AllowDependent=*/false)) {
1077 // C++ [temp.local]p3:
1078 // A lookup that finds an injected-class-name (10.2) can result in an
1079 // ambiguity in certain cases (for example, if it is found in more than
1080 // one base class). If all of the injected-class-names that are found
1081 // refer to specializations of the same class template, and if the name
1082 // is followed by a template-argument-list, the reference refers to the
1083 // class template itself and not a specialization thereof, and is not
1084 // ambiguous.
1085 //
1086 // This filtering can make an ambiguous result into an unambiguous one,
1087 // so try again after filtering out template names.
1088 FilterAcceptableTemplateNames(R&: Result);
1089 if (!Result.isAmbiguous()) {
1090 IsFilteredTemplateName = true;
1091 break;
1092 }
1093 }
1094
1095 // Diagnose the ambiguity and return an error.
1096 return NameClassification::Error();
1097 }
1098
1099 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1100 (IsFilteredTemplateName ||
1101 hasAnyAcceptableTemplateNames(
1102 R&: Result, /*AllowFunctionTemplates=*/true,
1103 /*AllowDependent=*/false,
1104 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1105 getLangOpts().CPlusPlus20))) {
1106 // C++ [temp.names]p3:
1107 // After name lookup (3.4) finds that a name is a template-name or that
1108 // an operator-function-id or a literal- operator-id refers to a set of
1109 // overloaded functions any member of which is a function template if
1110 // this is followed by a <, the < is always taken as the delimiter of a
1111 // template-argument-list and never as the less-than operator.
1112 // C++2a [temp.names]p2:
1113 // A name is also considered to refer to a template if it is an
1114 // unqualified-id followed by a < and name lookup finds either one
1115 // or more functions or finds nothing.
1116 if (!IsFilteredTemplateName)
1117 FilterAcceptableTemplateNames(R&: Result);
1118
1119 bool IsFunctionTemplate;
1120 bool IsVarTemplate;
1121 TemplateName Template;
1122 if (Result.end() - Result.begin() > 1) {
1123 IsFunctionTemplate = true;
1124 Template = Context.getOverloadedTemplateName(Begin: Result.begin(),
1125 End: Result.end());
1126 } else if (!Result.empty()) {
1127 auto *TD = cast<TemplateDecl>(Val: getAsTemplateNameDecl(
1128 D: *Result.begin(), /*AllowFunctionTemplates=*/true,
1129 /*AllowDependent=*/false));
1130 IsFunctionTemplate = isa<FunctionTemplateDecl>(Val: TD);
1131 IsVarTemplate = isa<VarTemplateDecl>(Val: TD);
1132
1133 UsingShadowDecl *FoundUsingShadow =
1134 dyn_cast<UsingShadowDecl>(Val: *Result.begin());
1135 assert(!FoundUsingShadow ||
1136 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1137 Template =
1138 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1139 if (SS.isNotEmpty())
1140 Template = Context.getQualifiedTemplateName(NNS: SS.getScopeRep(),
1141 /*TemplateKeyword=*/false,
1142 Template);
1143 } else {
1144 // All results were non-template functions. This is a function template
1145 // name.
1146 IsFunctionTemplate = true;
1147 Template = Context.getAssumedTemplateName(Name: NameInfo.getName());
1148 }
1149
1150 if (IsFunctionTemplate) {
1151 // Function templates always go through overload resolution, at which
1152 // point we'll perform the various checks (e.g., accessibility) we need
1153 // to based on which function we selected.
1154 Result.suppressDiagnostics();
1155
1156 return NameClassification::FunctionTemplate(Name: Template);
1157 }
1158
1159 return IsVarTemplate ? NameClassification::VarTemplate(Name: Template)
1160 : NameClassification::TypeTemplate(Name: Template);
1161 }
1162
1163 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1164 QualType T = Context.getTypeDeclType(Decl: Type);
1165 if (const auto *USD = dyn_cast<UsingShadowDecl>(Val: Found))
1166 T = Context.getUsingType(Found: USD, Underlying: T);
1167 return buildNamedType(S&: *this, SS: &SS, T, NameLoc);
1168 };
1169
1170 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1171 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: FirstDecl)) {
1172 DiagnoseUseOfDecl(Type, NameLoc);
1173 MarkAnyDeclReferenced(Loc: Type->getLocation(), D: Type, /*OdrUse=*/MightBeOdrUse: false);
1174 return BuildTypeFor(Type, *Result.begin());
1175 }
1176
1177 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Val: FirstDecl);
1178 if (!Class) {
1179 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1180 if (ObjCCompatibleAliasDecl *Alias =
1181 dyn_cast<ObjCCompatibleAliasDecl>(Val: FirstDecl))
1182 Class = Alias->getClassInterface();
1183 }
1184
1185 if (Class) {
1186 DiagnoseUseOfDecl(Class, NameLoc);
1187
1188 if (NextToken.is(K: tok::period)) {
1189 // Interface. <something> is parsed as a property reference expression.
1190 // Just return "unknown" as a fall-through for now.
1191 Result.suppressDiagnostics();
1192 return NameClassification::Unknown();
1193 }
1194
1195 QualType T = Context.getObjCInterfaceType(Decl: Class);
1196 return ParsedType::make(P: T);
1197 }
1198
1199 if (isa<ConceptDecl>(Val: FirstDecl)) {
1200 // We want to preserve the UsingShadowDecl for concepts.
1201 if (auto *USD = dyn_cast<UsingShadowDecl>(Val: Result.getRepresentativeDecl()))
1202 return NameClassification::Concept(Name: TemplateName(USD));
1203 return NameClassification::Concept(
1204 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1205 }
1206
1207 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: FirstDecl)) {
1208 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1209 return NameClassification::Error();
1210 }
1211
1212 // We can have a type template here if we're classifying a template argument.
1213 if (isa<TemplateDecl>(Val: FirstDecl) && !isa<FunctionTemplateDecl>(Val: FirstDecl) &&
1214 !isa<VarTemplateDecl>(Val: FirstDecl))
1215 return NameClassification::TypeTemplate(
1216 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1217
1218 // Check for a tag type hidden by a non-type decl in a few cases where it
1219 // seems likely a type is wanted instead of the non-type that was found.
1220 bool NextIsOp = NextToken.isOneOf(K1: tok::amp, K2: tok::star);
1221 if ((NextToken.is(K: tok::identifier) ||
1222 (NextIsOp &&
1223 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1224 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1225 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1226 DiagnoseUseOfDecl(Type, NameLoc);
1227 return BuildTypeFor(Type, *Result.begin());
1228 }
1229
1230 // If we already know which single declaration is referenced, just annotate
1231 // that declaration directly. Defer resolving even non-overloaded class
1232 // member accesses, as we need to defer certain access checks until we know
1233 // the context.
1234 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1235 if (Result.isSingleResult() && !ADL &&
1236 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(Val: FirstDecl)))
1237 return NameClassification::NonType(D: Result.getRepresentativeDecl());
1238
1239 // Otherwise, this is an overload set that we will need to resolve later.
1240 Result.suppressDiagnostics();
1241 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1242 Context, NamingClass: Result.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
1243 NameInfo: Result.getLookupNameInfo(), RequiresADL: ADL, Begin: Result.begin(), End: Result.end(),
1244 /*KnownDependent=*/false));
1245}
1246
1247ExprResult
1248Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1249 SourceLocation NameLoc) {
1250 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1251 CXXScopeSpec SS;
1252 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1253 return BuildDeclarationNameExpr(SS, R&: Result, /*ADL=*/NeedsADL: true);
1254}
1255
1256ExprResult
1257Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1258 IdentifierInfo *Name,
1259 SourceLocation NameLoc,
1260 bool IsAddressOfOperand) {
1261 DeclarationNameInfo NameInfo(Name, NameLoc);
1262 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1263 NameInfo, isAddressOfOperand: IsAddressOfOperand,
1264 /*TemplateArgs=*/nullptr);
1265}
1266
1267ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1268 NamedDecl *Found,
1269 SourceLocation NameLoc,
1270 const Token &NextToken) {
1271 if (getCurMethodDecl() && SS.isEmpty())
1272 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Val: Found->getUnderlyingDecl()))
1273 return BuildIvarRefExpr(S, Loc: NameLoc, IV: Ivar);
1274
1275 // Reconstruct the lookup result.
1276 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1277 Result.addDecl(D: Found);
1278 Result.resolveKind();
1279
1280 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1281 return BuildDeclarationNameExpr(SS, R&: Result, NeedsADL: ADL, /*AcceptInvalidDecl=*/true);
1282}
1283
1284ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1285 // For an implicit class member access, transform the result into a member
1286 // access expression if necessary.
1287 auto *ULE = cast<UnresolvedLookupExpr>(Val: E);
1288 if ((*ULE->decls_begin())->isCXXClassMember()) {
1289 CXXScopeSpec SS;
1290 SS.Adopt(Other: ULE->getQualifierLoc());
1291
1292 // Reconstruct the lookup result.
1293 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1294 LookupOrdinaryName);
1295 Result.setNamingClass(ULE->getNamingClass());
1296 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1297 Result.addDecl(*I, I.getAccess());
1298 Result.resolveKind();
1299 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc: SourceLocation(), R&: Result,
1300 TemplateArgs: nullptr, S);
1301 }
1302
1303 // Otherwise, this is already in the form we needed, and no further checks
1304 // are necessary.
1305 return ULE;
1306}
1307
1308Sema::TemplateNameKindForDiagnostics
1309Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1310 auto *TD = Name.getAsTemplateDecl();
1311 if (!TD)
1312 return TemplateNameKindForDiagnostics::DependentTemplate;
1313 if (isa<ClassTemplateDecl>(Val: TD))
1314 return TemplateNameKindForDiagnostics::ClassTemplate;
1315 if (isa<FunctionTemplateDecl>(Val: TD))
1316 return TemplateNameKindForDiagnostics::FunctionTemplate;
1317 if (isa<VarTemplateDecl>(Val: TD))
1318 return TemplateNameKindForDiagnostics::VarTemplate;
1319 if (isa<TypeAliasTemplateDecl>(Val: TD))
1320 return TemplateNameKindForDiagnostics::AliasTemplate;
1321 if (isa<TemplateTemplateParmDecl>(Val: TD))
1322 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1323 if (isa<ConceptDecl>(Val: TD))
1324 return TemplateNameKindForDiagnostics::Concept;
1325 return TemplateNameKindForDiagnostics::DependentTemplate;
1326}
1327
1328void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1329 assert(DC->getLexicalParent() == CurContext &&
1330 "The next DeclContext should be lexically contained in the current one.");
1331 CurContext = DC;
1332 S->setEntity(DC);
1333}
1334
1335void Sema::PopDeclContext() {
1336 assert(CurContext && "DeclContext imbalance!");
1337
1338 CurContext = CurContext->getLexicalParent();
1339 assert(CurContext && "Popped translation unit!");
1340}
1341
1342Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1343 Decl *D) {
1344 // Unlike PushDeclContext, the context to which we return is not necessarily
1345 // the containing DC of TD, because the new context will be some pre-existing
1346 // TagDecl definition instead of a fresh one.
1347 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1348 CurContext = cast<TagDecl>(Val: D)->getDefinition();
1349 assert(CurContext && "skipping definition of undefined tag");
1350 // Start lookups from the parent of the current context; we don't want to look
1351 // into the pre-existing complete definition.
1352 S->setEntity(CurContext->getLookupParent());
1353 return Result;
1354}
1355
1356void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1357 CurContext = static_cast<decltype(CurContext)>(Context);
1358}
1359
1360/// EnterDeclaratorContext - Used when we must lookup names in the context
1361/// of a declarator's nested name specifier.
1362///
1363void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1364 // C++0x [basic.lookup.unqual]p13:
1365 // A name used in the definition of a static data member of class
1366 // X (after the qualified-id of the static member) is looked up as
1367 // if the name was used in a member function of X.
1368 // C++0x [basic.lookup.unqual]p14:
1369 // If a variable member of a namespace is defined outside of the
1370 // scope of its namespace then any name used in the definition of
1371 // the variable member (after the declarator-id) is looked up as
1372 // if the definition of the variable member occurred in its
1373 // namespace.
1374 // Both of these imply that we should push a scope whose context
1375 // is the semantic context of the declaration. We can't use
1376 // PushDeclContext here because that context is not necessarily
1377 // lexically contained in the current context. Fortunately,
1378 // the containing scope should have the appropriate information.
1379
1380 assert(!S->getEntity() && "scope already has entity");
1381
1382#ifndef NDEBUG
1383 Scope *Ancestor = S->getParent();
1384 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1385 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1386#endif
1387
1388 CurContext = DC;
1389 S->setEntity(DC);
1390
1391 if (S->getParent()->isTemplateParamScope()) {
1392 // Also set the corresponding entities for all immediately-enclosing
1393 // template parameter scopes.
1394 EnterTemplatedContext(S: S->getParent(), DC);
1395 }
1396}
1397
1398void Sema::ExitDeclaratorContext(Scope *S) {
1399 assert(S->getEntity() == CurContext && "Context imbalance!");
1400
1401 // Switch back to the lexical context. The safety of this is
1402 // enforced by an assert in EnterDeclaratorContext.
1403 Scope *Ancestor = S->getParent();
1404 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1405 CurContext = Ancestor->getEntity();
1406
1407 // We don't need to do anything with the scope, which is going to
1408 // disappear.
1409}
1410
1411void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1412 assert(S->isTemplateParamScope() &&
1413 "expected to be initializing a template parameter scope");
1414
1415 // C++20 [temp.local]p7:
1416 // In the definition of a member of a class template that appears outside
1417 // of the class template definition, the name of a member of the class
1418 // template hides the name of a template-parameter of any enclosing class
1419 // templates (but not a template-parameter of the member if the member is a
1420 // class or function template).
1421 // C++20 [temp.local]p9:
1422 // In the definition of a class template or in the definition of a member
1423 // of such a template that appears outside of the template definition, for
1424 // each non-dependent base class (13.8.2.1), if the name of the base class
1425 // or the name of a member of the base class is the same as the name of a
1426 // template-parameter, the base class name or member name hides the
1427 // template-parameter name (6.4.10).
1428 //
1429 // This means that a template parameter scope should be searched immediately
1430 // after searching the DeclContext for which it is a template parameter
1431 // scope. For example, for
1432 // template<typename T> template<typename U> template<typename V>
1433 // void N::A<T>::B<U>::f(...)
1434 // we search V then B<U> (and base classes) then U then A<T> (and base
1435 // classes) then T then N then ::.
1436 unsigned ScopeDepth = getTemplateDepth(S);
1437 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1438 DeclContext *SearchDCAfterScope = DC;
1439 for (; DC; DC = DC->getLookupParent()) {
1440 if (const TemplateParameterList *TPL =
1441 cast<Decl>(Val: DC)->getDescribedTemplateParams()) {
1442 unsigned DCDepth = TPL->getDepth() + 1;
1443 if (DCDepth > ScopeDepth)
1444 continue;
1445 if (ScopeDepth == DCDepth)
1446 SearchDCAfterScope = DC = DC->getLookupParent();
1447 break;
1448 }
1449 }
1450 S->setLookupEntity(SearchDCAfterScope);
1451 }
1452}
1453
1454void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1455 // We assume that the caller has already called
1456 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1457 FunctionDecl *FD = D->getAsFunction();
1458 if (!FD)
1459 return;
1460
1461 // Same implementation as PushDeclContext, but enters the context
1462 // from the lexical parent, rather than the top-level class.
1463 assert(CurContext == FD->getLexicalParent() &&
1464 "The next DeclContext should be lexically contained in the current one.");
1465 CurContext = FD;
1466 S->setEntity(CurContext);
1467
1468 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1469 ParmVarDecl *Param = FD->getParamDecl(i: P);
1470 // If the parameter has an identifier, then add it to the scope
1471 if (Param->getIdentifier()) {
1472 S->AddDecl(Param);
1473 IdResolver.AddDecl(Param);
1474 }
1475 }
1476}
1477
1478void Sema::ActOnExitFunctionContext() {
1479 // Same implementation as PopDeclContext, but returns to the lexical parent,
1480 // rather than the top-level class.
1481 assert(CurContext && "DeclContext imbalance!");
1482 CurContext = CurContext->getLexicalParent();
1483 assert(CurContext && "Popped translation unit!");
1484}
1485
1486/// Determine whether overloading is allowed for a new function
1487/// declaration considering prior declarations of the same name.
1488///
1489/// This routine determines whether overloading is possible, not
1490/// whether a new declaration actually overloads a previous one.
1491/// It will return true in C++ (where overloads are alway permitted)
1492/// or, as a C extension, when either the new declaration or a
1493/// previous one is declared with the 'overloadable' attribute.
1494static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1495 ASTContext &Context,
1496 const FunctionDecl *New) {
1497 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1498 return true;
1499
1500 // Multiversion function declarations are not overloads in the
1501 // usual sense of that term, but lookup will report that an
1502 // overload set was found if more than one multiversion function
1503 // declaration is present for the same name. It is therefore
1504 // inadequate to assume that some prior declaration(s) had
1505 // the overloadable attribute; checking is required. Since one
1506 // declaration is permitted to omit the attribute, it is necessary
1507 // to check at least two; hence the 'any_of' check below. Note that
1508 // the overloadable attribute is implicitly added to declarations
1509 // that were required to have it but did not.
1510 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1511 return llvm::any_of(Range: Previous, P: [](const NamedDecl *ND) {
1512 return ND->hasAttr<OverloadableAttr>();
1513 });
1514 } else if (Previous.getResultKind() == LookupResult::Found)
1515 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1516
1517 return false;
1518}
1519
1520/// Add this decl to the scope shadowed decl chains.
1521void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1522 // Move up the scope chain until we find the nearest enclosing
1523 // non-transparent context. The declaration will be introduced into this
1524 // scope.
1525 while (S->getEntity() && S->getEntity()->isTransparentContext())
1526 S = S->getParent();
1527
1528 // Add scoped declarations into their context, so that they can be
1529 // found later. Declarations without a context won't be inserted
1530 // into any context.
1531 if (AddToContext)
1532 CurContext->addDecl(D);
1533
1534 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1535 // are function-local declarations.
1536 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1537 return;
1538
1539 // Template instantiations should also not be pushed into scope.
1540 if (isa<FunctionDecl>(Val: D) &&
1541 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization())
1542 return;
1543
1544 if (isa<UsingEnumDecl>(Val: D) && D->getDeclName().isEmpty()) {
1545 S->AddDecl(D);
1546 return;
1547 }
1548 // If this replaces anything in the current scope,
1549 IdentifierResolver::iterator I = IdResolver.begin(Name: D->getDeclName()),
1550 IEnd = IdResolver.end();
1551 for (; I != IEnd; ++I) {
1552 if (S->isDeclScope(*I) && D->declarationReplaces(OldD: *I)) {
1553 S->RemoveDecl(*I);
1554 IdResolver.RemoveDecl(D: *I);
1555
1556 // Should only need to replace one decl.
1557 break;
1558 }
1559 }
1560
1561 S->AddDecl(D);
1562
1563 if (isa<LabelDecl>(Val: D) && !cast<LabelDecl>(Val: D)->isGnuLocal()) {
1564 // Implicitly-generated labels may end up getting generated in an order that
1565 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1566 // the label at the appropriate place in the identifier chain.
1567 for (I = IdResolver.begin(Name: D->getDeclName()); I != IEnd; ++I) {
1568 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1569 if (IDC == CurContext) {
1570 if (!S->isDeclScope(*I))
1571 continue;
1572 } else if (IDC->Encloses(DC: CurContext))
1573 break;
1574 }
1575
1576 IdResolver.InsertDeclAfter(Pos: I, D);
1577 } else {
1578 IdResolver.AddDecl(D);
1579 }
1580 warnOnReservedIdentifier(D);
1581}
1582
1583bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1584 bool AllowInlineNamespace) const {
1585 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1586}
1587
1588Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1589 DeclContext *TargetDC = DC->getPrimaryContext();
1590 do {
1591 if (DeclContext *ScopeDC = S->getEntity())
1592 if (ScopeDC->getPrimaryContext() == TargetDC)
1593 return S;
1594 } while ((S = S->getParent()));
1595
1596 return nullptr;
1597}
1598
1599static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1600 DeclContext*,
1601 ASTContext&);
1602
1603/// Filters out lookup results that don't fall within the given scope
1604/// as determined by isDeclInScope.
1605void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1606 bool ConsiderLinkage,
1607 bool AllowInlineNamespace) {
1608 LookupResult::Filter F = R.makeFilter();
1609 while (F.hasNext()) {
1610 NamedDecl *D = F.next();
1611
1612 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1613 continue;
1614
1615 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1616 continue;
1617
1618 F.erase();
1619 }
1620
1621 F.done();
1622}
1623
1624/// We've determined that \p New is a redeclaration of \p Old. Check that they
1625/// have compatible owning modules.
1626bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1627 // [module.interface]p7:
1628 // A declaration is attached to a module as follows:
1629 // - If the declaration is a non-dependent friend declaration that nominates a
1630 // function with a declarator-id that is a qualified-id or template-id or that
1631 // nominates a class other than with an elaborated-type-specifier with neither
1632 // a nested-name-specifier nor a simple-template-id, it is attached to the
1633 // module to which the friend is attached ([basic.link]).
1634 if (New->getFriendObjectKind() &&
1635 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1636 New->setLocalOwningModule(Old->getOwningModule());
1637 makeMergedDefinitionVisible(ND: New);
1638 return false;
1639 }
1640
1641 Module *NewM = New->getOwningModule();
1642 Module *OldM = Old->getOwningModule();
1643
1644 if (NewM && NewM->isPrivateModule())
1645 NewM = NewM->Parent;
1646 if (OldM && OldM->isPrivateModule())
1647 OldM = OldM->Parent;
1648
1649 if (NewM == OldM)
1650 return false;
1651
1652 if (NewM && OldM) {
1653 // A module implementation unit has visibility of the decls in its
1654 // implicitly imported interface.
1655 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1656 return false;
1657
1658 // Partitions are part of the module, but a partition could import another
1659 // module, so verify that the PMIs agree.
1660 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1661 NewM->getPrimaryModuleInterfaceName() ==
1662 OldM->getPrimaryModuleInterfaceName())
1663 return false;
1664 }
1665
1666 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1667 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1668 if (NewIsModuleInterface || OldIsModuleInterface) {
1669 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1670 // if a declaration of D [...] appears in the purview of a module, all
1671 // other such declarations shall appear in the purview of the same module
1672 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1673 << New
1674 << NewIsModuleInterface
1675 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1676 << OldIsModuleInterface
1677 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1678 Diag(Old->getLocation(), diag::note_previous_declaration);
1679 New->setInvalidDecl();
1680 return true;
1681 }
1682
1683 return false;
1684}
1685
1686// [module.interface]p6:
1687// A redeclaration of an entity X is implicitly exported if X was introduced by
1688// an exported declaration; otherwise it shall not be exported.
1689bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1690 // [module.interface]p1:
1691 // An export-declaration shall inhabit a namespace scope.
1692 //
1693 // So it is meaningless to talk about redeclaration which is not at namespace
1694 // scope.
1695 if (!New->getLexicalDeclContext()
1696 ->getNonTransparentContext()
1697 ->isFileContext() ||
1698 !Old->getLexicalDeclContext()
1699 ->getNonTransparentContext()
1700 ->isFileContext())
1701 return false;
1702
1703 bool IsNewExported = New->isInExportDeclContext();
1704 bool IsOldExported = Old->isInExportDeclContext();
1705
1706 // It should be irrevelant if both of them are not exported.
1707 if (!IsNewExported && !IsOldExported)
1708 return false;
1709
1710 if (IsOldExported)
1711 return false;
1712
1713 assert(IsNewExported);
1714
1715 auto Lk = Old->getFormalLinkage();
1716 int S = 0;
1717 if (Lk == Linkage::Internal)
1718 S = 1;
1719 else if (Lk == Linkage::Module)
1720 S = 2;
1721 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1722 Diag(Old->getLocation(), diag::note_previous_declaration);
1723 return true;
1724}
1725
1726// A wrapper function for checking the semantic restrictions of
1727// a redeclaration within a module.
1728bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1729 if (CheckRedeclarationModuleOwnership(New, Old))
1730 return true;
1731
1732 if (CheckRedeclarationExported(New, Old))
1733 return true;
1734
1735 return false;
1736}
1737
1738// Check the redefinition in C++20 Modules.
1739//
1740// [basic.def.odr]p14:
1741// For any definable item D with definitions in multiple translation units,
1742// - if D is a non-inline non-templated function or variable, or
1743// - if the definitions in different translation units do not satisfy the
1744// following requirements,
1745// the program is ill-formed; a diagnostic is required only if the definable
1746// item is attached to a named module and a prior definition is reachable at
1747// the point where a later definition occurs.
1748// - Each such definition shall not be attached to a named module
1749// ([module.unit]).
1750// - Each such definition shall consist of the same sequence of tokens, ...
1751// ...
1752//
1753// Return true if the redefinition is not allowed. Return false otherwise.
1754bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1755 const NamedDecl *Old) const {
1756 assert(getASTContext().isSameEntity(New, Old) &&
1757 "New and Old are not the same definition, we should diagnostic it "
1758 "immediately instead of checking it.");
1759 assert(const_cast<Sema *>(this)->isReachable(New) &&
1760 const_cast<Sema *>(this)->isReachable(Old) &&
1761 "We shouldn't see unreachable definitions here.");
1762
1763 Module *NewM = New->getOwningModule();
1764 Module *OldM = Old->getOwningModule();
1765
1766 // We only checks for named modules here. The header like modules is skipped.
1767 // FIXME: This is not right if we import the header like modules in the module
1768 // purview.
1769 //
1770 // For example, assuming "header.h" provides definition for `D`.
1771 // ```C++
1772 // //--- M.cppm
1773 // export module M;
1774 // import "header.h"; // or #include "header.h" but import it by clang modules
1775 // actually.
1776 //
1777 // //--- Use.cpp
1778 // import M;
1779 // import "header.h"; // or uses clang modules.
1780 // ```
1781 //
1782 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1783 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1784 // reject it. But the current implementation couldn't detect the case since we
1785 // don't record the information about the importee modules.
1786 //
1787 // But this might not be painful in practice. Since the design of C++20 Named
1788 // Modules suggests us to use headers in global module fragment instead of
1789 // module purview.
1790 if (NewM && NewM->isHeaderLikeModule())
1791 NewM = nullptr;
1792 if (OldM && OldM->isHeaderLikeModule())
1793 OldM = nullptr;
1794
1795 if (!NewM && !OldM)
1796 return true;
1797
1798 // [basic.def.odr]p14.3
1799 // Each such definition shall not be attached to a named module
1800 // ([module.unit]).
1801 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1802 return true;
1803
1804 // Then New and Old lives in the same TU if their share one same module unit.
1805 if (NewM)
1806 NewM = NewM->getTopLevelModule();
1807 if (OldM)
1808 OldM = OldM->getTopLevelModule();
1809 return OldM == NewM;
1810}
1811
1812static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1813 if (D->getDeclContext()->isFileContext())
1814 return false;
1815
1816 return isa<UsingShadowDecl>(Val: D) ||
1817 isa<UnresolvedUsingTypenameDecl>(Val: D) ||
1818 isa<UnresolvedUsingValueDecl>(Val: D);
1819}
1820
1821/// Removes using shadow declarations not at class scope from the lookup
1822/// results.
1823static void RemoveUsingDecls(LookupResult &R) {
1824 LookupResult::Filter F = R.makeFilter();
1825 while (F.hasNext())
1826 if (isUsingDeclNotAtClassScope(D: F.next()))
1827 F.erase();
1828
1829 F.done();
1830}
1831
1832/// Check for this common pattern:
1833/// @code
1834/// class S {
1835/// S(const S&); // DO NOT IMPLEMENT
1836/// void operator=(const S&); // DO NOT IMPLEMENT
1837/// };
1838/// @endcode
1839static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1840 // FIXME: Should check for private access too but access is set after we get
1841 // the decl here.
1842 if (D->doesThisDeclarationHaveABody())
1843 return false;
1844
1845 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: D))
1846 return CD->isCopyConstructor();
1847 return D->isCopyAssignmentOperator();
1848}
1849
1850// We need this to handle
1851//
1852// typedef struct {
1853// void *foo() { return 0; }
1854// } A;
1855//
1856// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1857// for example. If 'A', foo will have external linkage. If we have '*A',
1858// foo will have no linkage. Since we can't know until we get to the end
1859// of the typedef, this function finds out if D might have non-external linkage.
1860// Callers should verify at the end of the TU if it D has external linkage or
1861// not.
1862bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1863 const DeclContext *DC = D->getDeclContext();
1864 while (!DC->isTranslationUnit()) {
1865 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Val: DC)){
1866 if (!RD->hasNameForLinkage())
1867 return true;
1868 }
1869 DC = DC->getParent();
1870 }
1871
1872 return !D->isExternallyVisible();
1873}
1874
1875// FIXME: This needs to be refactored; some other isInMainFile users want
1876// these semantics.
1877static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1878 if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1879 return false;
1880 return S.SourceMgr.isInMainFile(Loc);
1881}
1882
1883bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1884 assert(D);
1885
1886 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1887 return false;
1888
1889 // Ignore all entities declared within templates, and out-of-line definitions
1890 // of members of class templates.
1891 if (D->getDeclContext()->isDependentContext() ||
1892 D->getLexicalDeclContext()->isDependentContext())
1893 return false;
1894
1895 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1896 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1897 return false;
1898 // A non-out-of-line declaration of a member specialization was implicitly
1899 // instantiated; it's the out-of-line declaration that we're interested in.
1900 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1901 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1902 return false;
1903
1904 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
1905 if (MD->isVirtual() || IsDisallowedCopyOrAssign(D: MD))
1906 return false;
1907 } else {
1908 // 'static inline' functions are defined in headers; don't warn.
1909 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1910 return false;
1911 }
1912
1913 if (FD->doesThisDeclarationHaveABody() &&
1914 Context.DeclMustBeEmitted(FD))
1915 return false;
1916 } else if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1917 // Constants and utility variables are defined in headers with internal
1918 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1919 // like "inline".)
1920 if (!isMainFileLoc(*this, VD->getLocation()))
1921 return false;
1922
1923 if (Context.DeclMustBeEmitted(VD))
1924 return false;
1925
1926 if (VD->isStaticDataMember() &&
1927 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1928 return false;
1929 if (VD->isStaticDataMember() &&
1930 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1931 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1932 return false;
1933
1934 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1935 return false;
1936 } else {
1937 return false;
1938 }
1939
1940 // Only warn for unused decls internal to the translation unit.
1941 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1942 // for inline functions defined in the main source file, for instance.
1943 return mightHaveNonExternalLinkage(D);
1944}
1945
1946void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1947 if (!D)
1948 return;
1949
1950 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1951 const FunctionDecl *First = FD->getFirstDecl();
1952 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1953 return; // First should already be in the vector.
1954 }
1955
1956 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1957 const VarDecl *First = VD->getFirstDecl();
1958 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1959 return; // First should already be in the vector.
1960 }
1961
1962 if (ShouldWarnIfUnusedFileScopedDecl(D))
1963 UnusedFileScopedDecls.push_back(LocalValue: D);
1964}
1965
1966static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1967 const NamedDecl *D) {
1968 if (D->isInvalidDecl())
1969 return false;
1970
1971 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: D)) {
1972 // For a decomposition declaration, warn if none of the bindings are
1973 // referenced, instead of if the variable itself is referenced (which
1974 // it is, by the bindings' expressions).
1975 bool IsAllPlaceholders = true;
1976 for (const auto *BD : DD->bindings()) {
1977 if (BD->isReferenced())
1978 return false;
1979 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
1980 }
1981 if (IsAllPlaceholders)
1982 return false;
1983 } else if (!D->getDeclName()) {
1984 return false;
1985 } else if (D->isReferenced() || D->isUsed()) {
1986 return false;
1987 }
1988
1989 if (D->isPlaceholderVar(LangOpts))
1990 return false;
1991
1992 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1993 D->hasAttr<CleanupAttr>())
1994 return false;
1995
1996 if (isa<LabelDecl>(Val: D))
1997 return true;
1998
1999 // Except for labels, we only care about unused decls that are local to
2000 // functions.
2001 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2002 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2003 // For dependent types, the diagnostic is deferred.
2004 WithinFunction =
2005 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2006 if (!WithinFunction)
2007 return false;
2008
2009 if (isa<TypedefNameDecl>(Val: D))
2010 return true;
2011
2012 // White-list anything that isn't a local variable.
2013 if (!isa<VarDecl>(Val: D) || isa<ParmVarDecl>(Val: D) || isa<ImplicitParamDecl>(Val: D))
2014 return false;
2015
2016 // Types of valid local variables should be complete, so this should succeed.
2017 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2018
2019 const Expr *Init = VD->getInit();
2020 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Val: Init))
2021 Init = Cleanups->getSubExpr();
2022
2023 const auto *Ty = VD->getType().getTypePtr();
2024
2025 // Only look at the outermost level of typedef.
2026 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2027 // Allow anything marked with __attribute__((unused)).
2028 if (TT->getDecl()->hasAttr<UnusedAttr>())
2029 return false;
2030 }
2031
2032 // Warn for reference variables whose initializtion performs lifetime
2033 // extension.
2034 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Val: Init);
2035 MTE && MTE->getExtendingDecl()) {
2036 Ty = VD->getType().getNonReferenceType().getTypePtr();
2037 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2038 }
2039
2040 // If we failed to complete the type for some reason, or if the type is
2041 // dependent, don't diagnose the variable.
2042 if (Ty->isIncompleteType() || Ty->isDependentType())
2043 return false;
2044
2045 // Look at the element type to ensure that the warning behaviour is
2046 // consistent for both scalars and arrays.
2047 Ty = Ty->getBaseElementTypeUnsafe();
2048
2049 if (const TagType *TT = Ty->getAs<TagType>()) {
2050 const TagDecl *Tag = TT->getDecl();
2051 if (Tag->hasAttr<UnusedAttr>())
2052 return false;
2053
2054 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2055 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2056 return false;
2057
2058 if (Init) {
2059 const auto *Construct =
2060 dyn_cast<CXXConstructExpr>(Val: Init->IgnoreImpCasts());
2061 if (Construct && !Construct->isElidable()) {
2062 const CXXConstructorDecl *CD = Construct->getConstructor();
2063 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2064 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2065 return false;
2066 }
2067
2068 // Suppress the warning if we don't know how this is constructed, and
2069 // it could possibly be non-trivial constructor.
2070 if (Init->isTypeDependent()) {
2071 for (const CXXConstructorDecl *Ctor : RD->ctors())
2072 if (!Ctor->isTrivial())
2073 return false;
2074 }
2075
2076 // Suppress the warning if the constructor is unresolved because
2077 // its arguments are dependent.
2078 if (isa<CXXUnresolvedConstructExpr>(Val: Init))
2079 return false;
2080 }
2081 }
2082 }
2083
2084 // TODO: __attribute__((unused)) templates?
2085 }
2086
2087 return true;
2088}
2089
2090static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2091 FixItHint &Hint) {
2092 if (isa<LabelDecl>(Val: D)) {
2093 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2094 loc: D->getEndLoc(), TKind: tok::colon, SM: Ctx.getSourceManager(), LangOpts: Ctx.getLangOpts(),
2095 /*SkipTrailingWhitespaceAndNewline=*/SkipTrailingWhitespaceAndNewLine: false);
2096 if (AfterColon.isInvalid())
2097 return;
2098 Hint = FixItHint::CreateRemoval(
2099 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2100 }
2101}
2102
2103void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2104 DiagnoseUnusedNestedTypedefs(
2105 D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2106}
2107
2108void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2109 DiagReceiverTy DiagReceiver) {
2110 if (D->getTypeForDecl()->isDependentType())
2111 return;
2112
2113 for (auto *TmpD : D->decls()) {
2114 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2115 DiagnoseUnusedDecl(T, DiagReceiver);
2116 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2117 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2118 }
2119}
2120
2121void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2122 DiagnoseUnusedDecl(
2123 ND: D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2124}
2125
2126/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2127/// unless they are marked attr(unused).
2128void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2129 if (!ShouldDiagnoseUnusedDecl(LangOpts: getLangOpts(), D))
2130 return;
2131
2132 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
2133 // typedefs can be referenced later on, so the diagnostics are emitted
2134 // at end-of-translation-unit.
2135 UnusedLocalTypedefNameCandidates.insert(X: TD);
2136 return;
2137 }
2138
2139 FixItHint Hint;
2140 GenerateFixForUnusedDecl(D, Ctx&: Context, Hint);
2141
2142 unsigned DiagID;
2143 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2144 DiagID = diag::warn_unused_exception_param;
2145 else if (isa<LabelDecl>(D))
2146 DiagID = diag::warn_unused_label;
2147 else
2148 DiagID = diag::warn_unused_variable;
2149
2150 SourceLocation DiagLoc = D->getLocation();
2151 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2152}
2153
2154void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2155 DiagReceiverTy DiagReceiver) {
2156 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2157 // it's not really unused.
2158 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2159 return;
2160
2161 // In C++, `_` variables behave as if they were maybe_unused
2162 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2163 return;
2164
2165 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2166
2167 if (Ty->isReferenceType() || Ty->isDependentType())
2168 return;
2169
2170 if (const TagType *TT = Ty->getAs<TagType>()) {
2171 const TagDecl *Tag = TT->getDecl();
2172 if (Tag->hasAttr<UnusedAttr>())
2173 return;
2174 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2175 // mimic gcc's behavior.
2176 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag);
2177 RD && !RD->hasAttr<WarnUnusedAttr>())
2178 return;
2179 }
2180
2181 // Don't warn about __block Objective-C pointer variables, as they might
2182 // be assigned in the block but not used elsewhere for the purpose of lifetime
2183 // extension.
2184 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2185 return;
2186
2187 // Don't warn about Objective-C pointer variables with precise lifetime
2188 // semantics; they can be used to ensure ARC releases the object at a known
2189 // time, which may mean assignment but no other references.
2190 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2191 return;
2192
2193 auto iter = RefsMinusAssignments.find(Val: VD);
2194 if (iter == RefsMinusAssignments.end())
2195 return;
2196
2197 assert(iter->getSecond() >= 0 &&
2198 "Found a negative number of references to a VarDecl");
2199 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2200 // Assume the given VarDecl is "used" if its ref count stored in
2201 // `RefMinusAssignments` is positive, with one exception.
2202 //
2203 // For a C++ variable whose decl (with initializer) entirely consist the
2204 // condition expression of a if/while/for construct,
2205 // Clang creates a DeclRefExpr for the condition expression rather than a
2206 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2207 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2208 // used in the body of the if/while/for construct.
2209 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2210 if (!UnusedCXXCondDecl)
2211 return;
2212 }
2213
2214 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2215 : diag::warn_unused_but_set_variable;
2216 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2217}
2218
2219static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2220 Sema::DiagReceiverTy DiagReceiver) {
2221 // Verify that we have no forward references left. If so, there was a goto
2222 // or address of a label taken, but no definition of it. Label fwd
2223 // definitions are indicated with a null substmt which is also not a resolved
2224 // MS inline assembly label name.
2225 bool Diagnose = false;
2226 if (L->isMSAsmLabel())
2227 Diagnose = !L->isResolvedMSAsmLabel();
2228 else
2229 Diagnose = L->getStmt() == nullptr;
2230 if (Diagnose)
2231 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2232 << L);
2233}
2234
2235void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2236 S->applyNRVO();
2237
2238 if (S->decl_empty()) return;
2239 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2240 "Scope shouldn't contain decls!");
2241
2242 /// We visit the decls in non-deterministic order, but we want diagnostics
2243 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2244 /// and sort the diagnostics before emitting them, after we visited all decls.
2245 struct LocAndDiag {
2246 SourceLocation Loc;
2247 std::optional<SourceLocation> PreviousDeclLoc;
2248 PartialDiagnostic PD;
2249 };
2250 SmallVector<LocAndDiag, 16> DeclDiags;
2251 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2252 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: std::nullopt, .PD: std::move(PD)});
2253 };
2254 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2255 SourceLocation PreviousDeclLoc,
2256 PartialDiagnostic PD) {
2257 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: PreviousDeclLoc, .PD: std::move(PD)});
2258 };
2259
2260 for (auto *TmpD : S->decls()) {
2261 assert(TmpD && "This decl didn't get pushed??");
2262
2263 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2264 NamedDecl *D = cast<NamedDecl>(Val: TmpD);
2265
2266 // Diagnose unused variables in this scope.
2267 if (!S->hasUnrecoverableErrorOccurred()) {
2268 DiagnoseUnusedDecl(D, DiagReceiver: addDiag);
2269 if (const auto *RD = dyn_cast<RecordDecl>(Val: D))
2270 DiagnoseUnusedNestedTypedefs(D: RD, DiagReceiver: addDiag);
2271 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2272 DiagnoseUnusedButSetDecl(VD, DiagReceiver: addDiag);
2273 RefsMinusAssignments.erase(Val: VD);
2274 }
2275 }
2276
2277 if (!D->getDeclName()) continue;
2278
2279 // If this was a forward reference to a label, verify it was defined.
2280 if (LabelDecl *LD = dyn_cast<LabelDecl>(Val: D))
2281 CheckPoppedLabel(L: LD, S&: *this, DiagReceiver: addDiag);
2282
2283 // Remove this name from our lexical scope, and warn on it if we haven't
2284 // already.
2285 IdResolver.RemoveDecl(D);
2286 auto ShadowI = ShadowingDecls.find(Val: D);
2287 if (ShadowI != ShadowingDecls.end()) {
2288 if (const auto *FD = dyn_cast<FieldDecl>(Val: ShadowI->second)) {
2289 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2290 PDiag(diag::warn_ctor_parm_shadows_field)
2291 << D << FD << FD->getParent());
2292 }
2293 ShadowingDecls.erase(I: ShadowI);
2294 }
2295 }
2296
2297 llvm::sort(C&: DeclDiags,
2298 Comp: [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2299 // The particular order for diagnostics is not important, as long
2300 // as the order is deterministic. Using the raw location is going
2301 // to generally be in source order unless there are macro
2302 // expansions involved.
2303 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2304 });
2305 for (const LocAndDiag &D : DeclDiags) {
2306 Diag(D.Loc, D.PD);
2307 if (D.PreviousDeclLoc)
2308 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2309 }
2310}
2311
2312/// Look for an Objective-C class in the translation unit.
2313///
2314/// \param Id The name of the Objective-C class we're looking for. If
2315/// typo-correction fixes this name, the Id will be updated
2316/// to the fixed name.
2317///
2318/// \param IdLoc The location of the name in the translation unit.
2319///
2320/// \param DoTypoCorrection If true, this routine will attempt typo correction
2321/// if there is no class with the given name.
2322///
2323/// \returns The declaration of the named Objective-C class, or NULL if the
2324/// class could not be found.
2325ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(const IdentifierInfo *&Id,
2326 SourceLocation IdLoc,
2327 bool DoTypoCorrection) {
2328 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2329 // creation from this context.
2330 NamedDecl *IDecl = LookupSingleName(S: TUScope, Name: Id, Loc: IdLoc, NameKind: LookupOrdinaryName);
2331
2332 if (!IDecl && DoTypoCorrection) {
2333 // Perform typo correction at the given location, but only if we
2334 // find an Objective-C class name.
2335 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2336 if (TypoCorrection C =
2337 CorrectTypo(Typo: DeclarationNameInfo(Id, IdLoc), LookupKind: LookupOrdinaryName,
2338 S: TUScope, SS: nullptr, CCC, Mode: CTK_ErrorRecovery)) {
2339 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2340 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2341 Id = IDecl->getIdentifier();
2342 }
2343 }
2344 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(Val: IDecl);
2345 // This routine must always return a class definition, if any.
2346 if (Def && Def->getDefinition())
2347 Def = Def->getDefinition();
2348 return Def;
2349}
2350
2351/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2352/// from S, where a non-field would be declared. This routine copes
2353/// with the difference between C and C++ scoping rules in structs and
2354/// unions. For example, the following code is well-formed in C but
2355/// ill-formed in C++:
2356/// @code
2357/// struct S6 {
2358/// enum { BAR } e;
2359/// };
2360///
2361/// void test_S6() {
2362/// struct S6 a;
2363/// a.e = BAR;
2364/// }
2365/// @endcode
2366/// For the declaration of BAR, this routine will return a different
2367/// scope. The scope S will be the scope of the unnamed enumeration
2368/// within S6. In C++, this routine will return the scope associated
2369/// with S6, because the enumeration's scope is a transparent
2370/// context but structures can contain non-field names. In C, this
2371/// routine will return the translation unit scope, since the
2372/// enumeration's scope is a transparent context and structures cannot
2373/// contain non-field names.
2374Scope *Sema::getNonFieldDeclScope(Scope *S) {
2375 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2376 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2377 (S->isClassScope() && !getLangOpts().CPlusPlus))
2378 S = S->getParent();
2379 return S;
2380}
2381
2382static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2383 ASTContext::GetBuiltinTypeError Error) {
2384 switch (Error) {
2385 case ASTContext::GE_None:
2386 return "";
2387 case ASTContext::GE_Missing_type:
2388 return BuiltinInfo.getHeaderName(ID);
2389 case ASTContext::GE_Missing_stdio:
2390 return "stdio.h";
2391 case ASTContext::GE_Missing_setjmp:
2392 return "setjmp.h";
2393 case ASTContext::GE_Missing_ucontext:
2394 return "ucontext.h";
2395 }
2396 llvm_unreachable("unhandled error kind");
2397}
2398
2399FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2400 unsigned ID, SourceLocation Loc) {
2401 DeclContext *Parent = Context.getTranslationUnitDecl();
2402
2403 if (getLangOpts().CPlusPlus) {
2404 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2405 C&: Context, DC: Parent, ExternLoc: Loc, LangLoc: Loc, Lang: LinkageSpecLanguageIDs::C, HasBraces: false);
2406 CLinkageDecl->setImplicit();
2407 Parent->addDecl(CLinkageDecl);
2408 Parent = CLinkageDecl;
2409 }
2410
2411 FunctionDecl *New = FunctionDecl::Create(C&: Context, DC: Parent, StartLoc: Loc, NLoc: Loc, N: II, T: Type,
2412 /*TInfo=*/nullptr, SC: SC_Extern,
2413 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
2414 isInlineSpecified: false, hasWrittenPrototype: Type->isFunctionProtoType());
2415 New->setImplicit();
2416 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2417
2418 // Create Decl objects for each parameter, adding them to the
2419 // FunctionDecl.
2420 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: Type)) {
2421 SmallVector<ParmVarDecl *, 16> Params;
2422 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2423 ParmVarDecl *parm = ParmVarDecl::Create(
2424 Context, New, SourceLocation(), SourceLocation(), nullptr,
2425 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2426 parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
2427 Params.push_back(Elt: parm);
2428 }
2429 New->setParams(Params);
2430 }
2431
2432 AddKnownFunctionAttributes(FD: New);
2433 return New;
2434}
2435
2436/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2437/// file scope. lazily create a decl for it. ForRedeclaration is true
2438/// if we're creating this built-in in anticipation of redeclaring the
2439/// built-in.
2440NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2441 Scope *S, bool ForRedeclaration,
2442 SourceLocation Loc) {
2443 LookupNecessaryTypesForBuiltin(S, ID);
2444
2445 ASTContext::GetBuiltinTypeError Error;
2446 QualType R = Context.GetBuiltinType(ID, Error);
2447 if (Error) {
2448 if (!ForRedeclaration)
2449 return nullptr;
2450
2451 // If we have a builtin without an associated type we should not emit a
2452 // warning when we were not able to find a type for it.
2453 if (Error == ASTContext::GE_Missing_type ||
2454 Context.BuiltinInfo.allowTypeMismatch(ID))
2455 return nullptr;
2456
2457 // If we could not find a type for setjmp it is because the jmp_buf type was
2458 // not defined prior to the setjmp declaration.
2459 if (Error == ASTContext::GE_Missing_setjmp) {
2460 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2461 << Context.BuiltinInfo.getName(ID);
2462 return nullptr;
2463 }
2464
2465 // Generally, we emit a warning that the declaration requires the
2466 // appropriate header.
2467 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2468 << getHeaderName(Context.BuiltinInfo, ID, Error)
2469 << Context.BuiltinInfo.getName(ID);
2470 return nullptr;
2471 }
2472
2473 if (!ForRedeclaration &&
2474 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2475 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2476 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2477 : diag::ext_implicit_lib_function_decl)
2478 << Context.BuiltinInfo.getName(ID) << R;
2479 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2480 Diag(Loc, diag::note_include_header_or_declare)
2481 << Header << Context.BuiltinInfo.getName(ID);
2482 }
2483
2484 if (R.isNull())
2485 return nullptr;
2486
2487 FunctionDecl *New = CreateBuiltin(II, Type: R, ID, Loc);
2488 RegisterLocallyScopedExternCDecl(New, S);
2489
2490 // TUScope is the translation-unit scope to insert this function into.
2491 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2492 // relate Scopes to DeclContexts, and probably eliminate CurContext
2493 // entirely, but we're not there yet.
2494 DeclContext *SavedContext = CurContext;
2495 CurContext = New->getDeclContext();
2496 PushOnScopeChains(New, TUScope);
2497 CurContext = SavedContext;
2498 return New;
2499}
2500
2501/// Typedef declarations don't have linkage, but they still denote the same
2502/// entity if their types are the same.
2503/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2504/// isSameEntity.
2505static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2506 TypedefNameDecl *Decl,
2507 LookupResult &Previous) {
2508 // This is only interesting when modules are enabled.
2509 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2510 return;
2511
2512 // Empty sets are uninteresting.
2513 if (Previous.empty())
2514 return;
2515
2516 LookupResult::Filter Filter = Previous.makeFilter();
2517 while (Filter.hasNext()) {
2518 NamedDecl *Old = Filter.next();
2519
2520 // Non-hidden declarations are never ignored.
2521 if (S.isVisible(D: Old))
2522 continue;
2523
2524 // Declarations of the same entity are not ignored, even if they have
2525 // different linkages.
2526 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2527 if (S.Context.hasSameType(T1: OldTD->getUnderlyingType(),
2528 T2: Decl->getUnderlyingType()))
2529 continue;
2530
2531 // If both declarations give a tag declaration a typedef name for linkage
2532 // purposes, then they declare the same entity.
2533 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2534 Decl->getAnonDeclWithTypedefName())
2535 continue;
2536 }
2537
2538 Filter.erase();
2539 }
2540
2541 Filter.done();
2542}
2543
2544bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2545 QualType OldType;
2546 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Val: Old))
2547 OldType = OldTypedef->getUnderlyingType();
2548 else
2549 OldType = Context.getTypeDeclType(Decl: Old);
2550 QualType NewType = New->getUnderlyingType();
2551
2552 if (NewType->isVariablyModifiedType()) {
2553 // Must not redefine a typedef with a variably-modified type.
2554 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2555 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2556 << Kind << NewType;
2557 if (Old->getLocation().isValid())
2558 notePreviousDefinition(Old, New: New->getLocation());
2559 New->setInvalidDecl();
2560 return true;
2561 }
2562
2563 if (OldType != NewType &&
2564 !OldType->isDependentType() &&
2565 !NewType->isDependentType() &&
2566 !Context.hasSameType(T1: OldType, T2: NewType)) {
2567 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2568 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2569 << Kind << NewType << OldType;
2570 if (Old->getLocation().isValid())
2571 notePreviousDefinition(Old, New: New->getLocation());
2572 New->setInvalidDecl();
2573 return true;
2574 }
2575 return false;
2576}
2577
2578/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2579/// same name and scope as a previous declaration 'Old'. Figure out
2580/// how to resolve this situation, merging decls or emitting
2581/// diagnostics as appropriate. If there was an error, set New to be invalid.
2582///
2583void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2584 LookupResult &OldDecls) {
2585 // If the new decl is known invalid already, don't bother doing any
2586 // merging checks.
2587 if (New->isInvalidDecl()) return;
2588
2589 // Allow multiple definitions for ObjC built-in typedefs.
2590 // FIXME: Verify the underlying types are equivalent!
2591 if (getLangOpts().ObjC) {
2592 const IdentifierInfo *TypeID = New->getIdentifier();
2593 switch (TypeID->getLength()) {
2594 default: break;
2595 case 2:
2596 {
2597 if (!TypeID->isStr(Str: "id"))
2598 break;
2599 QualType T = New->getUnderlyingType();
2600 if (!T->isPointerType())
2601 break;
2602 if (!T->isVoidPointerType()) {
2603 QualType PT = T->castAs<PointerType>()->getPointeeType();
2604 if (!PT->isStructureType())
2605 break;
2606 }
2607 Context.setObjCIdRedefinitionType(T);
2608 // Install the built-in type for 'id', ignoring the current definition.
2609 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2610 return;
2611 }
2612 case 5:
2613 if (!TypeID->isStr(Str: "Class"))
2614 break;
2615 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2616 // Install the built-in type for 'Class', ignoring the current definition.
2617 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2618 return;
2619 case 3:
2620 if (!TypeID->isStr(Str: "SEL"))
2621 break;
2622 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2623 // Install the built-in type for 'SEL', ignoring the current definition.
2624 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2625 return;
2626 }
2627 // Fall through - the typedef name was not a builtin type.
2628 }
2629
2630 // Verify the old decl was also a type.
2631 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2632 if (!Old) {
2633 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2634 << New->getDeclName();
2635
2636 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2637 if (OldD->getLocation().isValid())
2638 notePreviousDefinition(Old: OldD, New: New->getLocation());
2639
2640 return New->setInvalidDecl();
2641 }
2642
2643 // If the old declaration is invalid, just give up here.
2644 if (Old->isInvalidDecl())
2645 return New->setInvalidDecl();
2646
2647 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2648 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2649 auto *NewTag = New->getAnonDeclWithTypedefName();
2650 NamedDecl *Hidden = nullptr;
2651 if (OldTag && NewTag &&
2652 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2653 !hasVisibleDefinition(OldTag, &Hidden)) {
2654 // There is a definition of this tag, but it is not visible. Use it
2655 // instead of our tag.
2656 New->setTypeForDecl(OldTD->getTypeForDecl());
2657 if (OldTD->isModed())
2658 New->setModedTypeSourceInfo(unmodedTSI: OldTD->getTypeSourceInfo(),
2659 modedTy: OldTD->getUnderlyingType());
2660 else
2661 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2662
2663 // Make the old tag definition visible.
2664 makeMergedDefinitionVisible(ND: Hidden);
2665
2666 // If this was an unscoped enumeration, yank all of its enumerators
2667 // out of the scope.
2668 if (isa<EnumDecl>(Val: NewTag)) {
2669 Scope *EnumScope = getNonFieldDeclScope(S);
2670 for (auto *D : NewTag->decls()) {
2671 auto *ED = cast<EnumConstantDecl>(D);
2672 assert(EnumScope->isDeclScope(ED));
2673 EnumScope->RemoveDecl(ED);
2674 IdResolver.RemoveDecl(ED);
2675 ED->getLexicalDeclContext()->removeDecl(ED);
2676 }
2677 }
2678 }
2679 }
2680
2681 // If the typedef types are not identical, reject them in all languages and
2682 // with any extensions enabled.
2683 if (isIncompatibleTypedef(Old, New))
2684 return;
2685
2686 // The types match. Link up the redeclaration chain and merge attributes if
2687 // the old declaration was a typedef.
2688 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Val: Old)) {
2689 New->setPreviousDecl(Typedef);
2690 mergeDeclAttributes(New, Old);
2691 }
2692
2693 if (getLangOpts().MicrosoftExt)
2694 return;
2695
2696 if (getLangOpts().CPlusPlus) {
2697 // C++ [dcl.typedef]p2:
2698 // In a given non-class scope, a typedef specifier can be used to
2699 // redefine the name of any type declared in that scope to refer
2700 // to the type to which it already refers.
2701 if (!isa<CXXRecordDecl>(Val: CurContext))
2702 return;
2703
2704 // C++0x [dcl.typedef]p4:
2705 // In a given class scope, a typedef specifier can be used to redefine
2706 // any class-name declared in that scope that is not also a typedef-name
2707 // to refer to the type to which it already refers.
2708 //
2709 // This wording came in via DR424, which was a correction to the
2710 // wording in DR56, which accidentally banned code like:
2711 //
2712 // struct S {
2713 // typedef struct A { } A;
2714 // };
2715 //
2716 // in the C++03 standard. We implement the C++0x semantics, which
2717 // allow the above but disallow
2718 //
2719 // struct S {
2720 // typedef int I;
2721 // typedef int I;
2722 // };
2723 //
2724 // since that was the intent of DR56.
2725 if (!isa<TypedefNameDecl>(Val: Old))
2726 return;
2727
2728 Diag(New->getLocation(), diag::err_redefinition)
2729 << New->getDeclName();
2730 notePreviousDefinition(Old, New: New->getLocation());
2731 return New->setInvalidDecl();
2732 }
2733
2734 // Modules always permit redefinition of typedefs, as does C11.
2735 if (getLangOpts().Modules || getLangOpts().C11)
2736 return;
2737
2738 // If we have a redefinition of a typedef in C, emit a warning. This warning
2739 // is normally mapped to an error, but can be controlled with
2740 // -Wtypedef-redefinition. If either the original or the redefinition is
2741 // in a system header, don't emit this for compatibility with GCC.
2742 if (getDiagnostics().getSuppressSystemWarnings() &&
2743 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2744 (Old->isImplicit() ||
2745 Context.getSourceManager().isInSystemHeader(Loc: Old->getLocation()) ||
2746 Context.getSourceManager().isInSystemHeader(Loc: New->getLocation())))
2747 return;
2748
2749 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2750 << New->getDeclName();
2751 notePreviousDefinition(Old, New: New->getLocation());
2752}
2753
2754/// DeclhasAttr - returns true if decl Declaration already has the target
2755/// attribute.
2756static bool DeclHasAttr(const Decl *D, const Attr *A) {
2757 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2758 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2759 for (const auto *i : D->attrs())
2760 if (i->getKind() == A->getKind()) {
2761 if (Ann) {
2762 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2763 return true;
2764 continue;
2765 }
2766 // FIXME: Don't hardcode this check
2767 if (OA && isa<OwnershipAttr>(i))
2768 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2769 return true;
2770 }
2771
2772 return false;
2773}
2774
2775static bool isAttributeTargetADefinition(Decl *D) {
2776 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D))
2777 return VD->isThisDeclarationADefinition();
2778 if (TagDecl *TD = dyn_cast<TagDecl>(Val: D))
2779 return TD->isCompleteDefinition() || TD->isBeingDefined();
2780 return true;
2781}
2782
2783/// Merge alignment attributes from \p Old to \p New, taking into account the
2784/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2785///
2786/// \return \c true if any attributes were added to \p New.
2787static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2788 // Look for alignas attributes on Old, and pick out whichever attribute
2789 // specifies the strictest alignment requirement.
2790 AlignedAttr *OldAlignasAttr = nullptr;
2791 AlignedAttr *OldStrictestAlignAttr = nullptr;
2792 unsigned OldAlign = 0;
2793 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2794 // FIXME: We have no way of representing inherited dependent alignments
2795 // in a case like:
2796 // template<int A, int B> struct alignas(A) X;
2797 // template<int A, int B> struct alignas(B) X {};
2798 // For now, we just ignore any alignas attributes which are not on the
2799 // definition in such a case.
2800 if (I->isAlignmentDependent())
2801 return false;
2802
2803 if (I->isAlignas())
2804 OldAlignasAttr = I;
2805
2806 unsigned Align = I->getAlignment(S.Context);
2807 if (Align > OldAlign) {
2808 OldAlign = Align;
2809 OldStrictestAlignAttr = I;
2810 }
2811 }
2812
2813 // Look for alignas attributes on New.
2814 AlignedAttr *NewAlignasAttr = nullptr;
2815 unsigned NewAlign = 0;
2816 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2817 if (I->isAlignmentDependent())
2818 return false;
2819
2820 if (I->isAlignas())
2821 NewAlignasAttr = I;
2822
2823 unsigned Align = I->getAlignment(S.Context);
2824 if (Align > NewAlign)
2825 NewAlign = Align;
2826 }
2827
2828 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2829 // Both declarations have 'alignas' attributes. We require them to match.
2830 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2831 // fall short. (If two declarations both have alignas, they must both match
2832 // every definition, and so must match each other if there is a definition.)
2833
2834 // If either declaration only contains 'alignas(0)' specifiers, then it
2835 // specifies the natural alignment for the type.
2836 if (OldAlign == 0 || NewAlign == 0) {
2837 QualType Ty;
2838 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: New))
2839 Ty = VD->getType();
2840 else
2841 Ty = S.Context.getTagDeclType(Decl: cast<TagDecl>(Val: New));
2842
2843 if (OldAlign == 0)
2844 OldAlign = S.Context.getTypeAlign(T: Ty);
2845 if (NewAlign == 0)
2846 NewAlign = S.Context.getTypeAlign(T: Ty);
2847 }
2848
2849 if (OldAlign != NewAlign) {
2850 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2851 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2852 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2853 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2854 }
2855 }
2856
2857 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2858 // C++11 [dcl.align]p6:
2859 // if any declaration of an entity has an alignment-specifier,
2860 // every defining declaration of that entity shall specify an
2861 // equivalent alignment.
2862 // C11 6.7.5/7:
2863 // If the definition of an object does not have an alignment
2864 // specifier, any other declaration of that object shall also
2865 // have no alignment specifier.
2866 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2867 << OldAlignasAttr;
2868 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2869 << OldAlignasAttr;
2870 }
2871
2872 bool AnyAdded = false;
2873
2874 // Ensure we have an attribute representing the strictest alignment.
2875 if (OldAlign > NewAlign) {
2876 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2877 Clone->setInherited(true);
2878 New->addAttr(A: Clone);
2879 AnyAdded = true;
2880 }
2881
2882 // Ensure we have an alignas attribute if the old declaration had one.
2883 if (OldAlignasAttr && !NewAlignasAttr &&
2884 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2885 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2886 Clone->setInherited(true);
2887 New->addAttr(A: Clone);
2888 AnyAdded = true;
2889 }
2890
2891 return AnyAdded;
2892}
2893
2894#define WANT_DECL_MERGE_LOGIC
2895#include "clang/Sema/AttrParsedAttrImpl.inc"
2896#undef WANT_DECL_MERGE_LOGIC
2897
2898static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2899 const InheritableAttr *Attr,
2900 Sema::AvailabilityMergeKind AMK) {
2901 // Diagnose any mutual exclusions between the attribute that we want to add
2902 // and attributes that already exist on the declaration.
2903 if (!DiagnoseMutualExclusions(S, D, Attr))
2904 return false;
2905
2906 // This function copies an attribute Attr from a previous declaration to the
2907 // new declaration D if the new declaration doesn't itself have that attribute
2908 // yet or if that attribute allows duplicates.
2909 // If you're adding a new attribute that requires logic different from
2910 // "use explicit attribute on decl if present, else use attribute from
2911 // previous decl", for example if the attribute needs to be consistent
2912 // between redeclarations, you need to call a custom merge function here.
2913 InheritableAttr *NewAttr = nullptr;
2914 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2915 NewAttr = S.mergeAvailabilityAttr(
2916 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2917 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2918 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2919 AA->getPriority());
2920 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2921 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2922 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2923 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2924 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2925 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2926 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2927 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2928 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2929 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2930 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2931 NewAttr = S.mergeFormatAttr(D, CI: *FA, Format: FA->getType(), FormatIdx: FA->getFormatIdx(),
2932 FirstArg: FA->getFirstArg());
2933 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2934 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2935 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2936 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2937 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2938 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2939 IA->getInheritanceModel());
2940 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2941 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2942 &S.Context.Idents.get(AA->getSpelling()));
2943 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2944 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2945 isa<CUDAGlobalAttr>(Attr))) {
2946 // CUDA target attributes are part of function signature for
2947 // overloading purposes and must not be merged.
2948 return false;
2949 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2950 NewAttr = S.mergeMinSizeAttr(D, *MA);
2951 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2952 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2953 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2954 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2955 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2956 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2957 else if (isa<AlignedAttr>(Attr))
2958 // AlignedAttrs are handled separately, because we need to handle all
2959 // such attributes on a declaration at the same time.
2960 NewAttr = nullptr;
2961 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2962 (AMK == Sema::AMK_Override ||
2963 AMK == Sema::AMK_ProtocolImplementation ||
2964 AMK == Sema::AMK_OptionalProtocolImplementation))
2965 NewAttr = nullptr;
2966 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2967 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2968 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2969 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2970 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2971 NewAttr = S.mergeImportNameAttr(D, *INA);
2972 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2973 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2974 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2975 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2976 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2977 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2978 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2979 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2980 NT->getZ());
2981 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2982 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2983 else if (isa<SuppressAttr>(Attr))
2984 // Do nothing. Each redeclaration should be suppressed separately.
2985 NewAttr = nullptr;
2986 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2987 NewAttr = cast<InheritableAttr>(Attr->clone(C&: S.Context));
2988
2989 if (NewAttr) {
2990 NewAttr->setInherited(true);
2991 D->addAttr(NewAttr);
2992 if (isa<MSInheritanceAttr>(NewAttr))
2993 S.Consumer.AssignInheritanceModel(RD: cast<CXXRecordDecl>(D));
2994 return true;
2995 }
2996
2997 return false;
2998}
2999
3000static const NamedDecl *getDefinition(const Decl *D) {
3001 if (const TagDecl *TD = dyn_cast<TagDecl>(Val: D))
3002 return TD->getDefinition();
3003 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
3004 const VarDecl *Def = VD->getDefinition();
3005 if (Def)
3006 return Def;
3007 return VD->getActingDefinition();
3008 }
3009 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
3010 const FunctionDecl *Def = nullptr;
3011 if (FD->isDefined(Definition&: Def, CheckForPendingFriendDefinition: true))
3012 return Def;
3013 }
3014 return nullptr;
3015}
3016
3017static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3018 for (const auto *Attribute : D->attrs())
3019 if (Attribute->getKind() == Kind)
3020 return true;
3021 return false;
3022}
3023
3024/// checkNewAttributesAfterDef - If we already have a definition, check that
3025/// there are no new attributes in this declaration.
3026static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3027 if (!New->hasAttrs())
3028 return;
3029
3030 const NamedDecl *Def = getDefinition(D: Old);
3031 if (!Def || Def == New)
3032 return;
3033
3034 AttrVec &NewAttributes = New->getAttrs();
3035 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3036 const Attr *NewAttribute = NewAttributes[I];
3037
3038 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3039 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: New)) {
3040 SkipBodyInfo SkipBody;
3041 S.CheckForFunctionRedefinition(FD, EffectiveDefinition: cast<FunctionDecl>(Val: Def), SkipBody: &SkipBody);
3042
3043 // If we're skipping this definition, drop the "alias" attribute.
3044 if (SkipBody.ShouldSkip) {
3045 NewAttributes.erase(CI: NewAttributes.begin() + I);
3046 --E;
3047 continue;
3048 }
3049 } else {
3050 VarDecl *VD = cast<VarDecl>(Val: New);
3051 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3052 VarDecl::TentativeDefinition
3053 ? diag::err_alias_after_tentative
3054 : diag::err_redefinition;
3055 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3056 if (Diag == diag::err_redefinition)
3057 S.notePreviousDefinition(Old: Def, New: VD->getLocation());
3058 else
3059 S.Diag(Def->getLocation(), diag::note_previous_definition);
3060 VD->setInvalidDecl();
3061 }
3062 ++I;
3063 continue;
3064 }
3065
3066 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: Def)) {
3067 // Tentative definitions are only interesting for the alias check above.
3068 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3069 ++I;
3070 continue;
3071 }
3072 }
3073
3074 if (hasAttribute(Def, NewAttribute->getKind())) {
3075 ++I;
3076 continue; // regular attr merging will take care of validating this.
3077 }
3078
3079 if (isa<C11NoReturnAttr>(NewAttribute)) {
3080 // C's _Noreturn is allowed to be added to a function after it is defined.
3081 ++I;
3082 continue;
3083 } else if (isa<UuidAttr>(NewAttribute)) {
3084 // msvc will allow a subsequent definition to add an uuid to a class
3085 ++I;
3086 continue;
3087 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3088 if (AA->isAlignas()) {
3089 // C++11 [dcl.align]p6:
3090 // if any declaration of an entity has an alignment-specifier,
3091 // every defining declaration of that entity shall specify an
3092 // equivalent alignment.
3093 // C11 6.7.5/7:
3094 // If the definition of an object does not have an alignment
3095 // specifier, any other declaration of that object shall also
3096 // have no alignment specifier.
3097 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3098 << AA;
3099 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3100 << AA;
3101 NewAttributes.erase(CI: NewAttributes.begin() + I);
3102 --E;
3103 continue;
3104 }
3105 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3106 // If there is a C definition followed by a redeclaration with this
3107 // attribute then there are two different definitions. In C++, prefer the
3108 // standard diagnostics.
3109 if (!S.getLangOpts().CPlusPlus) {
3110 S.Diag(NewAttribute->getLocation(),
3111 diag::err_loader_uninitialized_redeclaration);
3112 S.Diag(Def->getLocation(), diag::note_previous_definition);
3113 NewAttributes.erase(CI: NewAttributes.begin() + I);
3114 --E;
3115 continue;
3116 }
3117 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3118 cast<VarDecl>(New)->isInline() &&
3119 !cast<VarDecl>(New)->isInlineSpecified()) {
3120 // Don't warn about applying selectany to implicitly inline variables.
3121 // Older compilers and language modes would require the use of selectany
3122 // to make such variables inline, and it would have no effect if we
3123 // honored it.
3124 ++I;
3125 continue;
3126 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3127 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3128 // declarations after definitions.
3129 ++I;
3130 continue;
3131 }
3132
3133 S.Diag(NewAttribute->getLocation(),
3134 diag::warn_attribute_precede_definition);
3135 S.Diag(Def->getLocation(), diag::note_previous_definition);
3136 NewAttributes.erase(CI: NewAttributes.begin() + I);
3137 --E;
3138 }
3139}
3140
3141static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3142 const ConstInitAttr *CIAttr,
3143 bool AttrBeforeInit) {
3144 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3145
3146 // Figure out a good way to write this specifier on the old declaration.
3147 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3148 // enough of the attribute list spelling information to extract that without
3149 // heroics.
3150 std::string SuitableSpelling;
3151 if (S.getLangOpts().CPlusPlus20)
3152 SuitableSpelling = std::string(
3153 S.PP.getLastMacroWithSpelling(Loc: InsertLoc, Tokens: {tok::kw_constinit}));
3154 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3155 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3156 Loc: InsertLoc, Tokens: {tok::l_square, tok::l_square,
3157 S.PP.getIdentifierInfo(Name: "clang"), tok::coloncolon,
3158 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3159 tok::r_square, tok::r_square}));
3160 if (SuitableSpelling.empty())
3161 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3162 Loc: InsertLoc, Tokens: {tok::kw___attribute, tok::l_paren, tok::r_paren,
3163 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3164 tok::r_paren, tok::r_paren}));
3165 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3166 SuitableSpelling = "constinit";
3167 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3168 SuitableSpelling = "[[clang::require_constant_initialization]]";
3169 if (SuitableSpelling.empty())
3170 SuitableSpelling = "__attribute__((require_constant_initialization))";
3171 SuitableSpelling += " ";
3172
3173 if (AttrBeforeInit) {
3174 // extern constinit int a;
3175 // int a = 0; // error (missing 'constinit'), accepted as extension
3176 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3177 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3178 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3179 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3180 } else {
3181 // int a = 0;
3182 // constinit extern int a; // error (missing 'constinit')
3183 S.Diag(CIAttr->getLocation(),
3184 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3185 : diag::warn_require_const_init_added_too_late)
3186 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3187 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3188 << CIAttr->isConstinit()
3189 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3190 }
3191}
3192
3193/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3194void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3195 AvailabilityMergeKind AMK) {
3196 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3197 UsedAttr *NewAttr = OldAttr->clone(Context);
3198 NewAttr->setInherited(true);
3199 New->addAttr(A: NewAttr);
3200 }
3201 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3202 RetainAttr *NewAttr = OldAttr->clone(Context);
3203 NewAttr->setInherited(true);
3204 New->addAttr(A: NewAttr);
3205 }
3206
3207 if (!Old->hasAttrs() && !New->hasAttrs())
3208 return;
3209
3210 // [dcl.constinit]p1:
3211 // If the [constinit] specifier is applied to any declaration of a
3212 // variable, it shall be applied to the initializing declaration.
3213 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3214 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3215 if (bool(OldConstInit) != bool(NewConstInit)) {
3216 const auto *OldVD = cast<VarDecl>(Val: Old);
3217 auto *NewVD = cast<VarDecl>(Val: New);
3218
3219 // Find the initializing declaration. Note that we might not have linked
3220 // the new declaration into the redeclaration chain yet.
3221 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3222 if (!InitDecl &&
3223 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3224 InitDecl = NewVD;
3225
3226 if (InitDecl == NewVD) {
3227 // This is the initializing declaration. If it would inherit 'constinit',
3228 // that's ill-formed. (Note that we do not apply this to the attribute
3229 // form).
3230 if (OldConstInit && OldConstInit->isConstinit())
3231 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3232 /*AttrBeforeInit=*/true);
3233 } else if (NewConstInit) {
3234 // This is the first time we've been told that this declaration should
3235 // have a constant initializer. If we already saw the initializing
3236 // declaration, this is too late.
3237 if (InitDecl && InitDecl != NewVD) {
3238 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3239 /*AttrBeforeInit=*/false);
3240 NewVD->dropAttr<ConstInitAttr>();
3241 }
3242 }
3243 }
3244
3245 // Attributes declared post-definition are currently ignored.
3246 checkNewAttributesAfterDef(*this, New, Old);
3247
3248 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3249 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3250 if (!OldA->isEquivalent(NewA)) {
3251 // This redeclaration changes __asm__ label.
3252 Diag(New->getLocation(), diag::err_different_asm_label);
3253 Diag(OldA->getLocation(), diag::note_previous_declaration);
3254 }
3255 } else if (Old->isUsed()) {
3256 // This redeclaration adds an __asm__ label to a declaration that has
3257 // already been ODR-used.
3258 Diag(New->getLocation(), diag::err_late_asm_label_name)
3259 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3260 }
3261 }
3262
3263 // Re-declaration cannot add abi_tag's.
3264 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3265 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3266 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3267 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3268 Diag(NewAbiTagAttr->getLocation(),
3269 diag::err_new_abi_tag_on_redeclaration)
3270 << NewTag;
3271 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3272 }
3273 }
3274 } else {
3275 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3276 Diag(Old->getLocation(), diag::note_previous_declaration);
3277 }
3278 }
3279
3280 // This redeclaration adds a section attribute.
3281 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3282 if (auto *VD = dyn_cast<VarDecl>(Val: New)) {
3283 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3284 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3285 Diag(Old->getLocation(), diag::note_previous_declaration);
3286 }
3287 }
3288 }
3289
3290 // Redeclaration adds code-seg attribute.
3291 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3292 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3293 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3294 Diag(New->getLocation(), diag::warn_mismatched_section)
3295 << 0 /*codeseg*/;
3296 Diag(Old->getLocation(), diag::note_previous_declaration);
3297 }
3298
3299 if (!Old->hasAttrs())
3300 return;
3301
3302 bool foundAny = New->hasAttrs();
3303
3304 // Ensure that any moving of objects within the allocated map is done before
3305 // we process them.
3306 if (!foundAny) New->setAttrs(AttrVec());
3307
3308 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3309 // Ignore deprecated/unavailable/availability attributes if requested.
3310 AvailabilityMergeKind LocalAMK = AMK_None;
3311 if (isa<DeprecatedAttr>(I) ||
3312 isa<UnavailableAttr>(I) ||
3313 isa<AvailabilityAttr>(I)) {
3314 switch (AMK) {
3315 case AMK_None:
3316 continue;
3317
3318 case AMK_Redeclaration:
3319 case AMK_Override:
3320 case AMK_ProtocolImplementation:
3321 case AMK_OptionalProtocolImplementation:
3322 LocalAMK = AMK;
3323 break;
3324 }
3325 }
3326
3327 // Already handled.
3328 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3329 continue;
3330
3331 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3332 foundAny = true;
3333 }
3334
3335 if (mergeAlignedAttrs(S&: *this, New, Old))
3336 foundAny = true;
3337
3338 if (!foundAny) New->dropAttrs();
3339}
3340
3341/// mergeParamDeclAttributes - Copy attributes from the old parameter
3342/// to the new one.
3343static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3344 const ParmVarDecl *oldDecl,
3345 Sema &S) {
3346 // C++11 [dcl.attr.depend]p2:
3347 // The first declaration of a function shall specify the
3348 // carries_dependency attribute for its declarator-id if any declaration
3349 // of the function specifies the carries_dependency attribute.
3350 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3351 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3352 S.Diag(CDA->getLocation(),
3353 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3354 // Find the first declaration of the parameter.
3355 // FIXME: Should we build redeclaration chains for function parameters?
3356 const FunctionDecl *FirstFD =
3357 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3358 const ParmVarDecl *FirstVD =
3359 FirstFD->getParamDecl(i: oldDecl->getFunctionScopeIndex());
3360 S.Diag(FirstVD->getLocation(),
3361 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3362 }
3363
3364 // HLSL parameter declarations for inout and out must match between
3365 // declarations. In HLSL inout and out are ambiguous at the call site, but
3366 // have different calling behavior, so you cannot overload a method based on a
3367 // difference between inout and out annotations.
3368 if (S.getLangOpts().HLSL) {
3369 const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>();
3370 const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>();
3371 // We don't need to cover the case where one declaration doesn't have an
3372 // attribute. The only possible case there is if one declaration has an `in`
3373 // attribute and the other declaration has no attribute. This case is
3374 // allowed since parameters are `in` by default.
3375 if (NDAttr && ODAttr &&
3376 NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) {
3377 S.Diag(newDecl->getLocation(), diag::err_hlsl_param_qualifier_mismatch)
3378 << NDAttr << newDecl;
3379 S.Diag(oldDecl->getLocation(), diag::note_previous_declaration_as)
3380 << ODAttr;
3381 }
3382 }
3383
3384 if (!oldDecl->hasAttrs())
3385 return;
3386
3387 bool foundAny = newDecl->hasAttrs();
3388
3389 // Ensure that any moving of objects within the allocated map is
3390 // done before we process them.
3391 if (!foundAny) newDecl->setAttrs(AttrVec());
3392
3393 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3394 if (!DeclHasAttr(newDecl, I)) {
3395 InheritableAttr *newAttr =
3396 cast<InheritableParamAttr>(I->clone(S.Context));
3397 newAttr->setInherited(true);
3398 newDecl->addAttr(newAttr);
3399 foundAny = true;
3400 }
3401 }
3402
3403 if (!foundAny) newDecl->dropAttrs();
3404}
3405
3406static bool EquivalentArrayTypes(QualType Old, QualType New,
3407 const ASTContext &Ctx) {
3408
3409 auto NoSizeInfo = [&Ctx](QualType Ty) {
3410 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3411 return true;
3412 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3413 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3414 return false;
3415 };
3416
3417 // `type[]` is equivalent to `type *` and `type[*]`.
3418 if (NoSizeInfo(Old) && NoSizeInfo(New))
3419 return true;
3420
3421 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3422 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3423 const auto *OldVAT = Ctx.getAsVariableArrayType(T: Old);
3424 const auto *NewVAT = Ctx.getAsVariableArrayType(T: New);
3425 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3426 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3427 return false;
3428 return true;
3429 }
3430
3431 // Only compare size, ignore Size modifiers and CVR.
3432 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3433 return Ctx.getAsConstantArrayType(T: Old)->getSize() ==
3434 Ctx.getAsConstantArrayType(T: New)->getSize();
3435 }
3436
3437 // Don't try to compare dependent sized array
3438 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3439 return true;
3440 }
3441
3442 return Old == New;
3443}
3444
3445static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3446 const ParmVarDecl *OldParam,
3447 Sema &S) {
3448 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3449 if (auto Newnullability = NewParam->getType()->getNullability()) {
3450 if (*Oldnullability != *Newnullability) {
3451 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3452 << DiagNullabilityKind(
3453 *Newnullability,
3454 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3455 != 0))
3456 << DiagNullabilityKind(
3457 *Oldnullability,
3458 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3459 != 0));
3460 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3461 }
3462 } else {
3463 QualType NewT = NewParam->getType();
3464 NewT = S.Context.getAttributedType(
3465 attrKind: AttributedType::getNullabilityAttrKind(kind: *Oldnullability),
3466 modifiedType: NewT, equivalentType: NewT);
3467 NewParam->setType(NewT);
3468 }
3469 }
3470 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3471 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3472 if (OldParamDT && NewParamDT &&
3473 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3474 QualType OldParamOT = OldParamDT->getOriginalType();
3475 QualType NewParamOT = NewParamDT->getOriginalType();
3476 if (!EquivalentArrayTypes(Old: OldParamOT, New: NewParamOT, Ctx: S.getASTContext())) {
3477 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3478 << NewParam << NewParamOT;
3479 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3480 << OldParamOT;
3481 }
3482 }
3483}
3484
3485namespace {
3486
3487/// Used in MergeFunctionDecl to keep track of function parameters in
3488/// C.
3489struct GNUCompatibleParamWarning {
3490 ParmVarDecl *OldParm;
3491 ParmVarDecl *NewParm;
3492 QualType PromotedType;
3493};
3494
3495} // end anonymous namespace
3496
3497// Determine whether the previous declaration was a definition, implicit
3498// declaration, or a declaration.
3499template <typename T>
3500static std::pair<diag::kind, SourceLocation>
3501getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3502 diag::kind PrevDiag;
3503 SourceLocation OldLocation = Old->getLocation();
3504 if (Old->isThisDeclarationADefinition())
3505 PrevDiag = diag::note_previous_definition;
3506 else if (Old->isImplicit()) {
3507 PrevDiag = diag::note_previous_implicit_declaration;
3508 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3509 if (FD->getBuiltinID())
3510 PrevDiag = diag::note_previous_builtin_declaration;
3511 }
3512 if (OldLocation.isInvalid())
3513 OldLocation = New->getLocation();
3514 } else
3515 PrevDiag = diag::note_previous_declaration;
3516 return std::make_pair(x&: PrevDiag, y&: OldLocation);
3517}
3518
3519/// canRedefineFunction - checks if a function can be redefined. Currently,
3520/// only extern inline functions can be redefined, and even then only in
3521/// GNU89 mode.
3522static bool canRedefineFunction(const FunctionDecl *FD,
3523 const LangOptions& LangOpts) {
3524 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3525 !LangOpts.CPlusPlus &&
3526 FD->isInlineSpecified() &&
3527 FD->getStorageClass() == SC_Extern);
3528}
3529
3530const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3531 const AttributedType *AT = T->getAs<AttributedType>();
3532 while (AT && !AT->isCallingConv())
3533 AT = AT->getModifiedType()->getAs<AttributedType>();
3534 return AT;
3535}
3536
3537template <typename T>
3538static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3539 const DeclContext *DC = Old->getDeclContext();
3540 if (DC->isRecord())
3541 return false;
3542
3543 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3544 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3545 return true;
3546 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3547 return true;
3548 return false;
3549}
3550
3551template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3552static bool isExternC(VarTemplateDecl *) { return false; }
3553static bool isExternC(FunctionTemplateDecl *) { return false; }
3554
3555/// Check whether a redeclaration of an entity introduced by a
3556/// using-declaration is valid, given that we know it's not an overload
3557/// (nor a hidden tag declaration).
3558template<typename ExpectedDecl>
3559static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3560 ExpectedDecl *New) {
3561 // C++11 [basic.scope.declarative]p4:
3562 // Given a set of declarations in a single declarative region, each of
3563 // which specifies the same unqualified name,
3564 // -- they shall all refer to the same entity, or all refer to functions
3565 // and function templates; or
3566 // -- exactly one declaration shall declare a class name or enumeration
3567 // name that is not a typedef name and the other declarations shall all
3568 // refer to the same variable or enumerator, or all refer to functions
3569 // and function templates; in this case the class name or enumeration
3570 // name is hidden (3.3.10).
3571
3572 // C++11 [namespace.udecl]p14:
3573 // If a function declaration in namespace scope or block scope has the
3574 // same name and the same parameter-type-list as a function introduced
3575 // by a using-declaration, and the declarations do not declare the same
3576 // function, the program is ill-formed.
3577
3578 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3579 if (Old &&
3580 !Old->getDeclContext()->getRedeclContext()->Equals(
3581 New->getDeclContext()->getRedeclContext()) &&
3582 !(isExternC(Old) && isExternC(New)))
3583 Old = nullptr;
3584
3585 if (!Old) {
3586 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3587 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3588 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3589 return true;
3590 }
3591 return false;
3592}
3593
3594static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3595 const FunctionDecl *B) {
3596 assert(A->getNumParams() == B->getNumParams());
3597
3598 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3599 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3600 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3601 if (AttrA == AttrB)
3602 return true;
3603 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3604 AttrA->isDynamic() == AttrB->isDynamic();
3605 };
3606
3607 return std::equal(first1: A->param_begin(), last1: A->param_end(), first2: B->param_begin(), binary_pred: AttrEq);
3608}
3609
3610/// If necessary, adjust the semantic declaration context for a qualified
3611/// declaration to name the correct inline namespace within the qualifier.
3612static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3613 DeclaratorDecl *OldD) {
3614 // The only case where we need to update the DeclContext is when
3615 // redeclaration lookup for a qualified name finds a declaration
3616 // in an inline namespace within the context named by the qualifier:
3617 //
3618 // inline namespace N { int f(); }
3619 // int ::f(); // Sema DC needs adjusting from :: to N::.
3620 //
3621 // For unqualified declarations, the semantic context *can* change
3622 // along the redeclaration chain (for local extern declarations,
3623 // extern "C" declarations, and friend declarations in particular).
3624 if (!NewD->getQualifier())
3625 return;
3626
3627 // NewD is probably already in the right context.
3628 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3629 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3630 if (NamedDC->Equals(SemaDC))
3631 return;
3632
3633 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3634 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3635 "unexpected context for redeclaration");
3636
3637 auto *LexDC = NewD->getLexicalDeclContext();
3638 auto FixSemaDC = [=](NamedDecl *D) {
3639 if (!D)
3640 return;
3641 D->setDeclContext(SemaDC);
3642 D->setLexicalDeclContext(LexDC);
3643 };
3644
3645 FixSemaDC(NewD);
3646 if (auto *FD = dyn_cast<FunctionDecl>(Val: NewD))
3647 FixSemaDC(FD->getDescribedFunctionTemplate());
3648 else if (auto *VD = dyn_cast<VarDecl>(Val: NewD))
3649 FixSemaDC(VD->getDescribedVarTemplate());
3650}
3651
3652/// MergeFunctionDecl - We just parsed a function 'New' from
3653/// declarator D which has the same name and scope as a previous
3654/// declaration 'Old'. Figure out how to resolve this situation,
3655/// merging decls or emitting diagnostics as appropriate.
3656///
3657/// In C++, New and Old must be declarations that are not
3658/// overloaded. Use IsOverload to determine whether New and Old are
3659/// overloaded, and to select the Old declaration that New should be
3660/// merged with.
3661///
3662/// Returns true if there was an error, false otherwise.
3663bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3664 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3665 // Verify the old decl was also a function.
3666 FunctionDecl *Old = OldD->getAsFunction();
3667 if (!Old) {
3668 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: OldD)) {
3669 if (New->getFriendObjectKind()) {
3670 Diag(New->getLocation(), diag::err_using_decl_friend);
3671 Diag(Shadow->getTargetDecl()->getLocation(),
3672 diag::note_using_decl_target);
3673 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3674 << 0;
3675 return true;
3676 }
3677
3678 // Check whether the two declarations might declare the same function or
3679 // function template.
3680 if (FunctionTemplateDecl *NewTemplate =
3681 New->getDescribedFunctionTemplate()) {
3682 if (checkUsingShadowRedecl<FunctionTemplateDecl>(S&: *this, OldS: Shadow,
3683 New: NewTemplate))
3684 return true;
3685 OldD = Old = cast<FunctionTemplateDecl>(Val: Shadow->getTargetDecl())
3686 ->getAsFunction();
3687 } else {
3688 if (checkUsingShadowRedecl<FunctionDecl>(S&: *this, OldS: Shadow, New))
3689 return true;
3690 OldD = Old = cast<FunctionDecl>(Val: Shadow->getTargetDecl());
3691 }
3692 } else {
3693 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3694 << New->getDeclName();
3695 notePreviousDefinition(Old: OldD, New: New->getLocation());
3696 return true;
3697 }
3698 }
3699
3700 // If the old declaration was found in an inline namespace and the new
3701 // declaration was qualified, update the DeclContext to match.
3702 adjustDeclContextForDeclaratorDecl(New, Old);
3703
3704 // If the old declaration is invalid, just give up here.
3705 if (Old->isInvalidDecl())
3706 return true;
3707
3708 // Disallow redeclaration of some builtins.
3709 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3710 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3711 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3712 << Old << Old->getType();
3713 return true;
3714 }
3715
3716 diag::kind PrevDiag;
3717 SourceLocation OldLocation;
3718 std::tie(args&: PrevDiag, args&: OldLocation) =
3719 getNoteDiagForInvalidRedeclaration(Old, New);
3720
3721 // Don't complain about this if we're in GNU89 mode and the old function
3722 // is an extern inline function.
3723 // Don't complain about specializations. They are not supposed to have
3724 // storage classes.
3725 if (!isa<CXXMethodDecl>(Val: New) && !isa<CXXMethodDecl>(Val: Old) &&
3726 New->getStorageClass() == SC_Static &&
3727 Old->hasExternalFormalLinkage() &&
3728 !New->getTemplateSpecializationInfo() &&
3729 !canRedefineFunction(FD: Old, LangOpts: getLangOpts())) {
3730 if (getLangOpts().MicrosoftExt) {
3731 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3732 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3733 } else {
3734 Diag(New->getLocation(), diag::err_static_non_static) << New;
3735 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3736 return true;
3737 }
3738 }
3739
3740 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3741 if (!Old->hasAttr<InternalLinkageAttr>()) {
3742 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3743 << ILA;
3744 Diag(Old->getLocation(), diag::note_previous_declaration);
3745 New->dropAttr<InternalLinkageAttr>();
3746 }
3747
3748 if (auto *EA = New->getAttr<ErrorAttr>()) {
3749 if (!Old->hasAttr<ErrorAttr>()) {
3750 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3751 Diag(Old->getLocation(), diag::note_previous_declaration);
3752 New->dropAttr<ErrorAttr>();
3753 }
3754 }
3755
3756 if (CheckRedeclarationInModule(New, Old))
3757 return true;
3758
3759 if (!getLangOpts().CPlusPlus) {
3760 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3761 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3762 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3763 << New << OldOvl;
3764
3765 // Try our best to find a decl that actually has the overloadable
3766 // attribute for the note. In most cases (e.g. programs with only one
3767 // broken declaration/definition), this won't matter.
3768 //
3769 // FIXME: We could do this if we juggled some extra state in
3770 // OverloadableAttr, rather than just removing it.
3771 const Decl *DiagOld = Old;
3772 if (OldOvl) {
3773 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3774 const auto *A = D->getAttr<OverloadableAttr>();
3775 return A && !A->isImplicit();
3776 });
3777 // If we've implicitly added *all* of the overloadable attrs to this
3778 // chain, emitting a "previous redecl" note is pointless.
3779 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3780 }
3781
3782 if (DiagOld)
3783 Diag(DiagOld->getLocation(),
3784 diag::note_attribute_overloadable_prev_overload)
3785 << OldOvl;
3786
3787 if (OldOvl)
3788 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3789 else
3790 New->dropAttr<OverloadableAttr>();
3791 }
3792 }
3793
3794 // It is not permitted to redeclare an SME function with different SME
3795 // attributes.
3796 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
3797 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3798 << New->getType() << Old->getType();
3799 Diag(OldLocation, diag::note_previous_declaration);
3800 return true;
3801 }
3802
3803 // If a function is first declared with a calling convention, but is later
3804 // declared or defined without one, all following decls assume the calling
3805 // convention of the first.
3806 //
3807 // It's OK if a function is first declared without a calling convention,
3808 // but is later declared or defined with the default calling convention.
3809 //
3810 // To test if either decl has an explicit calling convention, we look for
3811 // AttributedType sugar nodes on the type as written. If they are missing or
3812 // were canonicalized away, we assume the calling convention was implicit.
3813 //
3814 // Note also that we DO NOT return at this point, because we still have
3815 // other tests to run.
3816 QualType OldQType = Context.getCanonicalType(Old->getType());
3817 QualType NewQType = Context.getCanonicalType(New->getType());
3818 const FunctionType *OldType = cast<FunctionType>(Val&: OldQType);
3819 const FunctionType *NewType = cast<FunctionType>(Val&: NewQType);
3820 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3821 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3822 bool RequiresAdjustment = false;
3823
3824 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3825 FunctionDecl *First = Old->getFirstDecl();
3826 const FunctionType *FT =
3827 First->getType().getCanonicalType()->castAs<FunctionType>();
3828 FunctionType::ExtInfo FI = FT->getExtInfo();
3829 bool NewCCExplicit = getCallingConvAttributedType(T: New->getType());
3830 if (!NewCCExplicit) {
3831 // Inherit the CC from the previous declaration if it was specified
3832 // there but not here.
3833 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3834 RequiresAdjustment = true;
3835 } else if (Old->getBuiltinID()) {
3836 // Builtin attribute isn't propagated to the new one yet at this point,
3837 // so we check if the old one is a builtin.
3838
3839 // Calling Conventions on a Builtin aren't really useful and setting a
3840 // default calling convention and cdecl'ing some builtin redeclarations is
3841 // common, so warn and ignore the calling convention on the redeclaration.
3842 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3843 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3844 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3845 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3846 RequiresAdjustment = true;
3847 } else {
3848 // Calling conventions aren't compatible, so complain.
3849 bool FirstCCExplicit = getCallingConvAttributedType(T: First->getType());
3850 Diag(New->getLocation(), diag::err_cconv_change)
3851 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3852 << !FirstCCExplicit
3853 << (!FirstCCExplicit ? "" :
3854 FunctionType::getNameForCallConv(FI.getCC()));
3855
3856 // Put the note on the first decl, since it is the one that matters.
3857 Diag(First->getLocation(), diag::note_previous_declaration);
3858 return true;
3859 }
3860 }
3861
3862 // FIXME: diagnose the other way around?
3863 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3864 NewTypeInfo = NewTypeInfo.withNoReturn(noReturn: true);
3865 RequiresAdjustment = true;
3866 }
3867
3868 // Merge regparm attribute.
3869 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3870 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3871 if (NewTypeInfo.getHasRegParm()) {
3872 Diag(New->getLocation(), diag::err_regparm_mismatch)
3873 << NewType->getRegParmType()
3874 << OldType->getRegParmType();
3875 Diag(OldLocation, diag::note_previous_declaration);
3876 return true;
3877 }
3878
3879 NewTypeInfo = NewTypeInfo.withRegParm(RegParm: OldTypeInfo.getRegParm());
3880 RequiresAdjustment = true;
3881 }
3882
3883 // Merge ns_returns_retained attribute.
3884 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3885 if (NewTypeInfo.getProducesResult()) {
3886 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3887 << "'ns_returns_retained'";
3888 Diag(OldLocation, diag::note_previous_declaration);
3889 return true;
3890 }
3891
3892 NewTypeInfo = NewTypeInfo.withProducesResult(producesResult: true);
3893 RequiresAdjustment = true;
3894 }
3895
3896 if (OldTypeInfo.getNoCallerSavedRegs() !=
3897 NewTypeInfo.getNoCallerSavedRegs()) {
3898 if (NewTypeInfo.getNoCallerSavedRegs()) {
3899 AnyX86NoCallerSavedRegistersAttr *Attr =
3900 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3901 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3902 Diag(OldLocation, diag::note_previous_declaration);
3903 return true;
3904 }
3905
3906 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(noCallerSavedRegs: true);
3907 RequiresAdjustment = true;
3908 }
3909
3910 if (RequiresAdjustment) {
3911 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3912 AdjustedType = Context.adjustFunctionType(Fn: AdjustedType, EInfo: NewTypeInfo);
3913 New->setType(QualType(AdjustedType, 0));
3914 NewQType = Context.getCanonicalType(New->getType());
3915 }
3916
3917 // If this redeclaration makes the function inline, we may need to add it to
3918 // UndefinedButUsed.
3919 if (!Old->isInlined() && New->isInlined() &&
3920 !New->hasAttr<GNUInlineAttr>() &&
3921 !getLangOpts().GNUInline &&
3922 Old->isUsed(false) &&
3923 !Old->isDefined() && !New->isThisDeclarationADefinition())
3924 UndefinedButUsed.insert(std::make_pair(x: Old->getCanonicalDecl(),
3925 y: SourceLocation()));
3926
3927 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3928 // about it.
3929 if (New->hasAttr<GNUInlineAttr>() &&
3930 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3931 UndefinedButUsed.erase(Old->getCanonicalDecl());
3932 }
3933
3934 // If pass_object_size params don't match up perfectly, this isn't a valid
3935 // redeclaration.
3936 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3937 !hasIdenticalPassObjectSizeAttrs(A: Old, B: New)) {
3938 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3939 << New->getDeclName();
3940 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3941 return true;
3942 }
3943
3944 if (getLangOpts().CPlusPlus) {
3945 OldQType = Context.getCanonicalType(Old->getType());
3946 NewQType = Context.getCanonicalType(New->getType());
3947
3948 // Go back to the type source info to compare the declared return types,
3949 // per C++1y [dcl.type.auto]p13:
3950 // Redeclarations or specializations of a function or function template
3951 // with a declared return type that uses a placeholder type shall also
3952 // use that placeholder, not a deduced type.
3953 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3954 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3955 if (!Context.hasSameType(T1: OldDeclaredReturnType, T2: NewDeclaredReturnType) &&
3956 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3957 OldDeclaredReturnType)) {
3958 QualType ResQT;
3959 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3960 OldDeclaredReturnType->isObjCObjectPointerType())
3961 // FIXME: This does the wrong thing for a deduced return type.
3962 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3963 if (ResQT.isNull()) {
3964 if (New->isCXXClassMember() && New->isOutOfLine())
3965 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3966 << New << New->getReturnTypeSourceRange();
3967 else
3968 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3969 << New->getReturnTypeSourceRange();
3970 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3971 << Old->getReturnTypeSourceRange();
3972 return true;
3973 }
3974 else
3975 NewQType = ResQT;
3976 }
3977
3978 QualType OldReturnType = OldType->getReturnType();
3979 QualType NewReturnType = cast<FunctionType>(Val&: NewQType)->getReturnType();
3980 if (OldReturnType != NewReturnType) {
3981 // If this function has a deduced return type and has already been
3982 // defined, copy the deduced value from the old declaration.
3983 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3984 if (OldAT && OldAT->isDeduced()) {
3985 QualType DT = OldAT->getDeducedType();
3986 if (DT.isNull()) {
3987 New->setType(SubstAutoTypeDependent(TypeWithAuto: New->getType()));
3988 NewQType = Context.getCanonicalType(T: SubstAutoTypeDependent(TypeWithAuto: NewQType));
3989 } else {
3990 New->setType(SubstAutoType(TypeWithAuto: New->getType(), Replacement: DT));
3991 NewQType = Context.getCanonicalType(T: SubstAutoType(TypeWithAuto: NewQType, Replacement: DT));
3992 }
3993 }
3994 }
3995
3996 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
3997 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
3998 if (OldMethod && NewMethod) {
3999 // Preserve triviality.
4000 NewMethod->setTrivial(OldMethod->isTrivial());
4001
4002 // MSVC allows explicit template specialization at class scope:
4003 // 2 CXXMethodDecls referring to the same function will be injected.
4004 // We don't want a redeclaration error.
4005 bool IsClassScopeExplicitSpecialization =
4006 OldMethod->isFunctionTemplateSpecialization() &&
4007 NewMethod->isFunctionTemplateSpecialization();
4008 bool isFriend = NewMethod->getFriendObjectKind();
4009
4010 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4011 !IsClassScopeExplicitSpecialization) {
4012 // -- Member function declarations with the same name and the
4013 // same parameter types cannot be overloaded if any of them
4014 // is a static member function declaration.
4015 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4016 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4017 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4018 return true;
4019 }
4020
4021 // C++ [class.mem]p1:
4022 // [...] A member shall not be declared twice in the
4023 // member-specification, except that a nested class or member
4024 // class template can be declared and then later defined.
4025 if (!inTemplateInstantiation()) {
4026 unsigned NewDiag;
4027 if (isa<CXXConstructorDecl>(OldMethod))
4028 NewDiag = diag::err_constructor_redeclared;
4029 else if (isa<CXXDestructorDecl>(NewMethod))
4030 NewDiag = diag::err_destructor_redeclared;
4031 else if (isa<CXXConversionDecl>(NewMethod))
4032 NewDiag = diag::err_conv_function_redeclared;
4033 else
4034 NewDiag = diag::err_member_redeclared;
4035
4036 Diag(New->getLocation(), NewDiag);
4037 } else {
4038 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4039 << New << New->getType();
4040 }
4041 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4042 return true;
4043
4044 // Complain if this is an explicit declaration of a special
4045 // member that was initially declared implicitly.
4046 //
4047 // As an exception, it's okay to befriend such methods in order
4048 // to permit the implicit constructor/destructor/operator calls.
4049 } else if (OldMethod->isImplicit()) {
4050 if (isFriend) {
4051 NewMethod->setImplicit();
4052 } else {
4053 Diag(NewMethod->getLocation(),
4054 diag::err_definition_of_implicitly_declared_member)
4055 << New << llvm::to_underlying(getSpecialMember(OldMethod));
4056 return true;
4057 }
4058 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4059 Diag(NewMethod->getLocation(),
4060 diag::err_definition_of_explicitly_defaulted_member)
4061 << llvm::to_underlying(getSpecialMember(OldMethod));
4062 return true;
4063 }
4064 }
4065
4066 // C++1z [over.load]p2
4067 // Certain function declarations cannot be overloaded:
4068 // -- Function declarations that differ only in the return type,
4069 // the exception specification, or both cannot be overloaded.
4070
4071 // Check the exception specifications match. This may recompute the type of
4072 // both Old and New if it resolved exception specifications, so grab the
4073 // types again after this. Because this updates the type, we do this before
4074 // any of the other checks below, which may update the "de facto" NewQType
4075 // but do not necessarily update the type of New.
4076 if (CheckEquivalentExceptionSpec(Old, New))
4077 return true;
4078
4079 // C++11 [dcl.attr.noreturn]p1:
4080 // The first declaration of a function shall specify the noreturn
4081 // attribute if any declaration of that function specifies the noreturn
4082 // attribute.
4083 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4084 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4085 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4086 << NRA;
4087 Diag(Old->getLocation(), diag::note_previous_declaration);
4088 }
4089
4090 // C++11 [dcl.attr.depend]p2:
4091 // The first declaration of a function shall specify the
4092 // carries_dependency attribute for its declarator-id if any declaration
4093 // of the function specifies the carries_dependency attribute.
4094 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4095 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4096 Diag(CDA->getLocation(),
4097 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4098 Diag(Old->getFirstDecl()->getLocation(),
4099 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4100 }
4101
4102 // (C++98 8.3.5p3):
4103 // All declarations for a function shall agree exactly in both the
4104 // return type and the parameter-type-list.
4105 // We also want to respect all the extended bits except noreturn.
4106
4107 // noreturn should now match unless the old type info didn't have it.
4108 QualType OldQTypeForComparison = OldQType;
4109 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4110 auto *OldType = OldQType->castAs<FunctionProtoType>();
4111 const FunctionType *OldTypeForComparison
4112 = Context.adjustFunctionType(Fn: OldType, EInfo: OldTypeInfo.withNoReturn(noReturn: true));
4113 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4114 assert(OldQTypeForComparison.isCanonical());
4115 }
4116
4117 if (haveIncompatibleLanguageLinkages(Old, New)) {
4118 // As a special case, retain the language linkage from previous
4119 // declarations of a friend function as an extension.
4120 //
4121 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4122 // and is useful because there's otherwise no way to specify language
4123 // linkage within class scope.
4124 //
4125 // Check cautiously as the friend object kind isn't yet complete.
4126 if (New->getFriendObjectKind() != Decl::FOK_None) {
4127 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4128 Diag(OldLocation, PrevDiag);
4129 } else {
4130 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4131 Diag(OldLocation, PrevDiag);
4132 return true;
4133 }
4134 }
4135
4136 // If the function types are compatible, merge the declarations. Ignore the
4137 // exception specifier because it was already checked above in
4138 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4139 // about incompatible types under -fms-compatibility.
4140 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(T: OldQTypeForComparison,
4141 U: NewQType))
4142 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4143
4144 // If the types are imprecise (due to dependent constructs in friends or
4145 // local extern declarations), it's OK if they differ. We'll check again
4146 // during instantiation.
4147 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4148 return false;
4149
4150 // Fall through for conflicting redeclarations and redefinitions.
4151 }
4152
4153 // C: Function types need to be compatible, not identical. This handles
4154 // duplicate function decls like "void f(int); void f(enum X);" properly.
4155 if (!getLangOpts().CPlusPlus) {
4156 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4157 // type is specified by a function definition that contains a (possibly
4158 // empty) identifier list, both shall agree in the number of parameters
4159 // and the type of each parameter shall be compatible with the type that
4160 // results from the application of default argument promotions to the
4161 // type of the corresponding identifier. ...
4162 // This cannot be handled by ASTContext::typesAreCompatible() because that
4163 // doesn't know whether the function type is for a definition or not when
4164 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4165 // we need to cover here is that the number of arguments agree as the
4166 // default argument promotion rules were already checked by
4167 // ASTContext::typesAreCompatible().
4168 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4169 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4170 if (Old->hasInheritedPrototype())
4171 Old = Old->getCanonicalDecl();
4172 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4173 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4174 return true;
4175 }
4176
4177 // If we are merging two functions where only one of them has a prototype,
4178 // we may have enough information to decide to issue a diagnostic that the
4179 // function without a protoype will change behavior in C23. This handles
4180 // cases like:
4181 // void i(); void i(int j);
4182 // void i(int j); void i();
4183 // void i(); void i(int j) {}
4184 // See ActOnFinishFunctionBody() for other cases of the behavior change
4185 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4186 // type without a prototype.
4187 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4188 !New->isImplicit() && !Old->isImplicit()) {
4189 const FunctionDecl *WithProto, *WithoutProto;
4190 if (New->hasWrittenPrototype()) {
4191 WithProto = New;
4192 WithoutProto = Old;
4193 } else {
4194 WithProto = Old;
4195 WithoutProto = New;
4196 }
4197
4198 if (WithProto->getNumParams() != 0) {
4199 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4200 // The one without the prototype will be changing behavior in C23, so
4201 // warn about that one so long as it's a user-visible declaration.
4202 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4203 if (WithoutProto == New)
4204 IsWithoutProtoADef = NewDeclIsDefn;
4205 else
4206 IsWithProtoADef = NewDeclIsDefn;
4207 Diag(WithoutProto->getLocation(),
4208 diag::warn_non_prototype_changes_behavior)
4209 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4210 << (WithoutProto == Old) << IsWithProtoADef;
4211
4212 // The reason the one without the prototype will be changing behavior
4213 // is because of the one with the prototype, so note that so long as
4214 // it's a user-visible declaration. There is one exception to this:
4215 // when the new declaration is a definition without a prototype, the
4216 // old declaration with a prototype is not the cause of the issue,
4217 // and that does not need to be noted because the one with a
4218 // prototype will not change behavior in C23.
4219 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4220 !IsWithoutProtoADef)
4221 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4222 }
4223 }
4224 }
4225
4226 if (Context.typesAreCompatible(T1: OldQType, T2: NewQType)) {
4227 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4228 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4229 const FunctionProtoType *OldProto = nullptr;
4230 if (MergeTypeWithOld && isa<FunctionNoProtoType>(Val: NewFuncType) &&
4231 (OldProto = dyn_cast<FunctionProtoType>(Val: OldFuncType))) {
4232 // The old declaration provided a function prototype, but the
4233 // new declaration does not. Merge in the prototype.
4234 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4235 NewQType = Context.getFunctionType(ResultTy: NewFuncType->getReturnType(),
4236 Args: OldProto->getParamTypes(),
4237 EPI: OldProto->getExtProtoInfo());
4238 New->setType(NewQType);
4239 New->setHasInheritedPrototype();
4240
4241 // Synthesize parameters with the same types.
4242 SmallVector<ParmVarDecl *, 16> Params;
4243 for (const auto &ParamType : OldProto->param_types()) {
4244 ParmVarDecl *Param = ParmVarDecl::Create(
4245 Context, New, SourceLocation(), SourceLocation(), nullptr,
4246 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4247 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
4248 Param->setImplicit();
4249 Params.push_back(Elt: Param);
4250 }
4251
4252 New->setParams(Params);
4253 }
4254
4255 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4256 }
4257 }
4258
4259 // Check if the function types are compatible when pointer size address
4260 // spaces are ignored.
4261 if (Context.hasSameFunctionTypeIgnoringPtrSizes(T: OldQType, U: NewQType))
4262 return false;
4263
4264 // GNU C permits a K&R definition to follow a prototype declaration
4265 // if the declared types of the parameters in the K&R definition
4266 // match the types in the prototype declaration, even when the
4267 // promoted types of the parameters from the K&R definition differ
4268 // from the types in the prototype. GCC then keeps the types from
4269 // the prototype.
4270 //
4271 // If a variadic prototype is followed by a non-variadic K&R definition,
4272 // the K&R definition becomes variadic. This is sort of an edge case, but
4273 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4274 // C99 6.9.1p8.
4275 if (!getLangOpts().CPlusPlus &&
4276 Old->hasPrototype() && !New->hasPrototype() &&
4277 New->getType()->getAs<FunctionProtoType>() &&
4278 Old->getNumParams() == New->getNumParams()) {
4279 SmallVector<QualType, 16> ArgTypes;
4280 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4281 const FunctionProtoType *OldProto
4282 = Old->getType()->getAs<FunctionProtoType>();
4283 const FunctionProtoType *NewProto
4284 = New->getType()->getAs<FunctionProtoType>();
4285
4286 // Determine whether this is the GNU C extension.
4287 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4288 NewProto->getReturnType());
4289 bool LooseCompatible = !MergedReturn.isNull();
4290 for (unsigned Idx = 0, End = Old->getNumParams();
4291 LooseCompatible && Idx != End; ++Idx) {
4292 ParmVarDecl *OldParm = Old->getParamDecl(i: Idx);
4293 ParmVarDecl *NewParm = New->getParamDecl(i: Idx);
4294 if (Context.typesAreCompatible(T1: OldParm->getType(),
4295 T2: NewProto->getParamType(i: Idx))) {
4296 ArgTypes.push_back(Elt: NewParm->getType());
4297 } else if (Context.typesAreCompatible(T1: OldParm->getType(),
4298 T2: NewParm->getType(),
4299 /*CompareUnqualified=*/true)) {
4300 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4301 NewProto->getParamType(i: Idx) };
4302 Warnings.push_back(Elt: Warn);
4303 ArgTypes.push_back(Elt: NewParm->getType());
4304 } else
4305 LooseCompatible = false;
4306 }
4307
4308 if (LooseCompatible) {
4309 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4310 Diag(Warnings[Warn].NewParm->getLocation(),
4311 diag::ext_param_promoted_not_compatible_with_prototype)
4312 << Warnings[Warn].PromotedType
4313 << Warnings[Warn].OldParm->getType();
4314 if (Warnings[Warn].OldParm->getLocation().isValid())
4315 Diag(Warnings[Warn].OldParm->getLocation(),
4316 diag::note_previous_declaration);
4317 }
4318
4319 if (MergeTypeWithOld)
4320 New->setType(Context.getFunctionType(ResultTy: MergedReturn, Args: ArgTypes,
4321 EPI: OldProto->getExtProtoInfo()));
4322 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4323 }
4324
4325 // Fall through to diagnose conflicting types.
4326 }
4327
4328 // A function that has already been declared has been redeclared or
4329 // defined with a different type; show an appropriate diagnostic.
4330
4331 // If the previous declaration was an implicitly-generated builtin
4332 // declaration, then at the very least we should use a specialized note.
4333 unsigned BuiltinID;
4334 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4335 // If it's actually a library-defined builtin function like 'malloc'
4336 // or 'printf', just warn about the incompatible redeclaration.
4337 if (Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) {
4338 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4339 Diag(OldLocation, diag::note_previous_builtin_declaration)
4340 << Old << Old->getType();
4341 return false;
4342 }
4343
4344 PrevDiag = diag::note_previous_builtin_declaration;
4345 }
4346
4347 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4348 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4349 return true;
4350}
4351
4352/// Completes the merge of two function declarations that are
4353/// known to be compatible.
4354///
4355/// This routine handles the merging of attributes and other
4356/// properties of function declarations from the old declaration to
4357/// the new declaration, once we know that New is in fact a
4358/// redeclaration of Old.
4359///
4360/// \returns false
4361bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4362 Scope *S, bool MergeTypeWithOld) {
4363 // Merge the attributes
4364 mergeDeclAttributes(New, Old);
4365
4366 // Merge "pure" flag.
4367 if (Old->isPureVirtual())
4368 New->setIsPureVirtual();
4369
4370 // Merge "used" flag.
4371 if (Old->getMostRecentDecl()->isUsed(false))
4372 New->setIsUsed();
4373
4374 // Merge attributes from the parameters. These can mismatch with K&R
4375 // declarations.
4376 if (New->getNumParams() == Old->getNumParams())
4377 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4378 ParmVarDecl *NewParam = New->getParamDecl(i);
4379 ParmVarDecl *OldParam = Old->getParamDecl(i);
4380 mergeParamDeclAttributes(newDecl: NewParam, oldDecl: OldParam, S&: *this);
4381 mergeParamDeclTypes(NewParam, OldParam, S&: *this);
4382 }
4383
4384 if (getLangOpts().CPlusPlus)
4385 return MergeCXXFunctionDecl(New, Old, S);
4386
4387 // Merge the function types so the we get the composite types for the return
4388 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4389 // was visible.
4390 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4391 if (!Merged.isNull() && MergeTypeWithOld)
4392 New->setType(Merged);
4393
4394 return false;
4395}
4396
4397void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4398 ObjCMethodDecl *oldMethod) {
4399 // Merge the attributes, including deprecated/unavailable
4400 AvailabilityMergeKind MergeKind =
4401 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4402 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4403 : AMK_ProtocolImplementation)
4404 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4405 : AMK_Override;
4406
4407 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4408
4409 // Merge attributes from the parameters.
4410 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4411 oe = oldMethod->param_end();
4412 for (ObjCMethodDecl::param_iterator
4413 ni = newMethod->param_begin(), ne = newMethod->param_end();
4414 ni != ne && oi != oe; ++ni, ++oi)
4415 mergeParamDeclAttributes(newDecl: *ni, oldDecl: *oi, S&: *this);
4416
4417 CheckObjCMethodOverride(NewMethod: newMethod, Overridden: oldMethod);
4418}
4419
4420static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4421 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4422
4423 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4424 ? diag::err_redefinition_different_type
4425 : diag::err_redeclaration_different_type)
4426 << New->getDeclName() << New->getType() << Old->getType();
4427
4428 diag::kind PrevDiag;
4429 SourceLocation OldLocation;
4430 std::tie(args&: PrevDiag, args&: OldLocation)
4431 = getNoteDiagForInvalidRedeclaration(Old, New);
4432 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4433 New->setInvalidDecl();
4434}
4435
4436/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4437/// scope as a previous declaration 'Old'. Figure out how to merge their types,
4438/// emitting diagnostics as appropriate.
4439///
4440/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4441/// to here in AddInitializerToDecl. We can't check them before the initializer
4442/// is attached.
4443void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4444 bool MergeTypeWithOld) {
4445 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4446 return;
4447
4448 QualType MergedT;
4449 if (getLangOpts().CPlusPlus) {
4450 if (New->getType()->isUndeducedType()) {
4451 // We don't know what the new type is until the initializer is attached.
4452 return;
4453 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4454 // These could still be something that needs exception specs checked.
4455 return MergeVarDeclExceptionSpecs(New, Old);
4456 }
4457 // C++ [basic.link]p10:
4458 // [...] the types specified by all declarations referring to a given
4459 // object or function shall be identical, except that declarations for an
4460 // array object can specify array types that differ by the presence or
4461 // absence of a major array bound (8.3.4).
4462 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4463 const ArrayType *OldArray = Context.getAsArrayType(T: Old->getType());
4464 const ArrayType *NewArray = Context.getAsArrayType(T: New->getType());
4465
4466 // We are merging a variable declaration New into Old. If it has an array
4467 // bound, and that bound differs from Old's bound, we should diagnose the
4468 // mismatch.
4469 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4470 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4471 PrevVD = PrevVD->getPreviousDecl()) {
4472 QualType PrevVDTy = PrevVD->getType();
4473 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4474 continue;
4475
4476 if (!Context.hasSameType(New->getType(), PrevVDTy))
4477 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old: PrevVD);
4478 }
4479 }
4480
4481 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4482 if (Context.hasSameType(T1: OldArray->getElementType(),
4483 T2: NewArray->getElementType()))
4484 MergedT = New->getType();
4485 }
4486 // FIXME: Check visibility. New is hidden but has a complete type. If New
4487 // has no array bound, it should not inherit one from Old, if Old is not
4488 // visible.
4489 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4490 if (Context.hasSameType(T1: OldArray->getElementType(),
4491 T2: NewArray->getElementType()))
4492 MergedT = Old->getType();
4493 }
4494 }
4495 else if (New->getType()->isObjCObjectPointerType() &&
4496 Old->getType()->isObjCObjectPointerType()) {
4497 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4498 Old->getType());
4499 }
4500 } else {
4501 // C 6.2.7p2:
4502 // All declarations that refer to the same object or function shall have
4503 // compatible type.
4504 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4505 }
4506 if (MergedT.isNull()) {
4507 // It's OK if we couldn't merge types if either type is dependent, for a
4508 // block-scope variable. In other cases (static data members of class
4509 // templates, variable templates, ...), we require the types to be
4510 // equivalent.
4511 // FIXME: The C++ standard doesn't say anything about this.
4512 if ((New->getType()->isDependentType() ||
4513 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4514 // If the old type was dependent, we can't merge with it, so the new type
4515 // becomes dependent for now. We'll reproduce the original type when we
4516 // instantiate the TypeSourceInfo for the variable.
4517 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4518 New->setType(Context.DependentTy);
4519 return;
4520 }
4521 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old);
4522 }
4523
4524 // Don't actually update the type on the new declaration if the old
4525 // declaration was an extern declaration in a different scope.
4526 if (MergeTypeWithOld)
4527 New->setType(MergedT);
4528}
4529
4530static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4531 LookupResult &Previous) {
4532 // C11 6.2.7p4:
4533 // For an identifier with internal or external linkage declared
4534 // in a scope in which a prior declaration of that identifier is
4535 // visible, if the prior declaration specifies internal or
4536 // external linkage, the type of the identifier at the later
4537 // declaration becomes the composite type.
4538 //
4539 // If the variable isn't visible, we do not merge with its type.
4540 if (Previous.isShadowed())
4541 return false;
4542
4543 if (S.getLangOpts().CPlusPlus) {
4544 // C++11 [dcl.array]p3:
4545 // If there is a preceding declaration of the entity in the same
4546 // scope in which the bound was specified, an omitted array bound
4547 // is taken to be the same as in that earlier declaration.
4548 return NewVD->isPreviousDeclInSameBlockScope() ||
4549 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4550 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4551 } else {
4552 // If the old declaration was function-local, don't merge with its
4553 // type unless we're in the same function.
4554 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4555 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4556 }
4557}
4558
4559/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4560/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4561/// situation, merging decls or emitting diagnostics as appropriate.
4562///
4563/// Tentative definition rules (C99 6.9.2p2) are checked by
4564/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4565/// definitions here, since the initializer hasn't been attached.
4566///
4567void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4568 // If the new decl is already invalid, don't do any other checking.
4569 if (New->isInvalidDecl())
4570 return;
4571
4572 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4573 return;
4574
4575 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4576
4577 // Verify the old decl was also a variable or variable template.
4578 VarDecl *Old = nullptr;
4579 VarTemplateDecl *OldTemplate = nullptr;
4580 if (Previous.isSingleResult()) {
4581 if (NewTemplate) {
4582 OldTemplate = dyn_cast<VarTemplateDecl>(Val: Previous.getFoundDecl());
4583 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4584
4585 if (auto *Shadow =
4586 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4587 if (checkUsingShadowRedecl<VarTemplateDecl>(S&: *this, OldS: Shadow, New: NewTemplate))
4588 return New->setInvalidDecl();
4589 } else {
4590 Old = dyn_cast<VarDecl>(Val: Previous.getFoundDecl());
4591
4592 if (auto *Shadow =
4593 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4594 if (checkUsingShadowRedecl<VarDecl>(S&: *this, OldS: Shadow, New))
4595 return New->setInvalidDecl();
4596 }
4597 }
4598 if (!Old) {
4599 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4600 << New->getDeclName();
4601 notePreviousDefinition(Old: Previous.getRepresentativeDecl(),
4602 New: New->getLocation());
4603 return New->setInvalidDecl();
4604 }
4605
4606 // If the old declaration was found in an inline namespace and the new
4607 // declaration was qualified, update the DeclContext to match.
4608 adjustDeclContextForDeclaratorDecl(New, Old);
4609
4610 // Ensure the template parameters are compatible.
4611 if (NewTemplate &&
4612 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4613 OldTemplate->getTemplateParameters(),
4614 /*Complain=*/true, TPL_TemplateMatch))
4615 return New->setInvalidDecl();
4616
4617 // C++ [class.mem]p1:
4618 // A member shall not be declared twice in the member-specification [...]
4619 //
4620 // Here, we need only consider static data members.
4621 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4622 Diag(New->getLocation(), diag::err_duplicate_member)
4623 << New->getIdentifier();
4624 Diag(Old->getLocation(), diag::note_previous_declaration);
4625 New->setInvalidDecl();
4626 }
4627
4628 mergeDeclAttributes(New, Old);
4629 // Warn if an already-declared variable is made a weak_import in a subsequent
4630 // declaration
4631 if (New->hasAttr<WeakImportAttr>() &&
4632 Old->getStorageClass() == SC_None &&
4633 !Old->hasAttr<WeakImportAttr>()) {
4634 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4635 Diag(Old->getLocation(), diag::note_previous_declaration);
4636 // Remove weak_import attribute on new declaration.
4637 New->dropAttr<WeakImportAttr>();
4638 }
4639
4640 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4641 if (!Old->hasAttr<InternalLinkageAttr>()) {
4642 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4643 << ILA;
4644 Diag(Old->getLocation(), diag::note_previous_declaration);
4645 New->dropAttr<InternalLinkageAttr>();
4646 }
4647
4648 // Merge the types.
4649 VarDecl *MostRecent = Old->getMostRecentDecl();
4650 if (MostRecent != Old) {
4651 MergeVarDeclTypes(New, Old: MostRecent,
4652 MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: MostRecent, Previous));
4653 if (New->isInvalidDecl())
4654 return;
4655 }
4656
4657 MergeVarDeclTypes(New, Old, MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: Old, Previous));
4658 if (New->isInvalidDecl())
4659 return;
4660
4661 diag::kind PrevDiag;
4662 SourceLocation OldLocation;
4663 std::tie(args&: PrevDiag, args&: OldLocation) =
4664 getNoteDiagForInvalidRedeclaration(Old, New);
4665
4666 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4667 if (New->getStorageClass() == SC_Static &&
4668 !New->isStaticDataMember() &&
4669 Old->hasExternalFormalLinkage()) {
4670 if (getLangOpts().MicrosoftExt) {
4671 Diag(New->getLocation(), diag::ext_static_non_static)
4672 << New->getDeclName();
4673 Diag(OldLocation, PrevDiag);
4674 } else {
4675 Diag(New->getLocation(), diag::err_static_non_static)
4676 << New->getDeclName();
4677 Diag(OldLocation, PrevDiag);
4678 return New->setInvalidDecl();
4679 }
4680 }
4681 // C99 6.2.2p4:
4682 // For an identifier declared with the storage-class specifier
4683 // extern in a scope in which a prior declaration of that
4684 // identifier is visible,23) if the prior declaration specifies
4685 // internal or external linkage, the linkage of the identifier at
4686 // the later declaration is the same as the linkage specified at
4687 // the prior declaration. If no prior declaration is visible, or
4688 // if the prior declaration specifies no linkage, then the
4689 // identifier has external linkage.
4690 if (New->hasExternalStorage() && Old->hasLinkage())
4691 /* Okay */;
4692 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4693 !New->isStaticDataMember() &&
4694 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4695 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4696 Diag(OldLocation, PrevDiag);
4697 return New->setInvalidDecl();
4698 }
4699
4700 // Check if extern is followed by non-extern and vice-versa.
4701 if (New->hasExternalStorage() &&
4702 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4703 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4704 Diag(OldLocation, PrevDiag);
4705 return New->setInvalidDecl();
4706 }
4707 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4708 !New->hasExternalStorage()) {
4709 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4710 Diag(OldLocation, PrevDiag);
4711 return New->setInvalidDecl();
4712 }
4713
4714 if (CheckRedeclarationInModule(New, Old))
4715 return;
4716
4717 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4718
4719 // FIXME: The test for external storage here seems wrong? We still
4720 // need to check for mismatches.
4721 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4722 // Don't complain about out-of-line definitions of static members.
4723 !(Old->getLexicalDeclContext()->isRecord() &&
4724 !New->getLexicalDeclContext()->isRecord())) {
4725 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4726 Diag(OldLocation, PrevDiag);
4727 return New->setInvalidDecl();
4728 }
4729
4730 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4731 if (VarDecl *Def = Old->getDefinition()) {
4732 // C++1z [dcl.fcn.spec]p4:
4733 // If the definition of a variable appears in a translation unit before
4734 // its first declaration as inline, the program is ill-formed.
4735 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4736 Diag(Def->getLocation(), diag::note_previous_definition);
4737 }
4738 }
4739
4740 // If this redeclaration makes the variable inline, we may need to add it to
4741 // UndefinedButUsed.
4742 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4743 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4744 UndefinedButUsed.insert(std::make_pair(x: Old->getCanonicalDecl(),
4745 y: SourceLocation()));
4746
4747 if (New->getTLSKind() != Old->getTLSKind()) {
4748 if (!Old->getTLSKind()) {
4749 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4750 Diag(OldLocation, PrevDiag);
4751 } else if (!New->getTLSKind()) {
4752 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4753 Diag(OldLocation, PrevDiag);
4754 } else {
4755 // Do not allow redeclaration to change the variable between requiring
4756 // static and dynamic initialization.
4757 // FIXME: GCC allows this, but uses the TLS keyword on the first
4758 // declaration to determine the kind. Do we need to be compatible here?
4759 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4760 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4761 Diag(OldLocation, PrevDiag);
4762 }
4763 }
4764
4765 // C++ doesn't have tentative definitions, so go right ahead and check here.
4766 if (getLangOpts().CPlusPlus) {
4767 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4768 Old->getCanonicalDecl()->isConstexpr()) {
4769 // This definition won't be a definition any more once it's been merged.
4770 Diag(New->getLocation(),
4771 diag::warn_deprecated_redundant_constexpr_static_def);
4772 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4773 VarDecl *Def = Old->getDefinition();
4774 if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New))
4775 return;
4776 }
4777 }
4778
4779 if (haveIncompatibleLanguageLinkages(Old, New)) {
4780 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4781 Diag(OldLocation, PrevDiag);
4782 New->setInvalidDecl();
4783 return;
4784 }
4785
4786 // Merge "used" flag.
4787 if (Old->getMostRecentDecl()->isUsed(false))
4788 New->setIsUsed();
4789
4790 // Keep a chain of previous declarations.
4791 New->setPreviousDecl(Old);
4792 if (NewTemplate)
4793 NewTemplate->setPreviousDecl(OldTemplate);
4794
4795 // Inherit access appropriately.
4796 New->setAccess(Old->getAccess());
4797 if (NewTemplate)
4798 NewTemplate->setAccess(New->getAccess());
4799
4800 if (Old->isInline())
4801 New->setImplicitlyInline();
4802}
4803
4804void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4805 SourceManager &SrcMgr = getSourceManager();
4806 auto FNewDecLoc = SrcMgr.getDecomposedLoc(Loc: New);
4807 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Loc: Old->getLocation());
4808 auto *FNew = SrcMgr.getFileEntryForID(FID: FNewDecLoc.first);
4809 auto FOld = SrcMgr.getFileEntryRefForID(FID: FOldDecLoc.first);
4810 auto &HSI = PP.getHeaderSearchInfo();
4811 StringRef HdrFilename =
4812 SrcMgr.getFilename(SpellingLoc: SrcMgr.getSpellingLoc(Loc: Old->getLocation()));
4813
4814 auto noteFromModuleOrInclude = [&](Module *Mod,
4815 SourceLocation IncLoc) -> bool {
4816 // Redefinition errors with modules are common with non modular mapped
4817 // headers, example: a non-modular header H in module A that also gets
4818 // included directly in a TU. Pointing twice to the same header/definition
4819 // is confusing, try to get better diagnostics when modules is on.
4820 if (IncLoc.isValid()) {
4821 if (Mod) {
4822 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4823 << HdrFilename.str() << Mod->getFullModuleName();
4824 if (!Mod->DefinitionLoc.isInvalid())
4825 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4826 << Mod->getFullModuleName();
4827 } else {
4828 Diag(IncLoc, diag::note_redefinition_include_same_file)
4829 << HdrFilename.str();
4830 }
4831 return true;
4832 }
4833
4834 return false;
4835 };
4836
4837 // Is it the same file and same offset? Provide more information on why
4838 // this leads to a redefinition error.
4839 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4840 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FID: FOldDecLoc.first);
4841 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FID: FNewDecLoc.first);
4842 bool EmittedDiag =
4843 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4844 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4845
4846 // If the header has no guards, emit a note suggesting one.
4847 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4848 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4849
4850 if (EmittedDiag)
4851 return;
4852 }
4853
4854 // Redefinition coming from different files or couldn't do better above.
4855 if (Old->getLocation().isValid())
4856 Diag(Old->getLocation(), diag::note_previous_definition);
4857}
4858
4859/// We've just determined that \p Old and \p New both appear to be definitions
4860/// of the same variable. Either diagnose or fix the problem.
4861bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4862 if (!hasVisibleDefinition(Old) &&
4863 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4864 isa<VarTemplateSpecializationDecl>(Val: New) ||
4865 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4866 New->getDeclContext()->isDependentContext())) {
4867 // The previous definition is hidden, and multiple definitions are
4868 // permitted (in separate TUs). Demote this to a declaration.
4869 New->demoteThisDefinitionToDeclaration();
4870
4871 // Make the canonical definition visible.
4872 if (auto *OldTD = Old->getDescribedVarTemplate())
4873 makeMergedDefinitionVisible(OldTD);
4874 makeMergedDefinitionVisible(Old);
4875 return false;
4876 } else {
4877 Diag(New->getLocation(), diag::err_redefinition) << New;
4878 notePreviousDefinition(Old, New: New->getLocation());
4879 New->setInvalidDecl();
4880 return true;
4881 }
4882}
4883
4884/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4885/// no declarator (e.g. "struct foo;") is parsed.
4886Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4887 DeclSpec &DS,
4888 const ParsedAttributesView &DeclAttrs,
4889 RecordDecl *&AnonRecord) {
4890 return ParsedFreeStandingDeclSpec(
4891 S, AS, DS, DeclAttrs, TemplateParams: MultiTemplateParamsArg(), IsExplicitInstantiation: false, AnonRecord);
4892}
4893
4894// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4895// disambiguate entities defined in different scopes.
4896// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4897// compatibility.
4898// We will pick our mangling number depending on which version of MSVC is being
4899// targeted.
4900static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4901 return LO.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015)
4902 ? S->getMSCurManglingNumber()
4903 : S->getMSLastManglingNumber();
4904}
4905
4906void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4907 if (!Context.getLangOpts().CPlusPlus)
4908 return;
4909
4910 if (isa<CXXRecordDecl>(Tag->getParent())) {
4911 // If this tag is the direct child of a class, number it if
4912 // it is anonymous.
4913 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4914 return;
4915 MangleNumberingContext &MCtx =
4916 Context.getManglingNumberContext(Tag->getParent());
4917 Context.setManglingNumber(
4918 Tag, MCtx.getManglingNumber(
4919 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
4920 return;
4921 }
4922
4923 // If this tag isn't a direct child of a class, number it if it is local.
4924 MangleNumberingContext *MCtx;
4925 Decl *ManglingContextDecl;
4926 std::tie(args&: MCtx, args&: ManglingContextDecl) =
4927 getCurrentMangleNumberContext(DC: Tag->getDeclContext());
4928 if (MCtx) {
4929 Context.setManglingNumber(
4930 Tag, MCtx->getManglingNumber(
4931 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
4932 }
4933}
4934
4935namespace {
4936struct NonCLikeKind {
4937 enum {
4938 None,
4939 BaseClass,
4940 DefaultMemberInit,
4941 Lambda,
4942 Friend,
4943 OtherMember,
4944 Invalid,
4945 } Kind = None;
4946 SourceRange Range;
4947
4948 explicit operator bool() { return Kind != None; }
4949};
4950}
4951
4952/// Determine whether a class is C-like, according to the rules of C++
4953/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4954static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4955 if (RD->isInvalidDecl())
4956 return {.Kind: NonCLikeKind::Invalid, .Range: {}};
4957
4958 // C++ [dcl.typedef]p9: [P1766R1]
4959 // An unnamed class with a typedef name for linkage purposes shall not
4960 //
4961 // -- have any base classes
4962 if (RD->getNumBases())
4963 return {.Kind: NonCLikeKind::BaseClass,
4964 .Range: SourceRange(RD->bases_begin()->getBeginLoc(),
4965 RD->bases_end()[-1].getEndLoc())};
4966 bool Invalid = false;
4967 for (Decl *D : RD->decls()) {
4968 // Don't complain about things we already diagnosed.
4969 if (D->isInvalidDecl()) {
4970 Invalid = true;
4971 continue;
4972 }
4973
4974 // -- have any [...] default member initializers
4975 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4976 if (FD->hasInClassInitializer()) {
4977 auto *Init = FD->getInClassInitializer();
4978 return {NonCLikeKind::DefaultMemberInit,
4979 Init ? Init->getSourceRange() : D->getSourceRange()};
4980 }
4981 continue;
4982 }
4983
4984 // FIXME: We don't allow friend declarations. This violates the wording of
4985 // P1766, but not the intent.
4986 if (isa<FriendDecl>(D))
4987 return {NonCLikeKind::Friend, D->getSourceRange()};
4988
4989 // -- declare any members other than non-static data members, member
4990 // enumerations, or member classes,
4991 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4992 isa<EnumDecl>(D))
4993 continue;
4994 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4995 if (!MemberRD) {
4996 if (D->isImplicit())
4997 continue;
4998 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4999 }
5000
5001 // -- contain a lambda-expression,
5002 if (MemberRD->isLambda())
5003 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5004
5005 // and all member classes shall also satisfy these requirements
5006 // (recursively).
5007 if (MemberRD->isThisDeclarationADefinition()) {
5008 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5009 return Kind;
5010 }
5011 }
5012
5013 return {.Kind: Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, .Range: {}};
5014}
5015
5016void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5017 TypedefNameDecl *NewTD) {
5018 if (TagFromDeclSpec->isInvalidDecl())
5019 return;
5020
5021 // Do nothing if the tag already has a name for linkage purposes.
5022 if (TagFromDeclSpec->hasNameForLinkage())
5023 return;
5024
5025 // A well-formed anonymous tag must always be a TUK_Definition.
5026 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5027
5028 // The type must match the tag exactly; no qualifiers allowed.
5029 if (!Context.hasSameType(T1: NewTD->getUnderlyingType(),
5030 T2: Context.getTagDeclType(Decl: TagFromDeclSpec))) {
5031 if (getLangOpts().CPlusPlus)
5032 Context.addTypedefNameForUnnamedTagDecl(TD: TagFromDeclSpec, TND: NewTD);
5033 return;
5034 }
5035
5036 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5037 // An unnamed class with a typedef name for linkage purposes shall [be
5038 // C-like].
5039 //
5040 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5041 // shouldn't happen, but there are constructs that the language rule doesn't
5042 // disallow for which we can't reasonably avoid computing linkage early.
5043 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TagFromDeclSpec);
5044 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5045 : NonCLikeKind();
5046 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5047 if (NonCLike || ChangesLinkage) {
5048 if (NonCLike.Kind == NonCLikeKind::Invalid)
5049 return;
5050
5051 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5052 if (ChangesLinkage) {
5053 // If the linkage changes, we can't accept this as an extension.
5054 if (NonCLike.Kind == NonCLikeKind::None)
5055 DiagID = diag::err_typedef_changes_linkage;
5056 else
5057 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5058 }
5059
5060 SourceLocation FixitLoc =
5061 getLocForEndOfToken(Loc: TagFromDeclSpec->getInnerLocStart());
5062 llvm::SmallString<40> TextToInsert;
5063 TextToInsert += ' ';
5064 TextToInsert += NewTD->getIdentifier()->getName();
5065
5066 Diag(FixitLoc, DiagID)
5067 << isa<TypeAliasDecl>(Val: NewTD)
5068 << FixItHint::CreateInsertion(InsertionLoc: FixitLoc, Code: TextToInsert);
5069 if (NonCLike.Kind != NonCLikeKind::None) {
5070 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5071 << NonCLike.Kind - 1 << NonCLike.Range;
5072 }
5073 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5074 << NewTD << isa<TypeAliasDecl>(NewTD);
5075
5076 if (ChangesLinkage)
5077 return;
5078 }
5079
5080 // Otherwise, set this as the anon-decl typedef for the tag.
5081 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5082}
5083
5084static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5085 DeclSpec::TST T = DS.getTypeSpecType();
5086 switch (T) {
5087 case DeclSpec::TST_class:
5088 return 0;
5089 case DeclSpec::TST_struct:
5090 return 1;
5091 case DeclSpec::TST_interface:
5092 return 2;
5093 case DeclSpec::TST_union:
5094 return 3;
5095 case DeclSpec::TST_enum:
5096 if (const auto *ED = dyn_cast<EnumDecl>(Val: DS.getRepAsDecl())) {
5097 if (ED->isScopedUsingClassTag())
5098 return 5;
5099 if (ED->isScoped())
5100 return 6;
5101 }
5102 return 4;
5103 default:
5104 llvm_unreachable("unexpected type specifier");
5105 }
5106}
5107/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5108/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5109/// parameters to cope with template friend declarations.
5110Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5111 DeclSpec &DS,
5112 const ParsedAttributesView &DeclAttrs,
5113 MultiTemplateParamsArg TemplateParams,
5114 bool IsExplicitInstantiation,
5115 RecordDecl *&AnonRecord) {
5116 Decl *TagD = nullptr;
5117 TagDecl *Tag = nullptr;
5118 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5119 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5120 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5121 DS.getTypeSpecType() == DeclSpec::TST_union ||
5122 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5123 TagD = DS.getRepAsDecl();
5124
5125 if (!TagD) // We probably had an error
5126 return nullptr;
5127
5128 // Note that the above type specs guarantee that the
5129 // type rep is a Decl, whereas in many of the others
5130 // it's a Type.
5131 if (isa<TagDecl>(Val: TagD))
5132 Tag = cast<TagDecl>(Val: TagD);
5133 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: TagD))
5134 Tag = CTD->getTemplatedDecl();
5135 }
5136
5137 if (Tag) {
5138 handleTagNumbering(Tag, TagScope: S);
5139 Tag->setFreeStanding();
5140 if (Tag->isInvalidDecl())
5141 return Tag;
5142 }
5143
5144 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5145 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5146 // or incomplete types shall not be restrict-qualified."
5147 if (TypeQuals & DeclSpec::TQ_restrict)
5148 Diag(DS.getRestrictSpecLoc(),
5149 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5150 << DS.getSourceRange();
5151 }
5152
5153 if (DS.isInlineSpecified())
5154 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5155 << getLangOpts().CPlusPlus17;
5156
5157 if (DS.hasConstexprSpecifier()) {
5158 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5159 // and definitions of functions and variables.
5160 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5161 // the declaration of a function or function template
5162 if (Tag)
5163 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5164 << GetDiagnosticTypeSpecifierID(DS)
5165 << static_cast<int>(DS.getConstexprSpecifier());
5166 else if (getLangOpts().C23)
5167 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5168 else
5169 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5170 << static_cast<int>(DS.getConstexprSpecifier());
5171 // Don't emit warnings after this error.
5172 return TagD;
5173 }
5174
5175 DiagnoseFunctionSpecifiers(DS);
5176
5177 if (DS.isFriendSpecified()) {
5178 // If we're dealing with a decl but not a TagDecl, assume that
5179 // whatever routines created it handled the friendship aspect.
5180 if (TagD && !Tag)
5181 return nullptr;
5182 return ActOnFriendTypeDecl(S, DS, TemplateParams);
5183 }
5184
5185 // Track whether this decl-specifier declares anything.
5186 bool DeclaresAnything = true;
5187
5188 // Handle anonymous struct definitions.
5189 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Val: Tag)) {
5190 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5191 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5192 if (getLangOpts().CPlusPlus ||
5193 Record->getDeclContext()->isRecord()) {
5194 // If CurContext is a DeclContext that can contain statements,
5195 // RecursiveASTVisitor won't visit the decls that
5196 // BuildAnonymousStructOrUnion() will put into CurContext.
5197 // Also store them here so that they can be part of the
5198 // DeclStmt that gets created in this case.
5199 // FIXME: Also return the IndirectFieldDecls created by
5200 // BuildAnonymousStructOr union, for the same reason?
5201 if (CurContext->isFunctionOrMethod())
5202 AnonRecord = Record;
5203 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5204 Policy: Context.getPrintingPolicy());
5205 }
5206
5207 DeclaresAnything = false;
5208 }
5209 }
5210
5211 // C11 6.7.2.1p2:
5212 // A struct-declaration that does not declare an anonymous structure or
5213 // anonymous union shall contain a struct-declarator-list.
5214 //
5215 // This rule also existed in C89 and C99; the grammar for struct-declaration
5216 // did not permit a struct-declaration without a struct-declarator-list.
5217 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5218 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5219 // Check for Microsoft C extension: anonymous struct/union member.
5220 // Handle 2 kinds of anonymous struct/union:
5221 // struct STRUCT;
5222 // union UNION;
5223 // and
5224 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5225 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5226 if ((Tag && Tag->getDeclName()) ||
5227 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5228 RecordDecl *Record = nullptr;
5229 if (Tag)
5230 Record = dyn_cast<RecordDecl>(Val: Tag);
5231 else if (const RecordType *RT =
5232 DS.getRepAsType().get()->getAsStructureType())
5233 Record = RT->getDecl();
5234 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5235 Record = UT->getDecl();
5236
5237 if (Record && getLangOpts().MicrosoftExt) {
5238 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5239 << Record->isUnion() << DS.getSourceRange();
5240 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5241 }
5242
5243 DeclaresAnything = false;
5244 }
5245 }
5246
5247 // Skip all the checks below if we have a type error.
5248 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5249 (TagD && TagD->isInvalidDecl()))
5250 return TagD;
5251
5252 if (getLangOpts().CPlusPlus &&
5253 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5254 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Val: Tag))
5255 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5256 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5257 DeclaresAnything = false;
5258
5259 if (!DS.isMissingDeclaratorOk()) {
5260 // Customize diagnostic for a typedef missing a name.
5261 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5262 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5263 << DS.getSourceRange();
5264 else
5265 DeclaresAnything = false;
5266 }
5267
5268 if (DS.isModulePrivateSpecified() &&
5269 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5270 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5271 << llvm::to_underlying(Tag->getTagKind())
5272 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5273
5274 ActOnDocumentableDecl(D: TagD);
5275
5276 // C 6.7/2:
5277 // A declaration [...] shall declare at least a declarator [...], a tag,
5278 // or the members of an enumeration.
5279 // C++ [dcl.dcl]p3:
5280 // [If there are no declarators], and except for the declaration of an
5281 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5282 // names into the program, or shall redeclare a name introduced by a
5283 // previous declaration.
5284 if (!DeclaresAnything) {
5285 // In C, we allow this as a (popular) extension / bug. Don't bother
5286 // producing further diagnostics for redundant qualifiers after this.
5287 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5288 ? diag::err_no_declarators
5289 : diag::ext_no_declarators)
5290 << DS.getSourceRange();
5291 return TagD;
5292 }
5293
5294 // C++ [dcl.stc]p1:
5295 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5296 // init-declarator-list of the declaration shall not be empty.
5297 // C++ [dcl.fct.spec]p1:
5298 // If a cv-qualifier appears in a decl-specifier-seq, the
5299 // init-declarator-list of the declaration shall not be empty.
5300 //
5301 // Spurious qualifiers here appear to be valid in C.
5302 unsigned DiagID = diag::warn_standalone_specifier;
5303 if (getLangOpts().CPlusPlus)
5304 DiagID = diag::ext_standalone_specifier;
5305
5306 // Note that a linkage-specification sets a storage class, but
5307 // 'extern "C" struct foo;' is actually valid and not theoretically
5308 // useless.
5309 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5310 if (SCS == DeclSpec::SCS_mutable)
5311 // Since mutable is not a viable storage class specifier in C, there is
5312 // no reason to treat it as an extension. Instead, diagnose as an error.
5313 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5314 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5315 Diag(DS.getStorageClassSpecLoc(), DiagID)
5316 << DeclSpec::getSpecifierName(S: SCS);
5317 }
5318
5319 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5320 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5321 << DeclSpec::getSpecifierName(S: TSCS);
5322 if (DS.getTypeQualifiers()) {
5323 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5324 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5325 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5326 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5327 // Restrict is covered above.
5328 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5329 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5330 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5331 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5332 }
5333
5334 // Warn about ignored type attributes, for example:
5335 // __attribute__((aligned)) struct A;
5336 // Attributes should be placed after tag to apply to type declaration.
5337 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5338 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5339 if (TypeSpecType == DeclSpec::TST_class ||
5340 TypeSpecType == DeclSpec::TST_struct ||
5341 TypeSpecType == DeclSpec::TST_interface ||
5342 TypeSpecType == DeclSpec::TST_union ||
5343 TypeSpecType == DeclSpec::TST_enum) {
5344
5345 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5346 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5347 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5348 DiagnosticId = diag::warn_attribute_ignored;
5349 else if (AL.isRegularKeywordAttribute())
5350 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5351 else
5352 DiagnosticId = diag::warn_declspec_attribute_ignored;
5353 Diag(AL.getLoc(), DiagnosticId)
5354 << AL << GetDiagnosticTypeSpecifierID(DS);
5355 };
5356
5357 llvm::for_each(Range&: DS.getAttributes(), F: EmitAttributeDiagnostic);
5358 llvm::for_each(Range: DeclAttrs, F: EmitAttributeDiagnostic);
5359 }
5360 }
5361
5362 return TagD;
5363}
5364
5365/// We are trying to inject an anonymous member into the given scope;
5366/// check if there's an existing declaration that can't be overloaded.
5367///
5368/// \return true if this is a forbidden redeclaration
5369static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5370 DeclContext *Owner,
5371 DeclarationName Name,
5372 SourceLocation NameLoc, bool IsUnion,
5373 StorageClass SC) {
5374 LookupResult R(SemaRef, Name, NameLoc,
5375 Owner->isRecord() ? Sema::LookupMemberName
5376 : Sema::LookupOrdinaryName,
5377 RedeclarationKind::ForVisibleRedeclaration);
5378 if (!SemaRef.LookupName(R, S)) return false;
5379
5380 // Pick a representative declaration.
5381 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5382 assert(PrevDecl && "Expected a non-null Decl");
5383
5384 if (!SemaRef.isDeclInScope(D: PrevDecl, Ctx: Owner, S))
5385 return false;
5386
5387 if (SC == StorageClass::SC_None &&
5388 PrevDecl->isPlaceholderVar(LangOpts: SemaRef.getLangOpts()) &&
5389 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5390 if (!Owner->isRecord())
5391 SemaRef.DiagPlaceholderVariableDefinition(Loc: NameLoc);
5392 return false;
5393 }
5394
5395 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5396 << IsUnion << Name;
5397 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5398
5399 return true;
5400}
5401
5402void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5403 if (auto *RD = dyn_cast_if_present<RecordDecl>(Val: D))
5404 DiagPlaceholderFieldDeclDefinitions(Record: RD);
5405}
5406
5407/// Emit diagnostic warnings for placeholder members.
5408/// We can only do that after the class is fully constructed,
5409/// as anonymous union/structs can insert placeholders
5410/// in their parent scope (which might be a Record).
5411void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5412 if (!getLangOpts().CPlusPlus)
5413 return;
5414
5415 // This function can be parsed before we have validated the
5416 // structure as an anonymous struct
5417 if (Record->isAnonymousStructOrUnion())
5418 return;
5419
5420 const NamedDecl *First = 0;
5421 for (const Decl *D : Record->decls()) {
5422 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5423 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5424 continue;
5425 if (!First)
5426 First = ND;
5427 else
5428 DiagPlaceholderVariableDefinition(ND->getLocation());
5429 }
5430}
5431
5432/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5433/// anonymous struct or union AnonRecord into the owning context Owner
5434/// and scope S. This routine will be invoked just after we realize
5435/// that an unnamed union or struct is actually an anonymous union or
5436/// struct, e.g.,
5437///
5438/// @code
5439/// union {
5440/// int i;
5441/// float f;
5442/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5443/// // f into the surrounding scope.x
5444/// @endcode
5445///
5446/// This routine is recursive, injecting the names of nested anonymous
5447/// structs/unions into the owning context and scope as well.
5448static bool
5449InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5450 RecordDecl *AnonRecord, AccessSpecifier AS,
5451 StorageClass SC,
5452 SmallVectorImpl<NamedDecl *> &Chaining) {
5453 bool Invalid = false;
5454
5455 // Look every FieldDecl and IndirectFieldDecl with a name.
5456 for (auto *D : AnonRecord->decls()) {
5457 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5458 cast<NamedDecl>(D)->getDeclName()) {
5459 ValueDecl *VD = cast<ValueDecl>(D);
5460 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5461 VD->getLocation(), AnonRecord->isUnion(),
5462 SC)) {
5463 // C++ [class.union]p2:
5464 // The names of the members of an anonymous union shall be
5465 // distinct from the names of any other entity in the
5466 // scope in which the anonymous union is declared.
5467 Invalid = true;
5468 } else {
5469 // C++ [class.union]p2:
5470 // For the purpose of name lookup, after the anonymous union
5471 // definition, the members of the anonymous union are
5472 // considered to have been defined in the scope in which the
5473 // anonymous union is declared.
5474 unsigned OldChainingSize = Chaining.size();
5475 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5476 Chaining.append(IF->chain_begin(), IF->chain_end());
5477 else
5478 Chaining.push_back(VD);
5479
5480 assert(Chaining.size() >= 2);
5481 NamedDecl **NamedChain =
5482 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5483 for (unsigned i = 0; i < Chaining.size(); i++)
5484 NamedChain[i] = Chaining[i];
5485
5486 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5487 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5488 VD->getType(), {NamedChain, Chaining.size()});
5489
5490 for (const auto *Attr : VD->attrs())
5491 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5492
5493 IndirectField->setAccess(AS);
5494 IndirectField->setImplicit();
5495 SemaRef.PushOnScopeChains(IndirectField, S);
5496
5497 // That includes picking up the appropriate access specifier.
5498 if (AS != AS_none) IndirectField->setAccess(AS);
5499
5500 Chaining.resize(OldChainingSize);
5501 }
5502 }
5503 }
5504
5505 return Invalid;
5506}
5507
5508/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5509/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5510/// illegal input values are mapped to SC_None.
5511static StorageClass
5512StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5513 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5514 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5515 "Parser allowed 'typedef' as storage class VarDecl.");
5516 switch (StorageClassSpec) {
5517 case DeclSpec::SCS_unspecified: return SC_None;
5518 case DeclSpec::SCS_extern:
5519 if (DS.isExternInLinkageSpec())
5520 return SC_None;
5521 return SC_Extern;
5522 case DeclSpec::SCS_static: return SC_Static;
5523 case DeclSpec::SCS_auto: return SC_Auto;
5524 case DeclSpec::SCS_register: return SC_Register;
5525 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5526 // Illegal SCSs map to None: error reporting is up to the caller.
5527 case DeclSpec::SCS_mutable: // Fall through.
5528 case DeclSpec::SCS_typedef: return SC_None;
5529 }
5530 llvm_unreachable("unknown storage class specifier");
5531}
5532
5533static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5534 assert(Record->hasInClassInitializer());
5535
5536 for (const auto *I : Record->decls()) {
5537 const auto *FD = dyn_cast<FieldDecl>(I);
5538 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5539 FD = IFD->getAnonField();
5540 if (FD && FD->hasInClassInitializer())
5541 return FD->getLocation();
5542 }
5543
5544 llvm_unreachable("couldn't find in-class initializer");
5545}
5546
5547static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5548 SourceLocation DefaultInitLoc) {
5549 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5550 return;
5551
5552 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5553 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5554}
5555
5556static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5557 CXXRecordDecl *AnonUnion) {
5558 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5559 return;
5560
5561 checkDuplicateDefaultInit(S, Parent, DefaultInitLoc: findDefaultInitializer(Record: AnonUnion));
5562}
5563
5564/// BuildAnonymousStructOrUnion - Handle the declaration of an
5565/// anonymous structure or union. Anonymous unions are a C++ feature
5566/// (C++ [class.union]) and a C11 feature; anonymous structures
5567/// are a C11 feature and GNU C++ extension.
5568Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5569 AccessSpecifier AS,
5570 RecordDecl *Record,
5571 const PrintingPolicy &Policy) {
5572 DeclContext *Owner = Record->getDeclContext();
5573
5574 // Diagnose whether this anonymous struct/union is an extension.
5575 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5576 Diag(Record->getLocation(), diag::ext_anonymous_union);
5577 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5578 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5579 else if (!Record->isUnion() && !getLangOpts().C11)
5580 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5581
5582 // C and C++ require different kinds of checks for anonymous
5583 // structs/unions.
5584 bool Invalid = false;
5585 if (getLangOpts().CPlusPlus) {
5586 const char *PrevSpec = nullptr;
5587 if (Record->isUnion()) {
5588 // C++ [class.union]p6:
5589 // C++17 [class.union.anon]p2:
5590 // Anonymous unions declared in a named namespace or in the
5591 // global namespace shall be declared static.
5592 unsigned DiagID;
5593 DeclContext *OwnerScope = Owner->getRedeclContext();
5594 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5595 (OwnerScope->isTranslationUnit() ||
5596 (OwnerScope->isNamespace() &&
5597 !cast<NamespaceDecl>(Val: OwnerScope)->isAnonymousNamespace()))) {
5598 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5599 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5600
5601 // Recover by adding 'static'.
5602 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_static, Loc: SourceLocation(),
5603 PrevSpec, DiagID, Policy);
5604 }
5605 // C++ [class.union]p6:
5606 // A storage class is not allowed in a declaration of an
5607 // anonymous union in a class scope.
5608 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5609 isa<RecordDecl>(Val: Owner)) {
5610 Diag(DS.getStorageClassSpecLoc(),
5611 diag::err_anonymous_union_with_storage_spec)
5612 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5613
5614 // Recover by removing the storage specifier.
5615 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_unspecified,
5616 Loc: SourceLocation(),
5617 PrevSpec, DiagID, Policy: Context.getPrintingPolicy());
5618 }
5619 }
5620
5621 // Ignore const/volatile/restrict qualifiers.
5622 if (DS.getTypeQualifiers()) {
5623 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5624 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5625 << Record->isUnion() << "const"
5626 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5627 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5628 Diag(DS.getVolatileSpecLoc(),
5629 diag::ext_anonymous_struct_union_qualified)
5630 << Record->isUnion() << "volatile"
5631 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5632 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5633 Diag(DS.getRestrictSpecLoc(),
5634 diag::ext_anonymous_struct_union_qualified)
5635 << Record->isUnion() << "restrict"
5636 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5637 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5638 Diag(DS.getAtomicSpecLoc(),
5639 diag::ext_anonymous_struct_union_qualified)
5640 << Record->isUnion() << "_Atomic"
5641 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5642 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5643 Diag(DS.getUnalignedSpecLoc(),
5644 diag::ext_anonymous_struct_union_qualified)
5645 << Record->isUnion() << "__unaligned"
5646 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5647
5648 DS.ClearTypeQualifiers();
5649 }
5650
5651 // C++ [class.union]p2:
5652 // The member-specification of an anonymous union shall only
5653 // define non-static data members. [Note: nested types and
5654 // functions cannot be declared within an anonymous union. ]
5655 for (auto *Mem : Record->decls()) {
5656 // Ignore invalid declarations; we already diagnosed them.
5657 if (Mem->isInvalidDecl())
5658 continue;
5659
5660 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5661 // C++ [class.union]p3:
5662 // An anonymous union shall not have private or protected
5663 // members (clause 11).
5664 assert(FD->getAccess() != AS_none);
5665 if (FD->getAccess() != AS_public) {
5666 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5667 << Record->isUnion() << (FD->getAccess() == AS_protected);
5668 Invalid = true;
5669 }
5670
5671 // C++ [class.union]p1
5672 // An object of a class with a non-trivial constructor, a non-trivial
5673 // copy constructor, a non-trivial destructor, or a non-trivial copy
5674 // assignment operator cannot be a member of a union, nor can an
5675 // array of such objects.
5676 if (CheckNontrivialField(FD))
5677 Invalid = true;
5678 } else if (Mem->isImplicit()) {
5679 // Any implicit members are fine.
5680 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5681 // This is a type that showed up in an
5682 // elaborated-type-specifier inside the anonymous struct or
5683 // union, but which actually declares a type outside of the
5684 // anonymous struct or union. It's okay.
5685 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5686 if (!MemRecord->isAnonymousStructOrUnion() &&
5687 MemRecord->getDeclName()) {
5688 // Visual C++ allows type definition in anonymous struct or union.
5689 if (getLangOpts().MicrosoftExt)
5690 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5691 << Record->isUnion();
5692 else {
5693 // This is a nested type declaration.
5694 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5695 << Record->isUnion();
5696 Invalid = true;
5697 }
5698 } else {
5699 // This is an anonymous type definition within another anonymous type.
5700 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5701 // not part of standard C++.
5702 Diag(MemRecord->getLocation(),
5703 diag::ext_anonymous_record_with_anonymous_type)
5704 << Record->isUnion();
5705 }
5706 } else if (isa<AccessSpecDecl>(Mem)) {
5707 // Any access specifier is fine.
5708 } else if (isa<StaticAssertDecl>(Mem)) {
5709 // In C++1z, static_assert declarations are also fine.
5710 } else {
5711 // We have something that isn't a non-static data
5712 // member. Complain about it.
5713 unsigned DK = diag::err_anonymous_record_bad_member;
5714 if (isa<TypeDecl>(Mem))
5715 DK = diag::err_anonymous_record_with_type;
5716 else if (isa<FunctionDecl>(Mem))
5717 DK = diag::err_anonymous_record_with_function;
5718 else if (isa<VarDecl>(Mem))
5719 DK = diag::err_anonymous_record_with_static;
5720
5721 // Visual C++ allows type definition in anonymous struct or union.
5722 if (getLangOpts().MicrosoftExt &&
5723 DK == diag::err_anonymous_record_with_type)
5724 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5725 << Record->isUnion();
5726 else {
5727 Diag(Mem->getLocation(), DK) << Record->isUnion();
5728 Invalid = true;
5729 }
5730 }
5731 }
5732
5733 // C++11 [class.union]p8 (DR1460):
5734 // At most one variant member of a union may have a
5735 // brace-or-equal-initializer.
5736 if (cast<CXXRecordDecl>(Val: Record)->hasInClassInitializer() &&
5737 Owner->isRecord())
5738 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Owner),
5739 AnonUnion: cast<CXXRecordDecl>(Val: Record));
5740 }
5741
5742 if (!Record->isUnion() && !Owner->isRecord()) {
5743 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5744 << getLangOpts().CPlusPlus;
5745 Invalid = true;
5746 }
5747
5748 // C++ [dcl.dcl]p3:
5749 // [If there are no declarators], and except for the declaration of an
5750 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5751 // names into the program
5752 // C++ [class.mem]p2:
5753 // each such member-declaration shall either declare at least one member
5754 // name of the class or declare at least one unnamed bit-field
5755 //
5756 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5757 if (getLangOpts().CPlusPlus && Record->field_empty())
5758 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5759
5760 // Mock up a declarator.
5761 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5762 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5763 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5764 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5765
5766 // Create a declaration for this anonymous struct/union.
5767 NamedDecl *Anon = nullptr;
5768 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Val: Owner)) {
5769 Anon = FieldDecl::Create(
5770 C: Context, DC: OwningClass, StartLoc: DS.getBeginLoc(), IdLoc: Record->getLocation(),
5771 /*IdentifierInfo=*/Id: nullptr, T: Context.getTypeDeclType(Record), TInfo,
5772 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5773 /*InitStyle=*/ICIS_NoInit);
5774 Anon->setAccess(AS);
5775 ProcessDeclAttributes(S, Anon, Dc);
5776
5777 if (getLangOpts().CPlusPlus)
5778 FieldCollector->Add(D: cast<FieldDecl>(Val: Anon));
5779 } else {
5780 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5781 if (SCSpec == DeclSpec::SCS_mutable) {
5782 // mutable can only appear on non-static class members, so it's always
5783 // an error here
5784 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5785 Invalid = true;
5786 SC = SC_None;
5787 }
5788
5789 Anon = VarDecl::Create(C&: Context, DC: Owner, StartLoc: DS.getBeginLoc(),
5790 IdLoc: Record->getLocation(), /*IdentifierInfo=*/Id: nullptr,
5791 T: Context.getTypeDeclType(Record), TInfo, S: SC);
5792 ProcessDeclAttributes(S, Anon, Dc);
5793
5794 // Default-initialize the implicit variable. This initialization will be
5795 // trivial in almost all cases, except if a union member has an in-class
5796 // initializer:
5797 // union { int n = 0; };
5798 ActOnUninitializedDecl(Anon);
5799 }
5800 Anon->setImplicit();
5801
5802 // Mark this as an anonymous struct/union type.
5803 Record->setAnonymousStructOrUnion(true);
5804
5805 // Add the anonymous struct/union object to the current
5806 // context. We'll be referencing this object when we refer to one of
5807 // its members.
5808 Owner->addDecl(Anon);
5809
5810 // Inject the members of the anonymous struct/union into the owning
5811 // context and into the identifier resolver chain for name lookup
5812 // purposes.
5813 SmallVector<NamedDecl*, 2> Chain;
5814 Chain.push_back(Elt: Anon);
5815
5816 if (InjectAnonymousStructOrUnionMembers(SemaRef&: *this, S, Owner, AnonRecord: Record, AS, SC,
5817 Chaining&: Chain))
5818 Invalid = true;
5819
5820 if (VarDecl *NewVD = dyn_cast<VarDecl>(Val: Anon)) {
5821 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5822 MangleNumberingContext *MCtx;
5823 Decl *ManglingContextDecl;
5824 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5825 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
5826 if (MCtx) {
5827 Context.setManglingNumber(
5828 NewVD, MCtx->getManglingNumber(
5829 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
5830 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
5831 }
5832 }
5833 }
5834
5835 if (Invalid)
5836 Anon->setInvalidDecl();
5837
5838 return Anon;
5839}
5840
5841/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5842/// Microsoft C anonymous structure.
5843/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5844/// Example:
5845///
5846/// struct A { int a; };
5847/// struct B { struct A; int b; };
5848///
5849/// void foo() {
5850/// B var;
5851/// var.a = 3;
5852/// }
5853///
5854Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5855 RecordDecl *Record) {
5856 assert(Record && "expected a record!");
5857
5858 // Mock up a declarator.
5859 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5860 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5861 assert(TInfo && "couldn't build declarator info for anonymous struct");
5862
5863 auto *ParentDecl = cast<RecordDecl>(Val: CurContext);
5864 QualType RecTy = Context.getTypeDeclType(Record);
5865
5866 // Create a declaration for this anonymous struct.
5867 NamedDecl *Anon =
5868 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5869 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5870 /*BitWidth=*/nullptr, /*Mutable=*/false,
5871 /*InitStyle=*/ICIS_NoInit);
5872 Anon->setImplicit();
5873
5874 // Add the anonymous struct object to the current context.
5875 CurContext->addDecl(Anon);
5876
5877 // Inject the members of the anonymous struct into the current
5878 // context and into the identifier resolver chain for name lookup
5879 // purposes.
5880 SmallVector<NamedDecl*, 2> Chain;
5881 Chain.push_back(Elt: Anon);
5882
5883 RecordDecl *RecordDef = Record->getDefinition();
5884 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5885 diag::err_field_incomplete_or_sizeless) ||
5886 InjectAnonymousStructOrUnionMembers(
5887 *this, S, CurContext, RecordDef, AS_none,
5888 StorageClassSpecToVarDeclStorageClass(DS), Chain)) {
5889 Anon->setInvalidDecl();
5890 ParentDecl->setInvalidDecl();
5891 }
5892
5893 return Anon;
5894}
5895
5896/// GetNameForDeclarator - Determine the full declaration name for the
5897/// given Declarator.
5898DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5899 return GetNameFromUnqualifiedId(Name: D.getName());
5900}
5901
5902/// Retrieves the declaration name from a parsed unqualified-id.
5903DeclarationNameInfo
5904Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5905 DeclarationNameInfo NameInfo;
5906 NameInfo.setLoc(Name.StartLocation);
5907
5908 switch (Name.getKind()) {
5909
5910 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5911 case UnqualifiedIdKind::IK_Identifier:
5912 NameInfo.setName(Name.Identifier);
5913 return NameInfo;
5914
5915 case UnqualifiedIdKind::IK_DeductionGuideName: {
5916 // C++ [temp.deduct.guide]p3:
5917 // The simple-template-id shall name a class template specialization.
5918 // The template-name shall be the same identifier as the template-name
5919 // of the simple-template-id.
5920 // These together intend to imply that the template-name shall name a
5921 // class template.
5922 // FIXME: template<typename T> struct X {};
5923 // template<typename T> using Y = X<T>;
5924 // Y(int) -> Y<int>;
5925 // satisfies these rules but does not name a class template.
5926 TemplateName TN = Name.TemplateName.get().get();
5927 auto *Template = TN.getAsTemplateDecl();
5928 if (!Template || !isa<ClassTemplateDecl>(Val: Template)) {
5929 Diag(Name.StartLocation,
5930 diag::err_deduction_guide_name_not_class_template)
5931 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5932 if (Template)
5933 NoteTemplateLocation(*Template);
5934 return DeclarationNameInfo();
5935 }
5936
5937 NameInfo.setName(
5938 Context.DeclarationNames.getCXXDeductionGuideName(TD: Template));
5939 return NameInfo;
5940 }
5941
5942 case UnqualifiedIdKind::IK_OperatorFunctionId:
5943 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5944 Op: Name.OperatorFunctionId.Operator));
5945 NameInfo.setCXXOperatorNameRange(SourceRange(
5946 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5947 return NameInfo;
5948
5949 case UnqualifiedIdKind::IK_LiteralOperatorId:
5950 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5951 II: Name.Identifier));
5952 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5953 return NameInfo;
5954
5955 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5956 TypeSourceInfo *TInfo;
5957 QualType Ty = GetTypeFromParser(Ty: Name.ConversionFunctionId, TInfo: &TInfo);
5958 if (Ty.isNull())
5959 return DeclarationNameInfo();
5960 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5961 Ty: Context.getCanonicalType(T: Ty)));
5962 NameInfo.setNamedTypeInfo(TInfo);
5963 return NameInfo;
5964 }
5965
5966 case UnqualifiedIdKind::IK_ConstructorName: {
5967 TypeSourceInfo *TInfo;
5968 QualType Ty = GetTypeFromParser(Ty: Name.ConstructorName, TInfo: &TInfo);
5969 if (Ty.isNull())
5970 return DeclarationNameInfo();
5971 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5972 Ty: Context.getCanonicalType(T: Ty)));
5973 NameInfo.setNamedTypeInfo(TInfo);
5974 return NameInfo;
5975 }
5976
5977 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5978 // In well-formed code, we can only have a constructor
5979 // template-id that refers to the current context, so go there
5980 // to find the actual type being constructed.
5981 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(Val: CurContext);
5982 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5983 return DeclarationNameInfo();
5984
5985 // Determine the type of the class being constructed.
5986 QualType CurClassType = Context.getTypeDeclType(CurClass);
5987
5988 // FIXME: Check two things: that the template-id names the same type as
5989 // CurClassType, and that the template-id does not occur when the name
5990 // was qualified.
5991
5992 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5993 Ty: Context.getCanonicalType(T: CurClassType)));
5994 // FIXME: should we retrieve TypeSourceInfo?
5995 NameInfo.setNamedTypeInfo(nullptr);
5996 return NameInfo;
5997 }
5998
5999 case UnqualifiedIdKind::IK_DestructorName: {
6000 TypeSourceInfo *TInfo;
6001 QualType Ty = GetTypeFromParser(Ty: Name.DestructorName, TInfo: &TInfo);
6002 if (Ty.isNull())
6003 return DeclarationNameInfo();
6004 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6005 Ty: Context.getCanonicalType(T: Ty)));
6006 NameInfo.setNamedTypeInfo(TInfo);
6007 return NameInfo;
6008 }
6009
6010 case UnqualifiedIdKind::IK_TemplateId: {
6011 TemplateName TName = Name.TemplateId->Template.get();
6012 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6013 return Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
6014 }
6015
6016 } // switch (Name.getKind())
6017
6018 llvm_unreachable("Unknown name kind");
6019}
6020
6021static QualType getCoreType(QualType Ty) {
6022 do {
6023 if (Ty->isPointerType() || Ty->isReferenceType())
6024 Ty = Ty->getPointeeType();
6025 else if (Ty->isArrayType())
6026 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6027 else
6028 return Ty.withoutLocalFastQualifiers();
6029 } while (true);
6030}
6031
6032/// hasSimilarParameters - Determine whether the C++ functions Declaration
6033/// and Definition have "nearly" matching parameters. This heuristic is
6034/// used to improve diagnostics in the case where an out-of-line function
6035/// definition doesn't match any declaration within the class or namespace.
6036/// Also sets Params to the list of indices to the parameters that differ
6037/// between the declaration and the definition. If hasSimilarParameters
6038/// returns true and Params is empty, then all of the parameters match.
6039static bool hasSimilarParameters(ASTContext &Context,
6040 FunctionDecl *Declaration,
6041 FunctionDecl *Definition,
6042 SmallVectorImpl<unsigned> &Params) {
6043 Params.clear();
6044 if (Declaration->param_size() != Definition->param_size())
6045 return false;
6046 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6047 QualType DeclParamTy = Declaration->getParamDecl(i: Idx)->getType();
6048 QualType DefParamTy = Definition->getParamDecl(i: Idx)->getType();
6049
6050 // The parameter types are identical
6051 if (Context.hasSameUnqualifiedType(T1: DefParamTy, T2: DeclParamTy))
6052 continue;
6053
6054 QualType DeclParamBaseTy = getCoreType(Ty: DeclParamTy);
6055 QualType DefParamBaseTy = getCoreType(Ty: DefParamTy);
6056 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6057 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6058
6059 if (Context.hasSameUnqualifiedType(T1: DeclParamBaseTy, T2: DefParamBaseTy) ||
6060 (DeclTyName && DeclTyName == DefTyName))
6061 Params.push_back(Elt: Idx);
6062 else // The two parameters aren't even close
6063 return false;
6064 }
6065
6066 return true;
6067}
6068
6069/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6070/// declarator needs to be rebuilt in the current instantiation.
6071/// Any bits of declarator which appear before the name are valid for
6072/// consideration here. That's specifically the type in the decl spec
6073/// and the base type in any member-pointer chunks.
6074static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6075 DeclarationName Name) {
6076 // The types we specifically need to rebuild are:
6077 // - typenames, typeofs, and decltypes
6078 // - types which will become injected class names
6079 // Of course, we also need to rebuild any type referencing such a
6080 // type. It's safest to just say "dependent", but we call out a
6081 // few cases here.
6082
6083 DeclSpec &DS = D.getMutableDeclSpec();
6084 switch (DS.getTypeSpecType()) {
6085 case DeclSpec::TST_typename:
6086 case DeclSpec::TST_typeofType:
6087 case DeclSpec::TST_typeof_unqualType:
6088#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6089#include "clang/Basic/TransformTypeTraits.def"
6090 case DeclSpec::TST_atomic: {
6091 // Grab the type from the parser.
6092 TypeSourceInfo *TSI = nullptr;
6093 QualType T = S.GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TSI);
6094 if (T.isNull() || !T->isInstantiationDependentType()) break;
6095
6096 // Make sure there's a type source info. This isn't really much
6097 // of a waste; most dependent types should have type source info
6098 // attached already.
6099 if (!TSI)
6100 TSI = S.Context.getTrivialTypeSourceInfo(T, Loc: DS.getTypeSpecTypeLoc());
6101
6102 // Rebuild the type in the current instantiation.
6103 TSI = S.RebuildTypeInCurrentInstantiation(T: TSI, Loc: D.getIdentifierLoc(), Name);
6104 if (!TSI) return true;
6105
6106 // Store the new type back in the decl spec.
6107 ParsedType LocType = S.CreateParsedType(T: TSI->getType(), TInfo: TSI);
6108 DS.UpdateTypeRep(Rep: LocType);
6109 break;
6110 }
6111
6112 case DeclSpec::TST_decltype:
6113 case DeclSpec::TST_typeof_unqualExpr:
6114 case DeclSpec::TST_typeofExpr: {
6115 Expr *E = DS.getRepAsExpr();
6116 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6117 if (Result.isInvalid()) return true;
6118 DS.UpdateExprRep(Rep: Result.get());
6119 break;
6120 }
6121
6122 default:
6123 // Nothing to do for these decl specs.
6124 break;
6125 }
6126
6127 // It doesn't matter what order we do this in.
6128 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6129 DeclaratorChunk &Chunk = D.getTypeObject(i: I);
6130
6131 // The only type information in the declarator which can come
6132 // before the declaration name is the base type of a member
6133 // pointer.
6134 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6135 continue;
6136
6137 // Rebuild the scope specifier in-place.
6138 CXXScopeSpec &SS = Chunk.Mem.Scope();
6139 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6140 return true;
6141 }
6142
6143 return false;
6144}
6145
6146/// Returns true if the declaration is declared in a system header or from a
6147/// system macro.
6148static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6149 return SM.isInSystemHeader(Loc: D->getLocation()) ||
6150 SM.isInSystemMacro(loc: D->getLocation());
6151}
6152
6153void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6154 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6155 // of system decl.
6156 if (D->getPreviousDecl() || D->isImplicit())
6157 return;
6158 ReservedIdentifierStatus Status = D->isReserved(LangOpts: getLangOpts());
6159 if (Status != ReservedIdentifierStatus::NotReserved &&
6160 !isFromSystemHeader(Context.getSourceManager(), D)) {
6161 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6162 << D << static_cast<int>(Status);
6163 }
6164}
6165
6166Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6167 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6168
6169 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6170 // declaration only if the `bind_to_declaration` extension is set.
6171 SmallVector<FunctionDecl *, 4> Bases;
6172 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6173 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6174 TP: llvm::omp::TraitProperty::
6175 implementation_extension_bind_to_declaration))
6176 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6177 S, D, TemplateParameterLists: MultiTemplateParamsArg(), Bases);
6178
6179 Decl *Dcl = HandleDeclarator(S, D, TemplateParameterLists: MultiTemplateParamsArg());
6180
6181 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6182 Dcl && Dcl->getDeclContext()->isFileContext())
6183 Dcl->setTopLevelDeclInObjCContainer();
6184
6185 if (!Bases.empty())
6186 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
6187 Bases);
6188
6189 return Dcl;
6190}
6191
6192/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6193/// If T is the name of a class, then each of the following shall have a
6194/// name different from T:
6195/// - every static data member of class T;
6196/// - every member function of class T
6197/// - every member of class T that is itself a type;
6198/// \returns true if the declaration name violates these rules.
6199bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6200 DeclarationNameInfo NameInfo) {
6201 DeclarationName Name = NameInfo.getName();
6202
6203 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC);
6204 while (Record && Record->isAnonymousStructOrUnion())
6205 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6206 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6207 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6208 return true;
6209 }
6210
6211 return false;
6212}
6213
6214/// Diagnose a declaration whose declarator-id has the given
6215/// nested-name-specifier.
6216///
6217/// \param SS The nested-name-specifier of the declarator-id.
6218///
6219/// \param DC The declaration context to which the nested-name-specifier
6220/// resolves.
6221///
6222/// \param Name The name of the entity being declared.
6223///
6224/// \param Loc The location of the name of the entity being declared.
6225///
6226/// \param IsMemberSpecialization Whether we are declaring a member
6227/// specialization.
6228///
6229/// \param TemplateId The template-id, if any.
6230///
6231/// \returns true if we cannot safely recover from this error, false otherwise.
6232bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6233 DeclarationName Name,
6234 SourceLocation Loc,
6235 TemplateIdAnnotation *TemplateId,
6236 bool IsMemberSpecialization) {
6237 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6238 "without nested-name-specifier");
6239 DeclContext *Cur = CurContext;
6240 while (isa<LinkageSpecDecl>(Val: Cur) || isa<CapturedDecl>(Val: Cur))
6241 Cur = Cur->getParent();
6242
6243 // If the user provided a superfluous scope specifier that refers back to the
6244 // class in which the entity is already declared, diagnose and ignore it.
6245 //
6246 // class X {
6247 // void X::f();
6248 // };
6249 //
6250 // Note, it was once ill-formed to give redundant qualification in all
6251 // contexts, but that rule was removed by DR482.
6252 if (Cur->Equals(DC)) {
6253 if (Cur->isRecord()) {
6254 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6255 : diag::err_member_extra_qualification)
6256 << Name << FixItHint::CreateRemoval(SS.getRange());
6257 SS.clear();
6258 } else {
6259 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6260 }
6261 return false;
6262 }
6263
6264 // Check whether the qualifying scope encloses the scope of the original
6265 // declaration. For a template-id, we perform the checks in
6266 // CheckTemplateSpecializationScope.
6267 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6268 if (Cur->isRecord())
6269 Diag(Loc, diag::err_member_qualification)
6270 << Name << SS.getRange();
6271 else if (isa<TranslationUnitDecl>(Val: DC))
6272 Diag(Loc, diag::err_invalid_declarator_global_scope)
6273 << Name << SS.getRange();
6274 else if (isa<FunctionDecl>(Val: Cur))
6275 Diag(Loc, diag::err_invalid_declarator_in_function)
6276 << Name << SS.getRange();
6277 else if (isa<BlockDecl>(Val: Cur))
6278 Diag(Loc, diag::err_invalid_declarator_in_block)
6279 << Name << SS.getRange();
6280 else if (isa<ExportDecl>(Val: Cur)) {
6281 if (!isa<NamespaceDecl>(Val: DC))
6282 Diag(Loc, diag::err_export_non_namespace_scope_name)
6283 << Name << SS.getRange();
6284 else
6285 // The cases that DC is not NamespaceDecl should be handled in
6286 // CheckRedeclarationExported.
6287 return false;
6288 } else
6289 Diag(Loc, diag::err_invalid_declarator_scope)
6290 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6291
6292 return true;
6293 }
6294
6295 if (Cur->isRecord()) {
6296 // Cannot qualify members within a class.
6297 Diag(Loc, diag::err_member_qualification)
6298 << Name << SS.getRange();
6299 SS.clear();
6300
6301 // C++ constructors and destructors with incorrect scopes can break
6302 // our AST invariants by having the wrong underlying types. If
6303 // that's the case, then drop this declaration entirely.
6304 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6305 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6306 !Context.hasSameType(T1: Name.getCXXNameType(),
6307 T2: Context.getTypeDeclType(cast<CXXRecordDecl>(Val: Cur))))
6308 return true;
6309
6310 return false;
6311 }
6312
6313 // C++23 [temp.names]p5:
6314 // The keyword template shall not appear immediately after a declarative
6315 // nested-name-specifier.
6316 //
6317 // First check the template-id (if any), and then check each component of the
6318 // nested-name-specifier in reverse order.
6319 //
6320 // FIXME: nested-name-specifiers in friend declarations are declarative,
6321 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6322 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6323 Diag(Loc, diag::ext_template_after_declarative_nns)
6324 << FixItHint::CreateRemoval(TemplateId->TemplateKWLoc);
6325
6326 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6327 do {
6328 if (SpecLoc.getNestedNameSpecifier()->getKind() ==
6329 NestedNameSpecifier::TypeSpecWithTemplate)
6330 Diag(Loc, diag::ext_template_after_declarative_nns)
6331 << FixItHint::CreateRemoval(
6332 SpecLoc.getTypeLoc().getTemplateKeywordLoc());
6333
6334 if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) {
6335 if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) {
6336 // C++23 [expr.prim.id.qual]p3:
6337 // [...] If a nested-name-specifier N is declarative and has a
6338 // simple-template-id with a template argument list A that involves a
6339 // template parameter, let T be the template nominated by N without A.
6340 // T shall be a class template.
6341 if (TST->isDependentType() && TST->isTypeAlias())
6342 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6343 << SpecLoc.getLocalSourceRange();
6344 } else if (T->isDecltypeType() || T->getAsAdjusted<PackIndexingType>()) {
6345 // C++23 [expr.prim.id.qual]p2:
6346 // [...] A declarative nested-name-specifier shall not have a
6347 // computed-type-specifier.
6348 //
6349 // CWG2858 changed this from 'decltype-specifier' to
6350 // 'computed-type-specifier'.
6351 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6352 << T->isDecltypeType() << SpecLoc.getTypeLoc().getSourceRange();
6353 }
6354 }
6355 } while ((SpecLoc = SpecLoc.getPrefix()));
6356
6357 return false;
6358}
6359
6360NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6361 MultiTemplateParamsArg TemplateParamLists) {
6362 // TODO: consider using NameInfo for diagnostic.
6363 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6364 DeclarationName Name = NameInfo.getName();
6365
6366 // All of these full declarators require an identifier. If it doesn't have
6367 // one, the ParsedFreeStandingDeclSpec action should be used.
6368 if (D.isDecompositionDeclarator()) {
6369 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6370 } else if (!Name) {
6371 if (!D.isInvalidType()) // Reject this if we think it is valid.
6372 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6373 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6374 return nullptr;
6375 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_DeclarationType))
6376 return nullptr;
6377
6378 DeclContext *DC = CurContext;
6379 if (D.getCXXScopeSpec().isInvalid())
6380 D.setInvalidType();
6381 else if (D.getCXXScopeSpec().isSet()) {
6382 if (DiagnoseUnexpandedParameterPack(SS: D.getCXXScopeSpec(),
6383 UPPC: UPPC_DeclarationQualifier))
6384 return nullptr;
6385
6386 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6387 DC = computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext);
6388 if (!DC || isa<EnumDecl>(Val: DC)) {
6389 // If we could not compute the declaration context, it's because the
6390 // declaration context is dependent but does not refer to a class,
6391 // class template, or class template partial specialization. Complain
6392 // and return early, to avoid the coming semantic disaster.
6393 Diag(D.getIdentifierLoc(),
6394 diag::err_template_qualified_declarator_no_match)
6395 << D.getCXXScopeSpec().getScopeRep()
6396 << D.getCXXScopeSpec().getRange();
6397 return nullptr;
6398 }
6399 bool IsDependentContext = DC->isDependentContext();
6400
6401 if (!IsDependentContext &&
6402 RequireCompleteDeclContext(SS&: D.getCXXScopeSpec(), DC))
6403 return nullptr;
6404
6405 // If a class is incomplete, do not parse entities inside it.
6406 if (isa<CXXRecordDecl>(Val: DC) && !cast<CXXRecordDecl>(Val: DC)->hasDefinition()) {
6407 Diag(D.getIdentifierLoc(),
6408 diag::err_member_def_undefined_record)
6409 << Name << DC << D.getCXXScopeSpec().getRange();
6410 return nullptr;
6411 }
6412 if (!D.getDeclSpec().isFriendSpecified()) {
6413 TemplateIdAnnotation *TemplateId =
6414 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6415 ? D.getName().TemplateId
6416 : nullptr;
6417 if (diagnoseQualifiedDeclaration(SS&: D.getCXXScopeSpec(), DC, Name,
6418 Loc: D.getIdentifierLoc(), TemplateId,
6419 /*IsMemberSpecialization=*/false)) {
6420 if (DC->isRecord())
6421 return nullptr;
6422
6423 D.setInvalidType();
6424 }
6425 }
6426
6427 // Check whether we need to rebuild the type of the given
6428 // declaration in the current instantiation.
6429 if (EnteringContext && IsDependentContext &&
6430 TemplateParamLists.size() != 0) {
6431 ContextRAII SavedContext(*this, DC);
6432 if (RebuildDeclaratorInCurrentInstantiation(S&: *this, D, Name))
6433 D.setInvalidType();
6434 }
6435 }
6436
6437 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6438 QualType R = TInfo->getType();
6439
6440 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
6441 UPPC: UPPC_DeclarationType))
6442 D.setInvalidType();
6443
6444 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6445 forRedeclarationInCurContext());
6446
6447 // See if this is a redefinition of a variable in the same scope.
6448 if (!D.getCXXScopeSpec().isSet()) {
6449 bool IsLinkageLookup = false;
6450 bool CreateBuiltins = false;
6451
6452 // If the declaration we're planning to build will be a function
6453 // or object with linkage, then look for another declaration with
6454 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6455 //
6456 // If the declaration we're planning to build will be declared with
6457 // external linkage in the translation unit, create any builtin with
6458 // the same name.
6459 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6460 /* Do nothing*/;
6461 else if (CurContext->isFunctionOrMethod() &&
6462 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6463 R->isFunctionType())) {
6464 IsLinkageLookup = true;
6465 CreateBuiltins =
6466 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6467 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6468 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6469 CreateBuiltins = true;
6470
6471 if (IsLinkageLookup) {
6472 Previous.clear(Kind: LookupRedeclarationWithLinkage);
6473 Previous.setRedeclarationKind(
6474 RedeclarationKind::ForExternalRedeclaration);
6475 }
6476
6477 LookupName(R&: Previous, S, AllowBuiltinCreation: CreateBuiltins);
6478 } else { // Something like "int foo::x;"
6479 LookupQualifiedName(R&: Previous, LookupCtx: DC);
6480
6481 // C++ [dcl.meaning]p1:
6482 // When the declarator-id is qualified, the declaration shall refer to a
6483 // previously declared member of the class or namespace to which the
6484 // qualifier refers (or, in the case of a namespace, of an element of the
6485 // inline namespace set of that namespace (7.3.1)) or to a specialization
6486 // thereof; [...]
6487 //
6488 // Note that we already checked the context above, and that we do not have
6489 // enough information to make sure that Previous contains the declaration
6490 // we want to match. For example, given:
6491 //
6492 // class X {
6493 // void f();
6494 // void f(float);
6495 // };
6496 //
6497 // void X::f(int) { } // ill-formed
6498 //
6499 // In this case, Previous will point to the overload set
6500 // containing the two f's declared in X, but neither of them
6501 // matches.
6502
6503 RemoveUsingDecls(R&: Previous);
6504 }
6505
6506 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6507 TPD && TPD->isTemplateParameter()) {
6508 // Older versions of clang allowed the names of function/variable templates
6509 // to shadow the names of their template parameters. For the compatibility
6510 // purposes we detect such cases and issue a default-to-error warning that
6511 // can be disabled with -Wno-strict-primary-template-shadow.
6512 if (!D.isInvalidType()) {
6513 bool AllowForCompatibility = false;
6514 if (Scope *DeclParent = S->getDeclParent();
6515 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6516 AllowForCompatibility = DeclParent->Contains(rhs: *TemplateParamParent) &&
6517 TemplateParamParent->isDeclScope(TPD);
6518 }
6519 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), TPD,
6520 AllowForCompatibility);
6521 }
6522
6523 // Just pretend that we didn't see the previous declaration.
6524 Previous.clear();
6525 }
6526
6527 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6528 // Forget that the previous declaration is the injected-class-name.
6529 Previous.clear();
6530
6531 // In C++, the previous declaration we find might be a tag type
6532 // (class or enum). In this case, the new declaration will hide the
6533 // tag type. Note that this applies to functions, function templates, and
6534 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6535 if (Previous.isSingleTagDecl() &&
6536 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6537 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6538 Previous.clear();
6539
6540 // Check that there are no default arguments other than in the parameters
6541 // of a function declaration (C++ only).
6542 if (getLangOpts().CPlusPlus)
6543 CheckExtraCXXDefaultArguments(D);
6544
6545 /// Get the innermost enclosing declaration scope.
6546 S = S->getDeclParent();
6547
6548 NamedDecl *New;
6549
6550 bool AddToScope = true;
6551 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6552 if (TemplateParamLists.size()) {
6553 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6554 return nullptr;
6555 }
6556
6557 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6558 } else if (R->isFunctionType()) {
6559 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6560 TemplateParamLists,
6561 AddToScope);
6562 } else {
6563 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6564 AddToScope);
6565 }
6566
6567 if (!New)
6568 return nullptr;
6569
6570 // If this has an identifier and is not a function template specialization,
6571 // add it to the scope stack.
6572 if (New->getDeclName() && AddToScope)
6573 PushOnScopeChains(D: New, S);
6574
6575 if (OpenMP().isInOpenMPDeclareTargetContext())
6576 OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6577
6578 return New;
6579}
6580
6581/// Helper method to turn variable array types into constant array
6582/// types in certain situations which would otherwise be errors (for
6583/// GCC compatibility).
6584static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6585 ASTContext &Context,
6586 bool &SizeIsNegative,
6587 llvm::APSInt &Oversized) {
6588 // This method tries to turn a variable array into a constant
6589 // array even when the size isn't an ICE. This is necessary
6590 // for compatibility with code that depends on gcc's buggy
6591 // constant expression folding, like struct {char x[(int)(char*)2];}
6592 SizeIsNegative = false;
6593 Oversized = 0;
6594
6595 if (T->isDependentType())
6596 return QualType();
6597
6598 QualifierCollector Qs;
6599 const Type *Ty = Qs.strip(type: T);
6600
6601 if (const PointerType* PTy = dyn_cast<PointerType>(Val: Ty)) {
6602 QualType Pointee = PTy->getPointeeType();
6603 QualType FixedType =
6604 TryToFixInvalidVariablyModifiedType(T: Pointee, Context, SizeIsNegative,
6605 Oversized);
6606 if (FixedType.isNull()) return FixedType;
6607 FixedType = Context.getPointerType(T: FixedType);
6608 return Qs.apply(Context, QT: FixedType);
6609 }
6610 if (const ParenType* PTy = dyn_cast<ParenType>(Val: Ty)) {
6611 QualType Inner = PTy->getInnerType();
6612 QualType FixedType =
6613 TryToFixInvalidVariablyModifiedType(T: Inner, Context, SizeIsNegative,
6614 Oversized);
6615 if (FixedType.isNull()) return FixedType;
6616 FixedType = Context.getParenType(NamedType: FixedType);
6617 return Qs.apply(Context, QT: FixedType);
6618 }
6619
6620 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(Val&: T);
6621 if (!VLATy)
6622 return QualType();
6623
6624 QualType ElemTy = VLATy->getElementType();
6625 if (ElemTy->isVariablyModifiedType()) {
6626 ElemTy = TryToFixInvalidVariablyModifiedType(T: ElemTy, Context,
6627 SizeIsNegative, Oversized);
6628 if (ElemTy.isNull())
6629 return QualType();
6630 }
6631
6632 Expr::EvalResult Result;
6633 if (!VLATy->getSizeExpr() ||
6634 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Ctx: Context))
6635 return QualType();
6636
6637 llvm::APSInt Res = Result.Val.getInt();
6638
6639 // Check whether the array size is negative.
6640 if (Res.isSigned() && Res.isNegative()) {
6641 SizeIsNegative = true;
6642 return QualType();
6643 }
6644
6645 // Check whether the array is too large to be addressed.
6646 unsigned ActiveSizeBits =
6647 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6648 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6649 ? ConstantArrayType::getNumAddressingBits(Context, ElementType: ElemTy, NumElements: Res)
6650 : Res.getActiveBits();
6651 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6652 Oversized = Res;
6653 return QualType();
6654 }
6655
6656 QualType FoldedArrayType = Context.getConstantArrayType(
6657 EltTy: ElemTy, ArySize: Res, SizeExpr: VLATy->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6658 return Qs.apply(Context, QT: FoldedArrayType);
6659}
6660
6661static void
6662FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6663 SrcTL = SrcTL.getUnqualifiedLoc();
6664 DstTL = DstTL.getUnqualifiedLoc();
6665 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6666 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6667 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6668 DstPTL.getPointeeLoc());
6669 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6670 return;
6671 }
6672 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6673 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6674 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getInnerLoc(),
6675 DstTL: DstPTL.getInnerLoc());
6676 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6677 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6678 return;
6679 }
6680 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6681 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6682 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6683 TypeLoc DstElemTL = DstATL.getElementLoc();
6684 if (VariableArrayTypeLoc SrcElemATL =
6685 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6686 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6687 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6688 } else {
6689 DstElemTL.initializeFullCopy(Other: SrcElemTL);
6690 }
6691 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6692 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6693 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6694}
6695
6696/// Helper method to turn variable array types into constant array
6697/// types in certain situations which would otherwise be errors (for
6698/// GCC compatibility).
6699static TypeSourceInfo*
6700TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6701 ASTContext &Context,
6702 bool &SizeIsNegative,
6703 llvm::APSInt &Oversized) {
6704 QualType FixedTy
6705 = TryToFixInvalidVariablyModifiedType(T: TInfo->getType(), Context,
6706 SizeIsNegative, Oversized);
6707 if (FixedTy.isNull())
6708 return nullptr;
6709 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(T: FixedTy);
6710 FixInvalidVariablyModifiedTypeLoc(SrcTL: TInfo->getTypeLoc(),
6711 DstTL: FixedTInfo->getTypeLoc());
6712 return FixedTInfo;
6713}
6714
6715/// Attempt to fold a variable-sized type to a constant-sized type, returning
6716/// true if we were successful.
6717bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6718 QualType &T, SourceLocation Loc,
6719 unsigned FailedFoldDiagID) {
6720 bool SizeIsNegative;
6721 llvm::APSInt Oversized;
6722 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6723 TInfo, Context, SizeIsNegative, Oversized);
6724 if (FixedTInfo) {
6725 Diag(Loc, diag::ext_vla_folded_to_constant);
6726 TInfo = FixedTInfo;
6727 T = FixedTInfo->getType();
6728 return true;
6729 }
6730
6731 if (SizeIsNegative)
6732 Diag(Loc, diag::err_typecheck_negative_array_size);
6733 else if (Oversized.getBoolValue())
6734 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6735 else if (FailedFoldDiagID)
6736 Diag(Loc, FailedFoldDiagID);
6737 return false;
6738}
6739
6740/// Register the given locally-scoped extern "C" declaration so
6741/// that it can be found later for redeclarations. We include any extern "C"
6742/// declaration that is not visible in the translation unit here, not just
6743/// function-scope declarations.
6744void
6745Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6746 if (!getLangOpts().CPlusPlus &&
6747 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6748 // Don't need to track declarations in the TU in C.
6749 return;
6750
6751 // Note that we have a locally-scoped external with this name.
6752 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6753}
6754
6755NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6756 // FIXME: We can have multiple results via __attribute__((overloadable)).
6757 auto Result = Context.getExternCContextDecl()->lookup(Name);
6758 return Result.empty() ? nullptr : *Result.begin();
6759}
6760
6761/// Diagnose function specifiers on a declaration of an identifier that
6762/// does not identify a function.
6763void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6764 // FIXME: We should probably indicate the identifier in question to avoid
6765 // confusion for constructs like "virtual int a(), b;"
6766 if (DS.isVirtualSpecified())
6767 Diag(DS.getVirtualSpecLoc(),
6768 diag::err_virtual_non_function);
6769
6770 if (DS.hasExplicitSpecifier())
6771 Diag(DS.getExplicitSpecLoc(),
6772 diag::err_explicit_non_function);
6773
6774 if (DS.isNoreturnSpecified())
6775 Diag(DS.getNoreturnSpecLoc(),
6776 diag::err_noreturn_non_function);
6777}
6778
6779NamedDecl*
6780Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6781 TypeSourceInfo *TInfo, LookupResult &Previous) {
6782 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6783 if (D.getCXXScopeSpec().isSet()) {
6784 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6785 << D.getCXXScopeSpec().getRange();
6786 D.setInvalidType();
6787 // Pretend we didn't see the scope specifier.
6788 DC = CurContext;
6789 Previous.clear();
6790 }
6791
6792 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
6793
6794 if (D.getDeclSpec().isInlineSpecified())
6795 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6796 << getLangOpts().CPlusPlus17;
6797 if (D.getDeclSpec().hasConstexprSpecifier())
6798 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6799 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6800
6801 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6802 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6803 Diag(D.getName().StartLocation,
6804 diag::err_deduction_guide_invalid_specifier)
6805 << "typedef";
6806 else
6807 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6808 << D.getName().getSourceRange();
6809 return nullptr;
6810 }
6811
6812 TypedefDecl *NewTD = ParseTypedefDecl(S, D, T: TInfo->getType(), TInfo);
6813 if (!NewTD) return nullptr;
6814
6815 // Handle attributes prior to checking for duplicates in MergeVarDecl
6816 ProcessDeclAttributes(S, NewTD, D);
6817
6818 CheckTypedefForVariablyModifiedType(S, NewTD);
6819
6820 bool Redeclaration = D.isRedeclaration();
6821 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6822 D.setRedeclaration(Redeclaration);
6823 return ND;
6824}
6825
6826void
6827Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6828 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6829 // then it shall have block scope.
6830 // Note that variably modified types must be fixed before merging the decl so
6831 // that redeclarations will match.
6832 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6833 QualType T = TInfo->getType();
6834 if (T->isVariablyModifiedType()) {
6835 setFunctionHasBranchProtectedScope();
6836
6837 if (S->getFnParent() == nullptr) {
6838 bool SizeIsNegative;
6839 llvm::APSInt Oversized;
6840 TypeSourceInfo *FixedTInfo =
6841 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6842 SizeIsNegative,
6843 Oversized);
6844 if (FixedTInfo) {
6845 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6846 NewTD->setTypeSourceInfo(FixedTInfo);
6847 } else {
6848 if (SizeIsNegative)
6849 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6850 else if (T->isVariableArrayType())
6851 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6852 else if (Oversized.getBoolValue())
6853 Diag(NewTD->getLocation(), diag::err_array_too_large)
6854 << toString(Oversized, 10);
6855 else
6856 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6857 NewTD->setInvalidDecl();
6858 }
6859 }
6860 }
6861}
6862
6863/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6864/// declares a typedef-name, either using the 'typedef' type specifier or via
6865/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6866NamedDecl*
6867Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6868 LookupResult &Previous, bool &Redeclaration) {
6869
6870 // Find the shadowed declaration before filtering for scope.
6871 NamedDecl *ShadowedDecl = getShadowedDeclaration(D: NewTD, R: Previous);
6872
6873 // Merge the decl with the existing one if appropriate. If the decl is
6874 // in an outer scope, it isn't the same thing.
6875 FilterLookupForScope(R&: Previous, Ctx: DC, S, /*ConsiderLinkage*/false,
6876 /*AllowInlineNamespace*/false);
6877 filterNonConflictingPreviousTypedefDecls(S&: *this, Decl: NewTD, Previous);
6878 if (!Previous.empty()) {
6879 Redeclaration = true;
6880 MergeTypedefNameDecl(S, New: NewTD, OldDecls&: Previous);
6881 } else {
6882 inferGslPointerAttribute(TD: NewTD);
6883 }
6884
6885 if (ShadowedDecl && !Redeclaration)
6886 CheckShadow(NewTD, ShadowedDecl, Previous);
6887
6888 // If this is the C FILE type, notify the AST context.
6889 if (IdentifierInfo *II = NewTD->getIdentifier())
6890 if (!NewTD->isInvalidDecl() &&
6891 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6892 switch (II->getNotableIdentifierID()) {
6893 case tok::NotableIdentifierKind::FILE:
6894 Context.setFILEDecl(NewTD);
6895 break;
6896 case tok::NotableIdentifierKind::jmp_buf:
6897 Context.setjmp_bufDecl(NewTD);
6898 break;
6899 case tok::NotableIdentifierKind::sigjmp_buf:
6900 Context.setsigjmp_bufDecl(NewTD);
6901 break;
6902 case tok::NotableIdentifierKind::ucontext_t:
6903 Context.setucontext_tDecl(NewTD);
6904 break;
6905 case tok::NotableIdentifierKind::float_t:
6906 case tok::NotableIdentifierKind::double_t:
6907 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6908 break;
6909 default:
6910 break;
6911 }
6912 }
6913
6914 return NewTD;
6915}
6916
6917/// Determines whether the given declaration is an out-of-scope
6918/// previous declaration.
6919///
6920/// This routine should be invoked when name lookup has found a
6921/// previous declaration (PrevDecl) that is not in the scope where a
6922/// new declaration by the same name is being introduced. If the new
6923/// declaration occurs in a local scope, previous declarations with
6924/// linkage may still be considered previous declarations (C99
6925/// 6.2.2p4-5, C++ [basic.link]p6).
6926///
6927/// \param PrevDecl the previous declaration found by name
6928/// lookup
6929///
6930/// \param DC the context in which the new declaration is being
6931/// declared.
6932///
6933/// \returns true if PrevDecl is an out-of-scope previous declaration
6934/// for a new delcaration with the same name.
6935static bool
6936isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6937 ASTContext &Context) {
6938 if (!PrevDecl)
6939 return false;
6940
6941 if (!PrevDecl->hasLinkage())
6942 return false;
6943
6944 if (Context.getLangOpts().CPlusPlus) {
6945 // C++ [basic.link]p6:
6946 // If there is a visible declaration of an entity with linkage
6947 // having the same name and type, ignoring entities declared
6948 // outside the innermost enclosing namespace scope, the block
6949 // scope declaration declares that same entity and receives the
6950 // linkage of the previous declaration.
6951 DeclContext *OuterContext = DC->getRedeclContext();
6952 if (!OuterContext->isFunctionOrMethod())
6953 // This rule only applies to block-scope declarations.
6954 return false;
6955
6956 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6957 if (PrevOuterContext->isRecord())
6958 // We found a member function: ignore it.
6959 return false;
6960
6961 // Find the innermost enclosing namespace for the new and
6962 // previous declarations.
6963 OuterContext = OuterContext->getEnclosingNamespaceContext();
6964 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6965
6966 // The previous declaration is in a different namespace, so it
6967 // isn't the same function.
6968 if (!OuterContext->Equals(DC: PrevOuterContext))
6969 return false;
6970 }
6971
6972 return true;
6973}
6974
6975static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6976 CXXScopeSpec &SS = D.getCXXScopeSpec();
6977 if (!SS.isSet()) return;
6978 DD->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
6979}
6980
6981bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6982 QualType type = decl->getType();
6983 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6984 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6985 // Various kinds of declaration aren't allowed to be __autoreleasing.
6986 unsigned kind = -1U;
6987 if (VarDecl *var = dyn_cast<VarDecl>(Val: decl)) {
6988 if (var->hasAttr<BlocksAttr>())
6989 kind = 0; // __block
6990 else if (!var->hasLocalStorage())
6991 kind = 1; // global
6992 } else if (isa<ObjCIvarDecl>(Val: decl)) {
6993 kind = 3; // ivar
6994 } else if (isa<FieldDecl>(Val: decl)) {
6995 kind = 2; // field
6996 }
6997
6998 if (kind != -1U) {
6999 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
7000 << kind;
7001 }
7002 } else if (lifetime == Qualifiers::OCL_None) {
7003 // Try to infer lifetime.
7004 if (!type->isObjCLifetimeType())
7005 return false;
7006
7007 lifetime = type->getObjCARCImplicitLifetime();
7008 type = Context.getLifetimeQualifiedType(type, lifetime);
7009 decl->setType(type);
7010 }
7011
7012 if (VarDecl *var = dyn_cast<VarDecl>(Val: decl)) {
7013 // Thread-local variables cannot have lifetime.
7014 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
7015 var->getTLSKind()) {
7016 Diag(var->getLocation(), diag::err_arc_thread_ownership)
7017 << var->getType();
7018 return true;
7019 }
7020 }
7021
7022 return false;
7023}
7024
7025void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
7026 if (Decl->getType().hasAddressSpace())
7027 return;
7028 if (Decl->getType()->isDependentType())
7029 return;
7030 if (VarDecl *Var = dyn_cast<VarDecl>(Val: Decl)) {
7031 QualType Type = Var->getType();
7032 if (Type->isSamplerT() || Type->isVoidType())
7033 return;
7034 LangAS ImplAS = LangAS::opencl_private;
7035 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7036 // __opencl_c_program_scope_global_variables feature, the address space
7037 // for a variable at program scope or a static or extern variable inside
7038 // a function are inferred to be __global.
7039 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()) &&
7040 Var->hasGlobalStorage())
7041 ImplAS = LangAS::opencl_global;
7042 // If the original type from a decayed type is an array type and that array
7043 // type has no address space yet, deduce it now.
7044 if (auto DT = dyn_cast<DecayedType>(Type)) {
7045 auto OrigTy = DT->getOriginalType();
7046 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7047 // Add the address space to the original array type and then propagate
7048 // that to the element type through `getAsArrayType`.
7049 OrigTy = Context.getAddrSpaceQualType(T: OrigTy, AddressSpace: ImplAS);
7050 OrigTy = QualType(Context.getAsArrayType(T: OrigTy), 0);
7051 // Re-generate the decayed type.
7052 Type = Context.getDecayedType(OrigTy);
7053 }
7054 }
7055 Type = Context.getAddrSpaceQualType(T: Type, AddressSpace: ImplAS);
7056 // Apply any qualifiers (including address space) from the array type to
7057 // the element type. This implements C99 6.7.3p8: "If the specification of
7058 // an array type includes any type qualifiers, the element type is so
7059 // qualified, not the array type."
7060 if (Type->isArrayType())
7061 Type = QualType(Context.getAsArrayType(T: Type), 0);
7062 Decl->setType(Type);
7063 }
7064}
7065
7066static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7067 // Ensure that an auto decl is deduced otherwise the checks below might cache
7068 // the wrong linkage.
7069 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7070
7071 // 'weak' only applies to declarations with external linkage.
7072 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7073 if (!ND.isExternallyVisible()) {
7074 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7075 ND.dropAttr<WeakAttr>();
7076 }
7077 }
7078 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7079 if (ND.isExternallyVisible()) {
7080 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7081 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7082 }
7083 }
7084
7085 if (auto *VD = dyn_cast<VarDecl>(Val: &ND)) {
7086 if (VD->hasInit()) {
7087 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7088 assert(VD->isThisDeclarationADefinition() &&
7089 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7090 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7091 VD->dropAttr<AliasAttr>();
7092 }
7093 }
7094 }
7095
7096 // 'selectany' only applies to externally visible variable declarations.
7097 // It does not apply to functions.
7098 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7099 if (isa<FunctionDecl>(Val: ND) || !ND.isExternallyVisible()) {
7100 S.Diag(Attr->getLocation(),
7101 diag::err_attribute_selectany_non_extern_data);
7102 ND.dropAttr<SelectAnyAttr>();
7103 }
7104 }
7105
7106 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7107 auto *VD = dyn_cast<VarDecl>(Val: &ND);
7108 bool IsAnonymousNS = false;
7109 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7110 if (VD) {
7111 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7112 while (NS && !IsAnonymousNS) {
7113 IsAnonymousNS = NS->isAnonymousNamespace();
7114 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7115 }
7116 }
7117 // dll attributes require external linkage. Static locals may have external
7118 // linkage but still cannot be explicitly imported or exported.
7119 // In Microsoft mode, a variable defined in anonymous namespace must have
7120 // external linkage in order to be exported.
7121 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7122 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7123 (!AnonNSInMicrosoftMode &&
7124 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7125 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7126 << &ND << Attr;
7127 ND.setInvalidDecl();
7128 }
7129 }
7130
7131 // Check the attributes on the function type, if any.
7132 if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND)) {
7133 // Don't declare this variable in the second operand of the for-statement;
7134 // GCC miscompiles that by ending its lifetime before evaluating the
7135 // third operand. See gcc.gnu.org/PR86769.
7136 AttributedTypeLoc ATL;
7137 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7138 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7139 TL = ATL.getModifiedLoc()) {
7140 // The [[lifetimebound]] attribute can be applied to the implicit object
7141 // parameter of a non-static member function (other than a ctor or dtor)
7142 // by applying it to the function type.
7143 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7144 const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
7145 if (!MD || MD->isStatic()) {
7146 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7147 << !MD << A->getRange();
7148 } else if (isa<CXXConstructorDecl>(Val: MD) || isa<CXXDestructorDecl>(Val: MD)) {
7149 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7150 << isa<CXXDestructorDecl>(MD) << A->getRange();
7151 }
7152 }
7153 }
7154 }
7155}
7156
7157static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7158 NamedDecl *NewDecl,
7159 bool IsSpecialization,
7160 bool IsDefinition) {
7161 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7162 return;
7163
7164 bool IsTemplate = false;
7165 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(Val: OldDecl)) {
7166 OldDecl = OldTD->getTemplatedDecl();
7167 IsTemplate = true;
7168 if (!IsSpecialization)
7169 IsDefinition = false;
7170 }
7171 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(Val: NewDecl)) {
7172 NewDecl = NewTD->getTemplatedDecl();
7173 IsTemplate = true;
7174 }
7175
7176 if (!OldDecl || !NewDecl)
7177 return;
7178
7179 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7180 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7181 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7182 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7183
7184 // dllimport and dllexport are inheritable attributes so we have to exclude
7185 // inherited attribute instances.
7186 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7187 (NewExportAttr && !NewExportAttr->isInherited());
7188
7189 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7190 // the only exception being explicit specializations.
7191 // Implicitly generated declarations are also excluded for now because there
7192 // is no other way to switch these to use dllimport or dllexport.
7193 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7194
7195 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7196 // Allow with a warning for free functions and global variables.
7197 bool JustWarn = false;
7198 if (!OldDecl->isCXXClassMember()) {
7199 auto *VD = dyn_cast<VarDecl>(Val: OldDecl);
7200 if (VD && !VD->getDescribedVarTemplate())
7201 JustWarn = true;
7202 auto *FD = dyn_cast<FunctionDecl>(Val: OldDecl);
7203 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7204 JustWarn = true;
7205 }
7206
7207 // We cannot change a declaration that's been used because IR has already
7208 // been emitted. Dllimported functions will still work though (modulo
7209 // address equality) as they can use the thunk.
7210 if (OldDecl->isUsed())
7211 if (!isa<FunctionDecl>(Val: OldDecl) || !NewImportAttr)
7212 JustWarn = false;
7213
7214 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7215 : diag::err_attribute_dll_redeclaration;
7216 S.Diag(NewDecl->getLocation(), DiagID)
7217 << NewDecl
7218 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7219 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7220 if (!JustWarn) {
7221 NewDecl->setInvalidDecl();
7222 return;
7223 }
7224 }
7225
7226 // A redeclaration is not allowed to drop a dllimport attribute, the only
7227 // exceptions being inline function definitions (except for function
7228 // templates), local extern declarations, qualified friend declarations or
7229 // special MSVC extension: in the last case, the declaration is treated as if
7230 // it were marked dllexport.
7231 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7232 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7233 if (const auto *VD = dyn_cast<VarDecl>(Val: NewDecl)) {
7234 // Ignore static data because out-of-line definitions are diagnosed
7235 // separately.
7236 IsStaticDataMember = VD->isStaticDataMember();
7237 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7238 VarDecl::DeclarationOnly;
7239 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: NewDecl)) {
7240 IsInline = FD->isInlined();
7241 IsQualifiedFriend = FD->getQualifier() &&
7242 FD->getFriendObjectKind() == Decl::FOK_Declared;
7243 }
7244
7245 if (OldImportAttr && !HasNewAttr &&
7246 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7247 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7248 if (IsMicrosoftABI && IsDefinition) {
7249 if (IsSpecialization) {
7250 S.Diag(
7251 NewDecl->getLocation(),
7252 diag::err_attribute_dllimport_function_specialization_definition);
7253 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7254 NewDecl->dropAttr<DLLImportAttr>();
7255 } else {
7256 S.Diag(NewDecl->getLocation(),
7257 diag::warn_redeclaration_without_import_attribute)
7258 << NewDecl;
7259 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7260 NewDecl->dropAttr<DLLImportAttr>();
7261 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7262 S.Context, NewImportAttr->getRange()));
7263 }
7264 } else if (IsMicrosoftABI && IsSpecialization) {
7265 assert(!IsDefinition);
7266 // MSVC allows this. Keep the inherited attribute.
7267 } else {
7268 S.Diag(NewDecl->getLocation(),
7269 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7270 << NewDecl << OldImportAttr;
7271 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7272 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7273 OldDecl->dropAttr<DLLImportAttr>();
7274 NewDecl->dropAttr<DLLImportAttr>();
7275 }
7276 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7277 // In MinGW, seeing a function declared inline drops the dllimport
7278 // attribute.
7279 OldDecl->dropAttr<DLLImportAttr>();
7280 NewDecl->dropAttr<DLLImportAttr>();
7281 S.Diag(NewDecl->getLocation(),
7282 diag::warn_dllimport_dropped_from_inline_function)
7283 << NewDecl << OldImportAttr;
7284 }
7285
7286 // A specialization of a class template member function is processed here
7287 // since it's a redeclaration. If the parent class is dllexport, the
7288 // specialization inherits that attribute. This doesn't happen automatically
7289 // since the parent class isn't instantiated until later.
7290 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDecl)) {
7291 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7292 !NewImportAttr && !NewExportAttr) {
7293 if (const DLLExportAttr *ParentExportAttr =
7294 MD->getParent()->getAttr<DLLExportAttr>()) {
7295 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7296 NewAttr->setInherited(true);
7297 NewDecl->addAttr(A: NewAttr);
7298 }
7299 }
7300 }
7301}
7302
7303/// Given that we are within the definition of the given function,
7304/// will that definition behave like C99's 'inline', where the
7305/// definition is discarded except for optimization purposes?
7306static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7307 // Try to avoid calling GetGVALinkageForFunction.
7308
7309 // All cases of this require the 'inline' keyword.
7310 if (!FD->isInlined()) return false;
7311
7312 // This is only possible in C++ with the gnu_inline attribute.
7313 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7314 return false;
7315
7316 // Okay, go ahead and call the relatively-more-expensive function.
7317 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7318}
7319
7320/// Determine whether a variable is extern "C" prior to attaching
7321/// an initializer. We can't just call isExternC() here, because that
7322/// will also compute and cache whether the declaration is externally
7323/// visible, which might change when we attach the initializer.
7324///
7325/// This can only be used if the declaration is known to not be a
7326/// redeclaration of an internal linkage declaration.
7327///
7328/// For instance:
7329///
7330/// auto x = []{};
7331///
7332/// Attaching the initializer here makes this declaration not externally
7333/// visible, because its type has internal linkage.
7334///
7335/// FIXME: This is a hack.
7336template<typename T>
7337static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7338 if (S.getLangOpts().CPlusPlus) {
7339 // In C++, the overloadable attribute negates the effects of extern "C".
7340 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7341 return false;
7342
7343 // So do CUDA's host/device attributes.
7344 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7345 D->template hasAttr<CUDAHostAttr>()))
7346 return false;
7347 }
7348 return D->isExternC();
7349}
7350
7351static bool shouldConsiderLinkage(const VarDecl *VD) {
7352 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7353 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(Val: DC) ||
7354 isa<OMPDeclareMapperDecl>(Val: DC))
7355 return VD->hasExternalStorage();
7356 if (DC->isFileContext())
7357 return true;
7358 if (DC->isRecord())
7359 return false;
7360 if (DC->getDeclKind() == Decl::HLSLBuffer)
7361 return false;
7362
7363 if (isa<RequiresExprBodyDecl>(Val: DC))
7364 return false;
7365 llvm_unreachable("Unexpected context");
7366}
7367
7368static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7369 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7370 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7371 isa<OMPDeclareReductionDecl>(Val: DC) || isa<OMPDeclareMapperDecl>(Val: DC))
7372 return true;
7373 if (DC->isRecord())
7374 return false;
7375 llvm_unreachable("Unexpected context");
7376}
7377
7378static bool hasParsedAttr(Scope *S, const Declarator &PD,
7379 ParsedAttr::Kind Kind) {
7380 // Check decl attributes on the DeclSpec.
7381 if (PD.getDeclSpec().getAttributes().hasAttribute(K: Kind))
7382 return true;
7383
7384 // Walk the declarator structure, checking decl attributes that were in a type
7385 // position to the decl itself.
7386 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7387 if (PD.getTypeObject(i: I).getAttrs().hasAttribute(K: Kind))
7388 return true;
7389 }
7390
7391 // Finally, check attributes on the decl itself.
7392 return PD.getAttributes().hasAttribute(K: Kind) ||
7393 PD.getDeclarationAttributes().hasAttribute(K: Kind);
7394}
7395
7396/// Adjust the \c DeclContext for a function or variable that might be a
7397/// function-local external declaration.
7398bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7399 if (!DC->isFunctionOrMethod())
7400 return false;
7401
7402 // If this is a local extern function or variable declared within a function
7403 // template, don't add it into the enclosing namespace scope until it is
7404 // instantiated; it might have a dependent type right now.
7405 if (DC->isDependentContext())
7406 return true;
7407
7408 // C++11 [basic.link]p7:
7409 // When a block scope declaration of an entity with linkage is not found to
7410 // refer to some other declaration, then that entity is a member of the
7411 // innermost enclosing namespace.
7412 //
7413 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7414 // semantically-enclosing namespace, not a lexically-enclosing one.
7415 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(Val: DC))
7416 DC = DC->getParent();
7417 return true;
7418}
7419
7420/// Returns true if given declaration has external C language linkage.
7421static bool isDeclExternC(const Decl *D) {
7422 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
7423 return FD->isExternC();
7424 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
7425 return VD->isExternC();
7426
7427 llvm_unreachable("Unknown type of decl!");
7428}
7429
7430/// Returns true if there hasn't been any invalid type diagnosed.
7431static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7432 DeclContext *DC = NewVD->getDeclContext();
7433 QualType R = NewVD->getType();
7434
7435 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7436 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7437 // argument.
7438 if (R->isImageType() || R->isPipeType()) {
7439 Se.Diag(NewVD->getLocation(),
7440 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7441 << R;
7442 NewVD->setInvalidDecl();
7443 return false;
7444 }
7445
7446 // OpenCL v1.2 s6.9.r:
7447 // The event type cannot be used to declare a program scope variable.
7448 // OpenCL v2.0 s6.9.q:
7449 // The clk_event_t and reserve_id_t types cannot be declared in program
7450 // scope.
7451 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7452 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7453 Se.Diag(NewVD->getLocation(),
7454 diag::err_invalid_type_for_program_scope_var)
7455 << R;
7456 NewVD->setInvalidDecl();
7457 return false;
7458 }
7459 }
7460
7461 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7462 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
7463 LO: Se.getLangOpts())) {
7464 QualType NR = R.getCanonicalType();
7465 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7466 NR->isReferenceType()) {
7467 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7468 NR->isFunctionReferenceType()) {
7469 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7470 << NR->isReferenceType();
7471 NewVD->setInvalidDecl();
7472 return false;
7473 }
7474 NR = NR->getPointeeType();
7475 }
7476 }
7477
7478 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
7479 LO: Se.getLangOpts())) {
7480 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7481 // half array type (unless the cl_khr_fp16 extension is enabled).
7482 if (Se.Context.getBaseElementType(QT: R)->isHalfType()) {
7483 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7484 NewVD->setInvalidDecl();
7485 return false;
7486 }
7487 }
7488
7489 // OpenCL v1.2 s6.9.r:
7490 // The event type cannot be used with the __local, __constant and __global
7491 // address space qualifiers.
7492 if (R->isEventT()) {
7493 if (R.getAddressSpace() != LangAS::opencl_private) {
7494 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7495 NewVD->setInvalidDecl();
7496 return false;
7497 }
7498 }
7499
7500 if (R->isSamplerT()) {
7501 // OpenCL v1.2 s6.9.b p4:
7502 // The sampler type cannot be used with the __local and __global address
7503 // space qualifiers.
7504 if (R.getAddressSpace() == LangAS::opencl_local ||
7505 R.getAddressSpace() == LangAS::opencl_global) {
7506 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7507 NewVD->setInvalidDecl();
7508 }
7509
7510 // OpenCL v1.2 s6.12.14.1:
7511 // A global sampler must be declared with either the constant address
7512 // space qualifier or with the const qualifier.
7513 if (DC->isTranslationUnit() &&
7514 !(R.getAddressSpace() == LangAS::opencl_constant ||
7515 R.isConstQualified())) {
7516 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7517 NewVD->setInvalidDecl();
7518 }
7519 if (NewVD->isInvalidDecl())
7520 return false;
7521 }
7522
7523 return true;
7524}
7525
7526template <typename AttrTy>
7527static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7528 const TypedefNameDecl *TND = TT->getDecl();
7529 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7530 AttrTy *Clone = Attribute->clone(S.Context);
7531 Clone->setInherited(true);
7532 D->addAttr(A: Clone);
7533 }
7534}
7535
7536// This function emits warning and a corresponding note based on the
7537// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7538// declarations of an annotated type must be const qualified.
7539void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7540 QualType VarType = VD->getType().getCanonicalType();
7541
7542 // Ignore local declarations (for now) and those with const qualification.
7543 // TODO: Local variables should not be allowed if their type declaration has
7544 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7545 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7546 return;
7547
7548 if (VarType->isArrayType()) {
7549 // Retrieve element type for array declarations.
7550 VarType = S.getASTContext().getBaseElementType(QT: VarType);
7551 }
7552
7553 const RecordDecl *RD = VarType->getAsRecordDecl();
7554
7555 // Check if the record declaration is present and if it has any attributes.
7556 if (RD == nullptr)
7557 return;
7558
7559 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7560 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7561 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7562 return;
7563 }
7564}
7565
7566NamedDecl *Sema::ActOnVariableDeclarator(
7567 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7568 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7569 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7570 QualType R = TInfo->getType();
7571 DeclarationName Name = GetNameForDeclarator(D).getName();
7572
7573 IdentifierInfo *II = Name.getAsIdentifierInfo();
7574 bool IsPlaceholderVariable = false;
7575
7576 if (D.isDecompositionDeclarator()) {
7577 // Take the name of the first declarator as our name for diagnostic
7578 // purposes.
7579 auto &Decomp = D.getDecompositionDeclarator();
7580 if (!Decomp.bindings().empty()) {
7581 II = Decomp.bindings()[0].Name;
7582 Name = II;
7583 }
7584 } else if (!II) {
7585 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7586 return nullptr;
7587 }
7588
7589
7590 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7591 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS: D.getDeclSpec());
7592
7593 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7594 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7595 IsPlaceholderVariable = true;
7596 if (!Previous.empty()) {
7597 NamedDecl *PrevDecl = *Previous.begin();
7598 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7599 DC->getRedeclContext());
7600 if (SameDC && isDeclInScope(D: PrevDecl, Ctx: CurContext, S, AllowInlineNamespace: false))
7601 DiagPlaceholderVariableDefinition(Loc: D.getIdentifierLoc());
7602 }
7603 }
7604
7605 // dllimport globals without explicit storage class are treated as extern. We
7606 // have to change the storage class this early to get the right DeclContext.
7607 if (SC == SC_None && !DC->isRecord() &&
7608 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7609 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7610 SC = SC_Extern;
7611
7612 DeclContext *OriginalDC = DC;
7613 bool IsLocalExternDecl = SC == SC_Extern &&
7614 adjustContextForLocalExternDecl(DC);
7615
7616 if (SCSpec == DeclSpec::SCS_mutable) {
7617 // mutable can only appear on non-static class members, so it's always
7618 // an error here
7619 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7620 D.setInvalidType();
7621 SC = SC_None;
7622 }
7623
7624 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7625 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7626 loc: D.getDeclSpec().getStorageClassSpecLoc())) {
7627 // In C++11, the 'register' storage class specifier is deprecated.
7628 // Suppress the warning in system macros, it's used in macros in some
7629 // popular C system headers, such as in glibc's htonl() macro.
7630 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7631 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7632 : diag::warn_deprecated_register)
7633 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7634 }
7635
7636 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
7637
7638 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7639 // C99 6.9p2: The storage-class specifiers auto and register shall not
7640 // appear in the declaration specifiers in an external declaration.
7641 // Global Register+Asm is a GNU extension we support.
7642 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7643 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7644 D.setInvalidType();
7645 }
7646 }
7647
7648 // If this variable has a VLA type and an initializer, try to
7649 // fold to a constant-sized type. This is otherwise invalid.
7650 if (D.hasInitializer() && R->isVariableArrayType())
7651 tryToFixVariablyModifiedVarType(TInfo, T&: R, Loc: D.getIdentifierLoc(),
7652 /*DiagID=*/FailedFoldDiagID: 0);
7653
7654 bool IsMemberSpecialization = false;
7655 bool IsVariableTemplateSpecialization = false;
7656 bool IsPartialSpecialization = false;
7657 bool IsVariableTemplate = false;
7658 VarDecl *NewVD = nullptr;
7659 VarTemplateDecl *NewTemplate = nullptr;
7660 TemplateParameterList *TemplateParams = nullptr;
7661 if (!getLangOpts().CPlusPlus) {
7662 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
7663 Id: II, T: R, TInfo, S: SC);
7664
7665 if (R->getContainedDeducedType())
7666 ParsingInitForAutoVars.insert(NewVD);
7667
7668 if (D.isInvalidType())
7669 NewVD->setInvalidDecl();
7670
7671 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7672 NewVD->hasLocalStorage())
7673 checkNonTrivialCUnion(QT: NewVD->getType(), Loc: NewVD->getLocation(),
7674 UseContext: NTCUC_AutoVar, NonTrivialKind: NTCUK_Destruct);
7675 } else {
7676 bool Invalid = false;
7677
7678 if (DC->isRecord() && !CurContext->isRecord()) {
7679 // This is an out-of-line definition of a static data member.
7680 switch (SC) {
7681 case SC_None:
7682 break;
7683 case SC_Static:
7684 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7685 diag::err_static_out_of_line)
7686 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7687 break;
7688 case SC_Auto:
7689 case SC_Register:
7690 case SC_Extern:
7691 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7692 // to names of variables declared in a block or to function parameters.
7693 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7694 // of class members
7695
7696 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7697 diag::err_storage_class_for_static_member)
7698 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7699 break;
7700 case SC_PrivateExtern:
7701 llvm_unreachable("C storage class in c++!");
7702 }
7703 }
7704
7705 if (SC == SC_Static && CurContext->isRecord()) {
7706 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
7707 // Walk up the enclosing DeclContexts to check for any that are
7708 // incompatible with static data members.
7709 const DeclContext *FunctionOrMethod = nullptr;
7710 const CXXRecordDecl *AnonStruct = nullptr;
7711 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7712 if (Ctxt->isFunctionOrMethod()) {
7713 FunctionOrMethod = Ctxt;
7714 break;
7715 }
7716 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Val: Ctxt);
7717 if (ParentDecl && !ParentDecl->getDeclName()) {
7718 AnonStruct = ParentDecl;
7719 break;
7720 }
7721 }
7722 if (FunctionOrMethod) {
7723 // C++ [class.static.data]p5: A local class shall not have static data
7724 // members.
7725 Diag(D.getIdentifierLoc(),
7726 diag::err_static_data_member_not_allowed_in_local_class)
7727 << Name << RD->getDeclName()
7728 << llvm::to_underlying(RD->getTagKind());
7729 } else if (AnonStruct) {
7730 // C++ [class.static.data]p4: Unnamed classes and classes contained
7731 // directly or indirectly within unnamed classes shall not contain
7732 // static data members.
7733 Diag(D.getIdentifierLoc(),
7734 diag::err_static_data_member_not_allowed_in_anon_struct)
7735 << Name << llvm::to_underlying(AnonStruct->getTagKind());
7736 Invalid = true;
7737 } else if (RD->isUnion()) {
7738 // C++98 [class.union]p1: If a union contains a static data member,
7739 // the program is ill-formed. C++11 drops this restriction.
7740 Diag(D.getIdentifierLoc(),
7741 getLangOpts().CPlusPlus11
7742 ? diag::warn_cxx98_compat_static_data_member_in_union
7743 : diag::ext_static_data_member_in_union) << Name;
7744 }
7745 }
7746 }
7747
7748 // Match up the template parameter lists with the scope specifier, then
7749 // determine whether we have a template or a template specialization.
7750 bool InvalidScope = false;
7751 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7752 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
7753 SS: D.getCXXScopeSpec(),
7754 TemplateId: D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7755 ? D.getName().TemplateId
7756 : nullptr,
7757 ParamLists: TemplateParamLists,
7758 /*never a friend*/ IsFriend: false, IsMemberSpecialization, Invalid&: InvalidScope);
7759 Invalid |= InvalidScope;
7760
7761 if (TemplateParams) {
7762 if (!TemplateParams->size() &&
7763 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7764 // There is an extraneous 'template<>' for this variable. Complain
7765 // about it, but allow the declaration of the variable.
7766 Diag(TemplateParams->getTemplateLoc(),
7767 diag::err_template_variable_noparams)
7768 << II
7769 << SourceRange(TemplateParams->getTemplateLoc(),
7770 TemplateParams->getRAngleLoc());
7771 TemplateParams = nullptr;
7772 } else {
7773 // Check that we can declare a template here.
7774 if (CheckTemplateDeclScope(S, TemplateParams))
7775 return nullptr;
7776
7777 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7778 // This is an explicit specialization or a partial specialization.
7779 IsVariableTemplateSpecialization = true;
7780 IsPartialSpecialization = TemplateParams->size() > 0;
7781 } else { // if (TemplateParams->size() > 0)
7782 // This is a template declaration.
7783 IsVariableTemplate = true;
7784
7785 // Only C++1y supports variable templates (N3651).
7786 Diag(D.getIdentifierLoc(),
7787 getLangOpts().CPlusPlus14
7788 ? diag::warn_cxx11_compat_variable_template
7789 : diag::ext_variable_template);
7790 }
7791 }
7792 } else {
7793 // Check that we can declare a member specialization here.
7794 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7795 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
7796 return nullptr;
7797 assert((Invalid ||
7798 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7799 "should have a 'template<>' for this decl");
7800 }
7801
7802 if (IsVariableTemplateSpecialization) {
7803 SourceLocation TemplateKWLoc =
7804 TemplateParamLists.size() > 0
7805 ? TemplateParamLists[0]->getTemplateLoc()
7806 : SourceLocation();
7807 DeclResult Res = ActOnVarTemplateSpecialization(
7808 S, D, DI: TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7809 IsPartialSpecialization);
7810 if (Res.isInvalid())
7811 return nullptr;
7812 NewVD = cast<VarDecl>(Val: Res.get());
7813 AddToScope = false;
7814 } else if (D.isDecompositionDeclarator()) {
7815 NewVD = DecompositionDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
7816 LSquareLoc: D.getIdentifierLoc(), T: R, TInfo, S: SC,
7817 Bindings);
7818 } else
7819 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
7820 IdLoc: D.getIdentifierLoc(), Id: II, T: R, TInfo, S: SC);
7821
7822 // If this is supposed to be a variable template, create it as such.
7823 if (IsVariableTemplate) {
7824 NewTemplate =
7825 VarTemplateDecl::Create(C&: Context, DC, L: D.getIdentifierLoc(), Name,
7826 Params: TemplateParams, Decl: NewVD);
7827 NewVD->setDescribedVarTemplate(NewTemplate);
7828 }
7829
7830 // If this decl has an auto type in need of deduction, make a note of the
7831 // Decl so we can diagnose uses of it in its own initializer.
7832 if (R->getContainedDeducedType())
7833 ParsingInitForAutoVars.insert(NewVD);
7834
7835 if (D.isInvalidType() || Invalid) {
7836 NewVD->setInvalidDecl();
7837 if (NewTemplate)
7838 NewTemplate->setInvalidDecl();
7839 }
7840
7841 SetNestedNameSpecifier(*this, NewVD, D);
7842
7843 // If we have any template parameter lists that don't directly belong to
7844 // the variable (matching the scope specifier), store them.
7845 // An explicit variable template specialization does not own any template
7846 // parameter lists.
7847 bool IsExplicitSpecialization =
7848 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7849 unsigned VDTemplateParamLists =
7850 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7851 if (TemplateParamLists.size() > VDTemplateParamLists)
7852 NewVD->setTemplateParameterListsInfo(
7853 Context, TemplateParamLists.drop_back(N: VDTemplateParamLists));
7854 }
7855
7856 if (D.getDeclSpec().isInlineSpecified()) {
7857 if (!getLangOpts().CPlusPlus) {
7858 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7859 << 0;
7860 } else if (CurContext->isFunctionOrMethod()) {
7861 // 'inline' is not allowed on block scope variable declaration.
7862 Diag(D.getDeclSpec().getInlineSpecLoc(),
7863 diag::err_inline_declaration_block_scope) << Name
7864 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7865 } else {
7866 Diag(D.getDeclSpec().getInlineSpecLoc(),
7867 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7868 : diag::ext_inline_variable);
7869 NewVD->setInlineSpecified();
7870 }
7871 }
7872
7873 // Set the lexical context. If the declarator has a C++ scope specifier, the
7874 // lexical context will be different from the semantic context.
7875 NewVD->setLexicalDeclContext(CurContext);
7876 if (NewTemplate)
7877 NewTemplate->setLexicalDeclContext(CurContext);
7878
7879 if (IsLocalExternDecl) {
7880 if (D.isDecompositionDeclarator())
7881 for (auto *B : Bindings)
7882 B->setLocalExternDecl();
7883 else
7884 NewVD->setLocalExternDecl();
7885 }
7886
7887 bool EmitTLSUnsupportedError = false;
7888 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7889 // C++11 [dcl.stc]p4:
7890 // When thread_local is applied to a variable of block scope the
7891 // storage-class-specifier static is implied if it does not appear
7892 // explicitly.
7893 // Core issue: 'static' is not implied if the variable is declared
7894 // 'extern'.
7895 if (NewVD->hasLocalStorage() &&
7896 (SCSpec != DeclSpec::SCS_unspecified ||
7897 TSCS != DeclSpec::TSCS_thread_local ||
7898 !DC->isFunctionOrMethod()))
7899 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7900 diag::err_thread_non_global)
7901 << DeclSpec::getSpecifierName(TSCS);
7902 else if (!Context.getTargetInfo().isTLSSupported()) {
7903 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7904 getLangOpts().SYCLIsDevice) {
7905 // Postpone error emission until we've collected attributes required to
7906 // figure out whether it's a host or device variable and whether the
7907 // error should be ignored.
7908 EmitTLSUnsupportedError = true;
7909 // We still need to mark the variable as TLS so it shows up in AST with
7910 // proper storage class for other tools to use even if we're not going
7911 // to emit any code for it.
7912 NewVD->setTSCSpec(TSCS);
7913 } else
7914 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7915 diag::err_thread_unsupported);
7916 } else
7917 NewVD->setTSCSpec(TSCS);
7918 }
7919
7920 switch (D.getDeclSpec().getConstexprSpecifier()) {
7921 case ConstexprSpecKind::Unspecified:
7922 break;
7923
7924 case ConstexprSpecKind::Consteval:
7925 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7926 diag::err_constexpr_wrong_decl_kind)
7927 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7928 [[fallthrough]];
7929
7930 case ConstexprSpecKind::Constexpr:
7931 NewVD->setConstexpr(true);
7932 // C++1z [dcl.spec.constexpr]p1:
7933 // A static data member declared with the constexpr specifier is
7934 // implicitly an inline variable.
7935 if (NewVD->isStaticDataMember() &&
7936 (getLangOpts().CPlusPlus17 ||
7937 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7938 NewVD->setImplicitlyInline();
7939 break;
7940
7941 case ConstexprSpecKind::Constinit:
7942 if (!NewVD->hasGlobalStorage())
7943 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7944 diag::err_constinit_local_variable);
7945 else
7946 NewVD->addAttr(
7947 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7948 ConstInitAttr::Keyword_constinit));
7949 break;
7950 }
7951
7952 // C99 6.7.4p3
7953 // An inline definition of a function with external linkage shall
7954 // not contain a definition of a modifiable object with static or
7955 // thread storage duration...
7956 // We only apply this when the function is required to be defined
7957 // elsewhere, i.e. when the function is not 'extern inline'. Note
7958 // that a local variable with thread storage duration still has to
7959 // be marked 'static'. Also note that it's possible to get these
7960 // semantics in C++ using __attribute__((gnu_inline)).
7961 if (SC == SC_Static && S->getFnParent() != nullptr &&
7962 !NewVD->getType().isConstQualified()) {
7963 FunctionDecl *CurFD = getCurFunctionDecl();
7964 if (CurFD && isFunctionDefinitionDiscarded(S&: *this, FD: CurFD)) {
7965 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7966 diag::warn_static_local_in_extern_inline);
7967 MaybeSuggestAddingStaticToDecl(D: CurFD);
7968 }
7969 }
7970
7971 if (D.getDeclSpec().isModulePrivateSpecified()) {
7972 if (IsVariableTemplateSpecialization)
7973 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7974 << (IsPartialSpecialization ? 1 : 0)
7975 << FixItHint::CreateRemoval(
7976 D.getDeclSpec().getModulePrivateSpecLoc());
7977 else if (IsMemberSpecialization)
7978 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7979 << 2
7980 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7981 else if (NewVD->hasLocalStorage())
7982 Diag(NewVD->getLocation(), diag::err_module_private_local)
7983 << 0 << NewVD
7984 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7985 << FixItHint::CreateRemoval(
7986 D.getDeclSpec().getModulePrivateSpecLoc());
7987 else {
7988 NewVD->setModulePrivate();
7989 if (NewTemplate)
7990 NewTemplate->setModulePrivate();
7991 for (auto *B : Bindings)
7992 B->setModulePrivate();
7993 }
7994 }
7995
7996 if (getLangOpts().OpenCL) {
7997 deduceOpenCLAddressSpace(NewVD);
7998
7999 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
8000 if (TSC != TSCS_unspecified) {
8001 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8002 diag::err_opencl_unknown_type_specifier)
8003 << getLangOpts().getOpenCLVersionString()
8004 << DeclSpec::getSpecifierName(TSC) << 1;
8005 NewVD->setInvalidDecl();
8006 }
8007 }
8008
8009 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8010 // address space if the table has local storage (semantic checks elsewhere
8011 // will produce an error anyway).
8012 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8013 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8014 !NewVD->hasLocalStorage()) {
8015 QualType Type = Context.getAddrSpaceQualType(
8016 T: NewVD->getType(), AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: 1));
8017 NewVD->setType(Type);
8018 }
8019 }
8020
8021 // Handle attributes prior to checking for duplicates in MergeVarDecl
8022 ProcessDeclAttributes(S, NewVD, D);
8023
8024 // FIXME: This is probably the wrong location to be doing this and we should
8025 // probably be doing this for more attributes (especially for function
8026 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8027 // the code to copy attributes would be generated by TableGen.
8028 if (R->isFunctionPointerType())
8029 if (const auto *TT = R->getAs<TypedefType>())
8030 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
8031
8032 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
8033 getLangOpts().SYCLIsDevice) {
8034 if (EmitTLSUnsupportedError &&
8035 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
8036 (getLangOpts().OpenMPIsTargetDevice &&
8037 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8038 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8039 diag::err_thread_unsupported);
8040
8041 if (EmitTLSUnsupportedError &&
8042 (LangOpts.SYCLIsDevice ||
8043 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8044 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8045 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8046 // storage [duration]."
8047 if (SC == SC_None && S->getFnParent() != nullptr &&
8048 (NewVD->hasAttr<CUDASharedAttr>() ||
8049 NewVD->hasAttr<CUDAConstantAttr>())) {
8050 NewVD->setStorageClass(SC_Static);
8051 }
8052 }
8053
8054 // Ensure that dllimport globals without explicit storage class are treated as
8055 // extern. The storage class is set above using parsed attributes. Now we can
8056 // check the VarDecl itself.
8057 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8058 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8059 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8060
8061 // In auto-retain/release, infer strong retension for variables of
8062 // retainable type.
8063 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
8064 NewVD->setInvalidDecl();
8065
8066 // Handle GNU asm-label extension (encoded as an attribute).
8067 if (Expr *E = (Expr*)D.getAsmLabel()) {
8068 // The parser guarantees this is a string.
8069 StringLiteral *SE = cast<StringLiteral>(Val: E);
8070 StringRef Label = SE->getString();
8071 if (S->getFnParent() != nullptr) {
8072 switch (SC) {
8073 case SC_None:
8074 case SC_Auto:
8075 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
8076 break;
8077 case SC_Register:
8078 // Local Named register
8079 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
8080 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
8081 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8082 break;
8083 case SC_Static:
8084 case SC_Extern:
8085 case SC_PrivateExtern:
8086 break;
8087 }
8088 } else if (SC == SC_Register) {
8089 // Global Named register
8090 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
8091 const auto &TI = Context.getTargetInfo();
8092 bool HasSizeMismatch;
8093
8094 if (!TI.isValidGCCRegisterName(Label))
8095 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8096 else if (!TI.validateGlobalRegisterVariable(Label,
8097 Context.getTypeSize(R),
8098 HasSizeMismatch))
8099 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
8100 else if (HasSizeMismatch)
8101 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
8102 }
8103
8104 if (!R->isIntegralType(Ctx: Context) && !R->isPointerType()) {
8105 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
8106 NewVD->setInvalidDecl(true);
8107 }
8108 }
8109
8110 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
8111 /*IsLiteralLabel=*/true,
8112 SE->getStrTokenLoc(0)));
8113 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8114 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8115 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
8116 if (I != ExtnameUndeclaredIdentifiers.end()) {
8117 if (isDeclExternC(NewVD)) {
8118 NewVD->addAttr(A: I->second);
8119 ExtnameUndeclaredIdentifiers.erase(I);
8120 } else
8121 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8122 << /*Variable*/1 << NewVD;
8123 }
8124 }
8125
8126 // Find the shadowed declaration before filtering for scope.
8127 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8128 ? getShadowedDeclaration(D: NewVD, R: Previous)
8129 : nullptr;
8130
8131 // Don't consider existing declarations that are in a different
8132 // scope and are out-of-semantic-context declarations (if the new
8133 // declaration has linkage).
8134 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(VD: NewVD),
8135 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
8136 IsMemberSpecialization ||
8137 IsVariableTemplateSpecialization);
8138
8139 // Check whether the previous declaration is in the same block scope. This
8140 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8141 if (getLangOpts().CPlusPlus &&
8142 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8143 NewVD->setPreviousDeclInSameBlockScope(
8144 Previous.isSingleResult() && !Previous.isShadowed() &&
8145 isDeclInScope(D: Previous.getFoundDecl(), Ctx: OriginalDC, S, AllowInlineNamespace: false));
8146
8147 if (!getLangOpts().CPlusPlus) {
8148 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8149 } else {
8150 // If this is an explicit specialization of a static data member, check it.
8151 if (IsMemberSpecialization && !IsVariableTemplateSpecialization &&
8152 !NewVD->isInvalidDecl() && CheckMemberSpecialization(NewVD, Previous))
8153 NewVD->setInvalidDecl();
8154
8155 // Merge the decl with the existing one if appropriate.
8156 if (!Previous.empty()) {
8157 if (Previous.isSingleResult() &&
8158 isa<FieldDecl>(Val: Previous.getFoundDecl()) &&
8159 D.getCXXScopeSpec().isSet()) {
8160 // The user tried to define a non-static data member
8161 // out-of-line (C++ [dcl.meaning]p1).
8162 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8163 << D.getCXXScopeSpec().getRange();
8164 Previous.clear();
8165 NewVD->setInvalidDecl();
8166 }
8167 } else if (D.getCXXScopeSpec().isSet() &&
8168 !IsVariableTemplateSpecialization) {
8169 // No previous declaration in the qualifying scope.
8170 Diag(D.getIdentifierLoc(), diag::err_no_member)
8171 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8172 << D.getCXXScopeSpec().getRange();
8173 NewVD->setInvalidDecl();
8174 }
8175
8176 if (!IsPlaceholderVariable)
8177 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8178
8179 // CheckVariableDeclaration will set NewVD as invalid if something is in
8180 // error like WebAssembly tables being declared as arrays with a non-zero
8181 // size, but then parsing continues and emits further errors on that line.
8182 // To avoid that we check here if it happened and return nullptr.
8183 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8184 return nullptr;
8185
8186 if (NewTemplate) {
8187 VarTemplateDecl *PrevVarTemplate =
8188 NewVD->getPreviousDecl()
8189 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8190 : nullptr;
8191
8192 // Check the template parameter list of this declaration, possibly
8193 // merging in the template parameter list from the previous variable
8194 // template declaration.
8195 if (CheckTemplateParameterList(
8196 NewParams: TemplateParams,
8197 OldParams: PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8198 : nullptr,
8199 TPC: (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8200 DC->isDependentContext())
8201 ? TPC_ClassTemplateMember
8202 : TPC_VarTemplate))
8203 NewVD->setInvalidDecl();
8204
8205 // If we are providing an explicit specialization of a static variable
8206 // template, make a note of that.
8207 if (PrevVarTemplate &&
8208 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8209 PrevVarTemplate->setMemberSpecialization();
8210 }
8211 }
8212
8213 // Diagnose shadowed variables iff this isn't a redeclaration.
8214 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8215 CheckShadow(NewVD, ShadowedDecl, Previous);
8216
8217 ProcessPragmaWeak(S, NewVD);
8218
8219 // If this is the first declaration of an extern C variable, update
8220 // the map of such variables.
8221 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8222 isIncompleteDeclExternC(S&: *this, D: NewVD))
8223 RegisterLocallyScopedExternCDecl(NewVD, S);
8224
8225 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8226 MangleNumberingContext *MCtx;
8227 Decl *ManglingContextDecl;
8228 std::tie(args&: MCtx, args&: ManglingContextDecl) =
8229 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
8230 if (MCtx) {
8231 Context.setManglingNumber(
8232 NewVD, MCtx->getManglingNumber(
8233 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
8234 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
8235 }
8236 }
8237
8238 // Special handling of variable named 'main'.
8239 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr(Str: "main") &&
8240 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8241 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
8242
8243 // C++ [basic.start.main]p3
8244 // A program that declares a variable main at global scope is ill-formed.
8245 if (getLangOpts().CPlusPlus)
8246 Diag(D.getBeginLoc(), diag::err_main_global_variable);
8247
8248 // In C, and external-linkage variable named main results in undefined
8249 // behavior.
8250 else if (NewVD->hasExternalFormalLinkage())
8251 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8252 }
8253
8254 if (D.isRedeclaration() && !Previous.empty()) {
8255 NamedDecl *Prev = Previous.getRepresentativeDecl();
8256 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8257 D.isFunctionDefinition());
8258 }
8259
8260 if (NewTemplate) {
8261 if (NewVD->isInvalidDecl())
8262 NewTemplate->setInvalidDecl();
8263 ActOnDocumentableDecl(NewTemplate);
8264 return NewTemplate;
8265 }
8266
8267 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8268 CompleteMemberSpecialization(NewVD, Previous);
8269
8270 emitReadOnlyPlacementAttrWarning(S&: *this, VD: NewVD);
8271
8272 return NewVD;
8273}
8274
8275/// Enum describing the %select options in diag::warn_decl_shadow.
8276enum ShadowedDeclKind {
8277 SDK_Local,
8278 SDK_Global,
8279 SDK_StaticMember,
8280 SDK_Field,
8281 SDK_Typedef,
8282 SDK_Using,
8283 SDK_StructuredBinding
8284};
8285
8286/// Determine what kind of declaration we're shadowing.
8287static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8288 const DeclContext *OldDC) {
8289 if (isa<TypeAliasDecl>(Val: ShadowedDecl))
8290 return SDK_Using;
8291 else if (isa<TypedefDecl>(Val: ShadowedDecl))
8292 return SDK_Typedef;
8293 else if (isa<BindingDecl>(Val: ShadowedDecl))
8294 return SDK_StructuredBinding;
8295 else if (isa<RecordDecl>(Val: OldDC))
8296 return isa<FieldDecl>(Val: ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8297
8298 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8299}
8300
8301/// Return the location of the capture if the given lambda captures the given
8302/// variable \p VD, or an invalid source location otherwise.
8303static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8304 const VarDecl *VD) {
8305 for (const Capture &Capture : LSI->Captures) {
8306 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8307 return Capture.getLocation();
8308 }
8309 return SourceLocation();
8310}
8311
8312static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8313 const LookupResult &R) {
8314 // Only diagnose if we're shadowing an unambiguous field or variable.
8315 if (R.getResultKind() != LookupResult::Found)
8316 return false;
8317
8318 // Return false if warning is ignored.
8319 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8320}
8321
8322/// Return the declaration shadowed by the given variable \p D, or null
8323/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8324NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8325 const LookupResult &R) {
8326 if (!shouldWarnIfShadowedDecl(Diags, R))
8327 return nullptr;
8328
8329 // Don't diagnose declarations at file scope.
8330 if (D->hasGlobalStorage() && !D->isStaticLocal())
8331 return nullptr;
8332
8333 NamedDecl *ShadowedDecl = R.getFoundDecl();
8334 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8335 : nullptr;
8336}
8337
8338/// Return the declaration shadowed by the given typedef \p D, or null
8339/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8340NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8341 const LookupResult &R) {
8342 // Don't warn if typedef declaration is part of a class
8343 if (D->getDeclContext()->isRecord())
8344 return nullptr;
8345
8346 if (!shouldWarnIfShadowedDecl(Diags, R))
8347 return nullptr;
8348
8349 NamedDecl *ShadowedDecl = R.getFoundDecl();
8350 return isa<TypedefNameDecl>(Val: ShadowedDecl) ? ShadowedDecl : nullptr;
8351}
8352
8353/// Return the declaration shadowed by the given variable \p D, or null
8354/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8355NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8356 const LookupResult &R) {
8357 if (!shouldWarnIfShadowedDecl(Diags, R))
8358 return nullptr;
8359
8360 NamedDecl *ShadowedDecl = R.getFoundDecl();
8361 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8362 : nullptr;
8363}
8364
8365/// Diagnose variable or built-in function shadowing. Implements
8366/// -Wshadow.
8367///
8368/// This method is called whenever a VarDecl is added to a "useful"
8369/// scope.
8370///
8371/// \param ShadowedDecl the declaration that is shadowed by the given variable
8372/// \param R the lookup of the name
8373///
8374void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8375 const LookupResult &R) {
8376 DeclContext *NewDC = D->getDeclContext();
8377
8378 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ShadowedDecl)) {
8379 // Fields are not shadowed by variables in C++ static methods.
8380 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDC))
8381 if (MD->isStatic())
8382 return;
8383
8384 // Fields shadowed by constructor parameters are a special case. Usually
8385 // the constructor initializes the field with the parameter.
8386 if (isa<CXXConstructorDecl>(Val: NewDC))
8387 if (const auto PVD = dyn_cast<ParmVarDecl>(Val: D)) {
8388 // Remember that this was shadowed so we can either warn about its
8389 // modification or its existence depending on warning settings.
8390 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8391 return;
8392 }
8393 }
8394
8395 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(Val: ShadowedDecl))
8396 if (shadowedVar->isExternC()) {
8397 // For shadowing external vars, make sure that we point to the global
8398 // declaration, not a locally scoped extern declaration.
8399 for (auto *I : shadowedVar->redecls())
8400 if (I->isFileVarDecl()) {
8401 ShadowedDecl = I;
8402 break;
8403 }
8404 }
8405
8406 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8407
8408 unsigned WarningDiag = diag::warn_decl_shadow;
8409 SourceLocation CaptureLoc;
8410 if (isa<VarDecl>(Val: D) && NewDC && isa<CXXMethodDecl>(Val: NewDC)) {
8411 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8412 if (RD->isLambda() && OldDC->Encloses(DC: NewDC->getLexicalParent())) {
8413 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl)) {
8414 const auto *LSI = cast<LambdaScopeInfo>(Val: getCurFunction());
8415 if (RD->getLambdaCaptureDefault() == LCD_None) {
8416 // Try to avoid warnings for lambdas with an explicit capture
8417 // list. Warn only when the lambda captures the shadowed decl
8418 // explicitly.
8419 CaptureLoc = getCaptureLocation(LSI, VD);
8420 if (CaptureLoc.isInvalid())
8421 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8422 } else {
8423 // Remember that this was shadowed so we can avoid the warning if
8424 // the shadowed decl isn't captured and the warning settings allow
8425 // it.
8426 cast<LambdaScopeInfo>(Val: getCurFunction())
8427 ->ShadowingDecls.push_back({.VD: D, VD});
8428 return;
8429 }
8430 }
8431 if (isa<FieldDecl>(Val: ShadowedDecl)) {
8432 // If lambda can capture this, then emit default shadowing warning,
8433 // Otherwise it is not really a shadowing case since field is not
8434 // available in lambda's body.
8435 // At this point we don't know that lambda can capture this, so
8436 // remember that this was shadowed and delay until we know.
8437 cast<LambdaScopeInfo>(Val: getCurFunction())
8438 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: ShadowedDecl});
8439 return;
8440 }
8441 }
8442 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl);
8443 VD && VD->hasLocalStorage()) {
8444 // A variable can't shadow a local variable in an enclosing scope, if
8445 // they are separated by a non-capturing declaration context.
8446 for (DeclContext *ParentDC = NewDC;
8447 ParentDC && !ParentDC->Equals(DC: OldDC);
8448 ParentDC = getLambdaAwareParentOfDeclContext(DC: ParentDC)) {
8449 // Only block literals, captured statements, and lambda expressions
8450 // can capture; other scopes don't.
8451 if (!isa<BlockDecl>(Val: ParentDC) && !isa<CapturedDecl>(Val: ParentDC) &&
8452 !isLambdaCallOperator(DC: ParentDC)) {
8453 return;
8454 }
8455 }
8456 }
8457 }
8458 }
8459
8460 // Never warn about shadowing a placeholder variable.
8461 if (ShadowedDecl->isPlaceholderVar(LangOpts: getLangOpts()))
8462 return;
8463
8464 // Only warn about certain kinds of shadowing for class members.
8465 if (NewDC && NewDC->isRecord()) {
8466 // In particular, don't warn about shadowing non-class members.
8467 if (!OldDC->isRecord())
8468 return;
8469
8470 // TODO: should we warn about static data members shadowing
8471 // static data members from base classes?
8472
8473 // TODO: don't diagnose for inaccessible shadowed members.
8474 // This is hard to do perfectly because we might friend the
8475 // shadowing context, but that's just a false negative.
8476 }
8477
8478
8479 DeclarationName Name = R.getLookupName();
8480
8481 // Emit warning and note.
8482 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8483 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8484 if (!CaptureLoc.isInvalid())
8485 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8486 << Name << /*explicitly*/ 1;
8487 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8488}
8489
8490/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8491/// when these variables are captured by the lambda.
8492void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8493 for (const auto &Shadow : LSI->ShadowingDecls) {
8494 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8495 // Try to avoid the warning when the shadowed decl isn't captured.
8496 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8497 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl)) {
8498 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8499 Diag(Shadow.VD->getLocation(),
8500 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8501 : diag::warn_decl_shadow)
8502 << Shadow.VD->getDeclName()
8503 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8504 if (CaptureLoc.isValid())
8505 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8506 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8507 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8508 } else if (isa<FieldDecl>(Val: ShadowedDecl)) {
8509 Diag(Shadow.VD->getLocation(),
8510 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8511 : diag::warn_decl_shadow_uncaptured_local)
8512 << Shadow.VD->getDeclName()
8513 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8514 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8515 }
8516 }
8517}
8518
8519/// Check -Wshadow without the advantage of a previous lookup.
8520void Sema::CheckShadow(Scope *S, VarDecl *D) {
8521 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8522 return;
8523
8524 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8525 Sema::LookupOrdinaryName,
8526 RedeclarationKind::ForVisibleRedeclaration);
8527 LookupName(R, S);
8528 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8529 CheckShadow(D, ShadowedDecl, R);
8530}
8531
8532/// Check if 'E', which is an expression that is about to be modified, refers
8533/// to a constructor parameter that shadows a field.
8534void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8535 // Quickly ignore expressions that can't be shadowing ctor parameters.
8536 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8537 return;
8538 E = E->IgnoreParenImpCasts();
8539 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
8540 if (!DRE)
8541 return;
8542 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8543 auto I = ShadowingDecls.find(Val: D);
8544 if (I == ShadowingDecls.end())
8545 return;
8546 const NamedDecl *ShadowedDecl = I->second;
8547 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8548 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8549 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8550 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8551
8552 // Avoid issuing multiple warnings about the same decl.
8553 ShadowingDecls.erase(I);
8554}
8555
8556/// Check for conflict between this global or extern "C" declaration and
8557/// previous global or extern "C" declarations. This is only used in C++.
8558template<typename T>
8559static bool checkGlobalOrExternCConflict(
8560 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8561 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8562 NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName());
8563
8564 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8565 // The common case: this global doesn't conflict with any extern "C"
8566 // declaration.
8567 return false;
8568 }
8569
8570 if (Prev) {
8571 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8572 // Both the old and new declarations have C language linkage. This is a
8573 // redeclaration.
8574 Previous.clear();
8575 Previous.addDecl(D: Prev);
8576 return true;
8577 }
8578
8579 // This is a global, non-extern "C" declaration, and there is a previous
8580 // non-global extern "C" declaration. Diagnose if this is a variable
8581 // declaration.
8582 if (!isa<VarDecl>(ND))
8583 return false;
8584 } else {
8585 // The declaration is extern "C". Check for any declaration in the
8586 // translation unit which might conflict.
8587 if (IsGlobal) {
8588 // We have already performed the lookup into the translation unit.
8589 IsGlobal = false;
8590 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8591 I != E; ++I) {
8592 if (isa<VarDecl>(Val: *I)) {
8593 Prev = *I;
8594 break;
8595 }
8596 }
8597 } else {
8598 DeclContext::lookup_result R =
8599 S.Context.getTranslationUnitDecl()->lookup(Name: ND->getDeclName());
8600 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8601 I != E; ++I) {
8602 if (isa<VarDecl>(Val: *I)) {
8603 Prev = *I;
8604 break;
8605 }
8606 // FIXME: If we have any other entity with this name in global scope,
8607 // the declaration is ill-formed, but that is a defect: it breaks the
8608 // 'stat' hack, for instance. Only variables can have mangled name
8609 // clashes with extern "C" declarations, so only they deserve a
8610 // diagnostic.
8611 }
8612 }
8613
8614 if (!Prev)
8615 return false;
8616 }
8617
8618 // Use the first declaration's location to ensure we point at something which
8619 // is lexically inside an extern "C" linkage-spec.
8620 assert(Prev && "should have found a previous declaration to diagnose");
8621 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: Prev))
8622 Prev = FD->getFirstDecl();
8623 else
8624 Prev = cast<VarDecl>(Val: Prev)->getFirstDecl();
8625
8626 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8627 << IsGlobal << ND;
8628 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8629 << IsGlobal;
8630 return false;
8631}
8632
8633/// Apply special rules for handling extern "C" declarations. Returns \c true
8634/// if we have found that this is a redeclaration of some prior entity.
8635///
8636/// Per C++ [dcl.link]p6:
8637/// Two declarations [for a function or variable] with C language linkage
8638/// with the same name that appear in different scopes refer to the same
8639/// [entity]. An entity with C language linkage shall not be declared with
8640/// the same name as an entity in global scope.
8641template<typename T>
8642static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8643 LookupResult &Previous) {
8644 if (!S.getLangOpts().CPlusPlus) {
8645 // In C, when declaring a global variable, look for a corresponding 'extern'
8646 // variable declared in function scope. We don't need this in C++, because
8647 // we find local extern decls in the surrounding file-scope DeclContext.
8648 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8649 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName())) {
8650 Previous.clear();
8651 Previous.addDecl(D: Prev);
8652 return true;
8653 }
8654 }
8655 return false;
8656 }
8657
8658 // A declaration in the translation unit can conflict with an extern "C"
8659 // declaration.
8660 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8661 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8662
8663 // An extern "C" declaration can conflict with a declaration in the
8664 // translation unit or can be a redeclaration of an extern "C" declaration
8665 // in another scope.
8666 if (isIncompleteDeclExternC(S,ND))
8667 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8668
8669 // Neither global nor extern "C": nothing to do.
8670 return false;
8671}
8672
8673static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8674 QualType T) {
8675 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8676 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8677 // any of its members, even recursively, shall not have an atomic type, or a
8678 // variably modified type, or a type that is volatile or restrict qualified.
8679 if (CanonT->isVariablyModifiedType()) {
8680 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8681 return true;
8682 }
8683
8684 // Arrays are qualified by their element type, so get the base type (this
8685 // works on non-arrays as well).
8686 CanonT = SemaRef.Context.getBaseElementType(QT: CanonT);
8687
8688 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8689 CanonT.isRestrictQualified()) {
8690 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8691 return true;
8692 }
8693
8694 if (CanonT->isRecordType()) {
8695 const RecordDecl *RD = CanonT->getAsRecordDecl();
8696 if (llvm::any_of(Range: RD->fields(), P: [&SemaRef, VarLoc](const FieldDecl *F) {
8697 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8698 }))
8699 return true;
8700 }
8701
8702 return false;
8703}
8704
8705void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8706 // If the decl is already known invalid, don't check it.
8707 if (NewVD->isInvalidDecl())
8708 return;
8709
8710 QualType T = NewVD->getType();
8711
8712 // Defer checking an 'auto' type until its initializer is attached.
8713 if (T->isUndeducedType())
8714 return;
8715
8716 if (NewVD->hasAttrs())
8717 CheckAlignasUnderalignment(NewVD);
8718
8719 if (T->isObjCObjectType()) {
8720 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8721 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8722 T = Context.getObjCObjectPointerType(OIT: T);
8723 NewVD->setType(T);
8724 }
8725
8726 // Emit an error if an address space was applied to decl with local storage.
8727 // This includes arrays of objects with address space qualifiers, but not
8728 // automatic variables that point to other address spaces.
8729 // ISO/IEC TR 18037 S5.1.2
8730 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8731 T.getAddressSpace() != LangAS::Default) {
8732 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8733 NewVD->setInvalidDecl();
8734 return;
8735 }
8736
8737 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8738 // scope.
8739 if (getLangOpts().OpenCLVersion == 120 &&
8740 !getOpenCLOptions().isAvailableOption(Ext: "cl_clang_storage_class_specifiers",
8741 LO: getLangOpts()) &&
8742 NewVD->isStaticLocal()) {
8743 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8744 NewVD->setInvalidDecl();
8745 return;
8746 }
8747
8748 if (getLangOpts().OpenCL) {
8749 if (!diagnoseOpenCLTypes(Se&: *this, NewVD))
8750 return;
8751
8752 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8753 if (NewVD->hasAttr<BlocksAttr>()) {
8754 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8755 return;
8756 }
8757
8758 if (T->isBlockPointerType()) {
8759 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8760 // can't use 'extern' storage class.
8761 if (!T.isConstQualified()) {
8762 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8763 << 0 /*const*/;
8764 NewVD->setInvalidDecl();
8765 return;
8766 }
8767 if (NewVD->hasExternalStorage()) {
8768 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8769 NewVD->setInvalidDecl();
8770 return;
8771 }
8772 }
8773
8774 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8775 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8776 NewVD->hasExternalStorage()) {
8777 if (!T->isSamplerT() && !T->isDependentType() &&
8778 !(T.getAddressSpace() == LangAS::opencl_constant ||
8779 (T.getAddressSpace() == LangAS::opencl_global &&
8780 getOpenCLOptions().areProgramScopeVariablesSupported(
8781 Opts: getLangOpts())))) {
8782 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8783 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8784 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8785 << Scope << "global or constant";
8786 else
8787 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8788 << Scope << "constant";
8789 NewVD->setInvalidDecl();
8790 return;
8791 }
8792 } else {
8793 if (T.getAddressSpace() == LangAS::opencl_global) {
8794 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8795 << 1 /*is any function*/ << "global";
8796 NewVD->setInvalidDecl();
8797 return;
8798 }
8799 if (T.getAddressSpace() == LangAS::opencl_constant ||
8800 T.getAddressSpace() == LangAS::opencl_local) {
8801 FunctionDecl *FD = getCurFunctionDecl();
8802 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8803 // in functions.
8804 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8805 if (T.getAddressSpace() == LangAS::opencl_constant)
8806 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8807 << 0 /*non-kernel only*/ << "constant";
8808 else
8809 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8810 << 0 /*non-kernel only*/ << "local";
8811 NewVD->setInvalidDecl();
8812 return;
8813 }
8814 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8815 // in the outermost scope of a kernel function.
8816 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8817 if (!getCurScope()->isFunctionScope()) {
8818 if (T.getAddressSpace() == LangAS::opencl_constant)
8819 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8820 << "constant";
8821 else
8822 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8823 << "local";
8824 NewVD->setInvalidDecl();
8825 return;
8826 }
8827 }
8828 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8829 // If we are parsing a template we didn't deduce an addr
8830 // space yet.
8831 T.getAddressSpace() != LangAS::Default) {
8832 // Do not allow other address spaces on automatic variable.
8833 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8834 NewVD->setInvalidDecl();
8835 return;
8836 }
8837 }
8838 }
8839
8840 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8841 && !NewVD->hasAttr<BlocksAttr>()) {
8842 if (getLangOpts().getGC() != LangOptions::NonGC)
8843 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8844 else {
8845 assert(!getLangOpts().ObjCAutoRefCount);
8846 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8847 }
8848 }
8849
8850 // WebAssembly tables must be static with a zero length and can't be
8851 // declared within functions.
8852 if (T->isWebAssemblyTableType()) {
8853 if (getCurScope()->getParent()) { // Parent is null at top-level
8854 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8855 NewVD->setInvalidDecl();
8856 return;
8857 }
8858 if (NewVD->getStorageClass() != SC_Static) {
8859 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8860 NewVD->setInvalidDecl();
8861 return;
8862 }
8863 const auto *ATy = dyn_cast<ConstantArrayType>(Val: T.getTypePtr());
8864 if (!ATy || ATy->getZExtSize() != 0) {
8865 Diag(NewVD->getLocation(),
8866 diag::err_typecheck_wasm_table_must_have_zero_length);
8867 NewVD->setInvalidDecl();
8868 return;
8869 }
8870 }
8871
8872 bool isVM = T->isVariablyModifiedType();
8873 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8874 NewVD->hasAttr<BlocksAttr>())
8875 setFunctionHasBranchProtectedScope();
8876
8877 if ((isVM && NewVD->hasLinkage()) ||
8878 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8879 bool SizeIsNegative;
8880 llvm::APSInt Oversized;
8881 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8882 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8883 QualType FixedT;
8884 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8885 FixedT = FixedTInfo->getType();
8886 else if (FixedTInfo) {
8887 // Type and type-as-written are canonically different. We need to fix up
8888 // both types separately.
8889 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8890 Oversized);
8891 }
8892 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8893 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8894 // FIXME: This won't give the correct result for
8895 // int a[10][n];
8896 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8897
8898 if (NewVD->isFileVarDecl())
8899 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8900 << SizeRange;
8901 else if (NewVD->isStaticLocal())
8902 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8903 << SizeRange;
8904 else
8905 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8906 << SizeRange;
8907 NewVD->setInvalidDecl();
8908 return;
8909 }
8910
8911 if (!FixedTInfo) {
8912 if (NewVD->isFileVarDecl())
8913 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8914 else
8915 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8916 NewVD->setInvalidDecl();
8917 return;
8918 }
8919
8920 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8921 NewVD->setType(FixedT);
8922 NewVD->setTypeSourceInfo(FixedTInfo);
8923 }
8924
8925 if (T->isVoidType()) {
8926 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8927 // of objects and functions.
8928 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8929 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8930 << T;
8931 NewVD->setInvalidDecl();
8932 return;
8933 }
8934 }
8935
8936 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8937 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8938 NewVD->setInvalidDecl();
8939 return;
8940 }
8941
8942 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8943 !T.isWebAssemblyReferenceType()) {
8944 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8945 NewVD->setInvalidDecl();
8946 return;
8947 }
8948
8949 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8950 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8951 NewVD->setInvalidDecl();
8952 return;
8953 }
8954
8955 if (getLangOpts().C23 && NewVD->isConstexpr() &&
8956 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
8957 NewVD->setInvalidDecl();
8958 return;
8959 }
8960
8961 if (NewVD->isConstexpr() && !T->isDependentType() &&
8962 RequireLiteralType(NewVD->getLocation(), T,
8963 diag::err_constexpr_var_non_literal)) {
8964 NewVD->setInvalidDecl();
8965 return;
8966 }
8967
8968 // PPC MMA non-pointer types are not allowed as non-local variable types.
8969 if (Context.getTargetInfo().getTriple().isPPC64() &&
8970 !NewVD->isLocalVarDecl() &&
8971 CheckPPCMMAType(Type: T, TypeLoc: NewVD->getLocation())) {
8972 NewVD->setInvalidDecl();
8973 return;
8974 }
8975
8976 // Check that SVE types are only used in functions with SVE available.
8977 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
8978 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
8979 llvm::StringMap<bool> CallerFeatureMap;
8980 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
8981 if (!Builtin::evaluateRequiredTargetFeatures(
8982 "sve", CallerFeatureMap)) {
8983 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8984 NewVD->setInvalidDecl();
8985 return;
8986 }
8987 }
8988
8989 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
8990 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
8991 llvm::StringMap<bool> CallerFeatureMap;
8992 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
8993 checkRVVTypeSupport(Ty: T, Loc: NewVD->getLocation(), D: cast<Decl>(Val: CurContext),
8994 FeatureMap: CallerFeatureMap);
8995 }
8996}
8997
8998/// Perform semantic checking on a newly-created variable
8999/// declaration.
9000///
9001/// This routine performs all of the type-checking required for a
9002/// variable declaration once it has been built. It is used both to
9003/// check variables after they have been parsed and their declarators
9004/// have been translated into a declaration, and to check variables
9005/// that have been instantiated from a template.
9006///
9007/// Sets NewVD->isInvalidDecl() if an error was encountered.
9008///
9009/// Returns true if the variable declaration is a redeclaration.
9010bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
9011 CheckVariableDeclarationType(NewVD);
9012
9013 // If the decl is already known invalid, don't check it.
9014 if (NewVD->isInvalidDecl())
9015 return false;
9016
9017 // If we did not find anything by this name, look for a non-visible
9018 // extern "C" declaration with the same name.
9019 if (Previous.empty() &&
9020 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewVD, Previous))
9021 Previous.setShadowed();
9022
9023 if (!Previous.empty()) {
9024 MergeVarDecl(New: NewVD, Previous);
9025 return true;
9026 }
9027 return false;
9028}
9029
9030/// AddOverriddenMethods - See if a method overrides any in the base classes,
9031/// and if so, check that it's a valid override and remember it.
9032bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
9033 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
9034
9035 // Look for methods in base classes that this method might override.
9036 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9037 /*DetectVirtual=*/false);
9038 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9039 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9040 DeclarationName Name = MD->getDeclName();
9041
9042 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9043 // We really want to find the base class destructor here.
9044 QualType T = Context.getTypeDeclType(BaseRecord);
9045 CanQualType CT = Context.getCanonicalType(T);
9046 Name = Context.DeclarationNames.getCXXDestructorName(Ty: CT);
9047 }
9048
9049 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9050 CXXMethodDecl *BaseMD =
9051 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9052 if (!BaseMD || !BaseMD->isVirtual() ||
9053 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9054 /*ConsiderCudaAttrs=*/true))
9055 continue;
9056 if (!CheckExplicitObjectOverride(MD, BaseMD))
9057 continue;
9058 if (Overridden.insert(BaseMD).second) {
9059 MD->addOverriddenMethod(BaseMD);
9060 CheckOverridingFunctionReturnType(MD, BaseMD);
9061 CheckOverridingFunctionAttributes(MD, BaseMD);
9062 CheckOverridingFunctionExceptionSpec(MD, BaseMD);
9063 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
9064 }
9065
9066 // A method can only override one function from each base class. We
9067 // don't track indirectly overridden methods from bases of bases.
9068 return true;
9069 }
9070
9071 return false;
9072 };
9073
9074 DC->lookupInBases(BaseMatches: VisitBase, Paths);
9075 return !Overridden.empty();
9076}
9077
9078namespace {
9079 // Struct for holding all of the extra arguments needed by
9080 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9081 struct ActOnFDArgs {
9082 Scope *S;
9083 Declarator &D;
9084 MultiTemplateParamsArg TemplateParamLists;
9085 bool AddToScope;
9086 };
9087} // end anonymous namespace
9088
9089namespace {
9090
9091// Callback to only accept typo corrections that have a non-zero edit distance.
9092// Also only accept corrections that have the same parent decl.
9093class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9094 public:
9095 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9096 CXXRecordDecl *Parent)
9097 : Context(Context), OriginalFD(TypoFD),
9098 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9099
9100 bool ValidateCandidate(const TypoCorrection &candidate) override {
9101 if (candidate.getEditDistance() == 0)
9102 return false;
9103
9104 SmallVector<unsigned, 1> MismatchedParams;
9105 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9106 CDeclEnd = candidate.end();
9107 CDecl != CDeclEnd; ++CDecl) {
9108 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9109
9110 if (FD && !FD->hasBody() &&
9111 hasSimilarParameters(Context, Declaration: FD, Definition: OriginalFD, Params&: MismatchedParams)) {
9112 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
9113 CXXRecordDecl *Parent = MD->getParent();
9114 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9115 return true;
9116 } else if (!ExpectedParent) {
9117 return true;
9118 }
9119 }
9120 }
9121
9122 return false;
9123 }
9124
9125 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9126 return std::make_unique<DifferentNameValidatorCCC>(args&: *this);
9127 }
9128
9129 private:
9130 ASTContext &Context;
9131 FunctionDecl *OriginalFD;
9132 CXXRecordDecl *ExpectedParent;
9133};
9134
9135} // end anonymous namespace
9136
9137void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9138 TypoCorrectedFunctionDefinitions.insert(Ptr: F);
9139}
9140
9141/// Generate diagnostics for an invalid function redeclaration.
9142///
9143/// This routine handles generating the diagnostic messages for an invalid
9144/// function redeclaration, including finding possible similar declarations
9145/// or performing typo correction if there are no previous declarations with
9146/// the same name.
9147///
9148/// Returns a NamedDecl iff typo correction was performed and substituting in
9149/// the new declaration name does not cause new errors.
9150static NamedDecl *DiagnoseInvalidRedeclaration(
9151 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9152 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9153 DeclarationName Name = NewFD->getDeclName();
9154 DeclContext *NewDC = NewFD->getDeclContext();
9155 SmallVector<unsigned, 1> MismatchedParams;
9156 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9157 TypoCorrection Correction;
9158 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9159 unsigned DiagMsg =
9160 IsLocalFriend ? diag::err_no_matching_local_friend :
9161 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9162 diag::err_member_decl_does_not_match;
9163 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9164 IsLocalFriend ? Sema::LookupLocalFriendName
9165 : Sema::LookupOrdinaryName,
9166 RedeclarationKind::ForVisibleRedeclaration);
9167
9168 NewFD->setInvalidDecl();
9169 if (IsLocalFriend)
9170 SemaRef.LookupName(R&: Prev, S);
9171 else
9172 SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: NewDC);
9173 assert(!Prev.isAmbiguous() &&
9174 "Cannot have an ambiguity in previous-declaration lookup");
9175 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9176 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9177 MD ? MD->getParent() : nullptr);
9178 if (!Prev.empty()) {
9179 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9180 Func != FuncEnd; ++Func) {
9181 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *Func);
9182 if (FD &&
9183 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9184 // Add 1 to the index so that 0 can mean the mismatch didn't
9185 // involve a parameter
9186 unsigned ParamNum =
9187 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9188 NearMatches.push_back(Elt: std::make_pair(x&: FD, y&: ParamNum));
9189 }
9190 }
9191 // If the qualified name lookup yielded nothing, try typo correction
9192 } else if ((Correction = SemaRef.CorrectTypo(
9193 Typo: Prev.getLookupNameInfo(), LookupKind: Prev.getLookupKind(), S,
9194 SS: &ExtraArgs.D.getCXXScopeSpec(), CCC, Mode: Sema::CTK_ErrorRecovery,
9195 MemberContext: IsLocalFriend ? nullptr : NewDC))) {
9196 // Set up everything for the call to ActOnFunctionDeclarator
9197 ExtraArgs.D.SetIdentifier(Id: Correction.getCorrectionAsIdentifierInfo(),
9198 IdLoc: ExtraArgs.D.getIdentifierLoc());
9199 Previous.clear();
9200 Previous.setLookupName(Correction.getCorrection());
9201 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9202 CDeclEnd = Correction.end();
9203 CDecl != CDeclEnd; ++CDecl) {
9204 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9205 if (FD && !FD->hasBody() &&
9206 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9207 Previous.addDecl(FD);
9208 }
9209 }
9210 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9211
9212 NamedDecl *Result;
9213 // Retry building the function declaration with the new previous
9214 // declarations, and with errors suppressed.
9215 {
9216 // Trap errors.
9217 Sema::SFINAETrap Trap(SemaRef);
9218
9219 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9220 // pieces need to verify the typo-corrected C++ declaration and hopefully
9221 // eliminate the need for the parameter pack ExtraArgs.
9222 Result = SemaRef.ActOnFunctionDeclarator(
9223 S: ExtraArgs.S, D&: ExtraArgs.D,
9224 DC: Correction.getCorrectionDecl()->getDeclContext(),
9225 TInfo: NewFD->getTypeSourceInfo(), Previous, TemplateParamLists: ExtraArgs.TemplateParamLists,
9226 AddToScope&: ExtraArgs.AddToScope);
9227
9228 if (Trap.hasErrorOccurred())
9229 Result = nullptr;
9230 }
9231
9232 if (Result) {
9233 // Determine which correction we picked.
9234 Decl *Canonical = Result->getCanonicalDecl();
9235 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9236 I != E; ++I)
9237 if ((*I)->getCanonicalDecl() == Canonical)
9238 Correction.setCorrectionDecl(*I);
9239
9240 // Let Sema know about the correction.
9241 SemaRef.MarkTypoCorrectedFunctionDefinition(F: Result);
9242 SemaRef.diagnoseTypo(
9243 Correction,
9244 SemaRef.PDiag(IsLocalFriend
9245 ? diag::err_no_matching_local_friend_suggest
9246 : diag::err_member_decl_does_not_match_suggest)
9247 << Name << NewDC << IsDefinition);
9248 return Result;
9249 }
9250
9251 // Pretend the typo correction never occurred
9252 ExtraArgs.D.SetIdentifier(Id: Name.getAsIdentifierInfo(),
9253 IdLoc: ExtraArgs.D.getIdentifierLoc());
9254 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9255 Previous.clear();
9256 Previous.setLookupName(Name);
9257 }
9258
9259 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9260 << Name << NewDC << IsDefinition << NewFD->getLocation();
9261
9262 bool NewFDisConst = false;
9263 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(Val: NewFD))
9264 NewFDisConst = NewMD->isConst();
9265
9266 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9267 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9268 NearMatch != NearMatchEnd; ++NearMatch) {
9269 FunctionDecl *FD = NearMatch->first;
9270 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
9271 bool FDisConst = MD && MD->isConst();
9272 bool IsMember = MD || !IsLocalFriend;
9273
9274 // FIXME: These notes are poorly worded for the local friend case.
9275 if (unsigned Idx = NearMatch->second) {
9276 ParmVarDecl *FDParam = FD->getParamDecl(i: Idx-1);
9277 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9278 if (Loc.isInvalid()) Loc = FD->getLocation();
9279 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9280 : diag::note_local_decl_close_param_match)
9281 << Idx << FDParam->getType()
9282 << NewFD->getParamDecl(Idx - 1)->getType();
9283 } else if (FDisConst != NewFDisConst) {
9284 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
9285 << NewFDisConst << FD->getSourceRange().getEnd()
9286 << (NewFDisConst
9287 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
9288 .getConstQualifierLoc())
9289 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
9290 .getRParenLoc()
9291 .getLocWithOffset(1),
9292 " const"));
9293 } else
9294 SemaRef.Diag(FD->getLocation(),
9295 IsMember ? diag::note_member_def_close_match
9296 : diag::note_local_decl_close_match);
9297 }
9298 return nullptr;
9299}
9300
9301static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9302 switch (D.getDeclSpec().getStorageClassSpec()) {
9303 default: llvm_unreachable("Unknown storage class!");
9304 case DeclSpec::SCS_auto:
9305 case DeclSpec::SCS_register:
9306 case DeclSpec::SCS_mutable:
9307 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9308 diag::err_typecheck_sclass_func);
9309 D.getMutableDeclSpec().ClearStorageClassSpecs();
9310 D.setInvalidType();
9311 break;
9312 case DeclSpec::SCS_unspecified: break;
9313 case DeclSpec::SCS_extern:
9314 if (D.getDeclSpec().isExternInLinkageSpec())
9315 return SC_None;
9316 return SC_Extern;
9317 case DeclSpec::SCS_static: {
9318 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9319 // C99 6.7.1p5:
9320 // The declaration of an identifier for a function that has
9321 // block scope shall have no explicit storage-class specifier
9322 // other than extern
9323 // See also (C++ [dcl.stc]p4).
9324 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9325 diag::err_static_block_func);
9326 break;
9327 } else
9328 return SC_Static;
9329 }
9330 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9331 }
9332
9333 // No explicit storage class has already been returned
9334 return SC_None;
9335}
9336
9337static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9338 DeclContext *DC, QualType &R,
9339 TypeSourceInfo *TInfo,
9340 StorageClass SC,
9341 bool &IsVirtualOkay) {
9342 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9343 DeclarationName Name = NameInfo.getName();
9344
9345 FunctionDecl *NewFD = nullptr;
9346 bool isInline = D.getDeclSpec().isInlineSpecified();
9347
9348 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9349 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9350 (SemaRef.getLangOpts().C23 &&
9351 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9352
9353 if (SemaRef.getLangOpts().C23)
9354 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9355 diag::err_c23_constexpr_not_variable);
9356 else
9357 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9358 diag::err_constexpr_wrong_decl_kind)
9359 << static_cast<int>(ConstexprKind);
9360 ConstexprKind = ConstexprSpecKind::Unspecified;
9361 D.getMutableDeclSpec().ClearConstexprSpec();
9362 }
9363
9364 if (!SemaRef.getLangOpts().CPlusPlus) {
9365 // Determine whether the function was written with a prototype. This is
9366 // true when:
9367 // - there is a prototype in the declarator, or
9368 // - the type R of the function is some kind of typedef or other non-
9369 // attributed reference to a type name (which eventually refers to a
9370 // function type). Note, we can't always look at the adjusted type to
9371 // check this case because attributes may cause a non-function
9372 // declarator to still have a function type. e.g.,
9373 // typedef void func(int a);
9374 // __attribute__((noreturn)) func other_func; // This has a prototype
9375 bool HasPrototype =
9376 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9377 (D.getDeclSpec().isTypeRep() &&
9378 SemaRef.GetTypeFromParser(Ty: D.getDeclSpec().getRepAsType(), TInfo: nullptr)
9379 ->isFunctionProtoType()) ||
9380 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9381 assert(
9382 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9383 "Strict prototypes are required");
9384
9385 NewFD = FunctionDecl::Create(
9386 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9387 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline, hasWrittenPrototype: HasPrototype,
9388 ConstexprKind: ConstexprSpecKind::Unspecified,
9389 /*TrailingRequiresClause=*/nullptr);
9390 if (D.isInvalidType())
9391 NewFD->setInvalidDecl();
9392
9393 return NewFD;
9394 }
9395
9396 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9397 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9398
9399 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9400
9401 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9402 // This is a C++ constructor declaration.
9403 assert(DC->isRecord() &&
9404 "Constructors can only be declared in a member context");
9405
9406 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9407 return CXXConstructorDecl::Create(
9408 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9409 TInfo, ES: ExplicitSpecifier, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(),
9410 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9411 Inherited: InheritedConstructor(), TrailingRequiresClause);
9412
9413 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9414 // This is a C++ destructor declaration.
9415 if (DC->isRecord()) {
9416 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9417 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC);
9418 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9419 C&: SemaRef.Context, RD: Record, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo,
9420 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9421 /*isImplicitlyDeclared=*/false, ConstexprKind,
9422 TrailingRequiresClause);
9423 // User defined destructors start as not selected if the class definition is still
9424 // not done.
9425 if (Record->isBeingDefined())
9426 NewDD->setIneligibleOrNotSelected(true);
9427
9428 // If the destructor needs an implicit exception specification, set it
9429 // now. FIXME: It'd be nice to be able to create the right type to start
9430 // with, but the type needs to reference the destructor declaration.
9431 if (SemaRef.getLangOpts().CPlusPlus11)
9432 SemaRef.AdjustDestructorExceptionSpec(Destructor: NewDD);
9433
9434 IsVirtualOkay = true;
9435 return NewDD;
9436
9437 } else {
9438 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9439 D.setInvalidType();
9440
9441 // Create a FunctionDecl to satisfy the function definition parsing
9442 // code path.
9443 return FunctionDecl::Create(
9444 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NLoc: D.getIdentifierLoc(), N: Name, T: R,
9445 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9446 /*hasPrototype=*/hasWrittenPrototype: true, ConstexprKind, TrailingRequiresClause);
9447 }
9448
9449 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9450 if (!DC->isRecord()) {
9451 SemaRef.Diag(D.getIdentifierLoc(),
9452 diag::err_conv_function_not_member);
9453 return nullptr;
9454 }
9455
9456 SemaRef.CheckConversionDeclarator(D, R, SC);
9457 if (D.isInvalidType())
9458 return nullptr;
9459
9460 IsVirtualOkay = true;
9461 return CXXConversionDecl::Create(
9462 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9463 TInfo, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9464 ES: ExplicitSpecifier, ConstexprKind, EndLocation: SourceLocation(),
9465 TrailingRequiresClause);
9466
9467 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9468 if (TrailingRequiresClause)
9469 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9470 diag::err_trailing_requires_clause_on_deduction_guide)
9471 << TrailingRequiresClause->getSourceRange();
9472 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9473 return nullptr;
9474 return CXXDeductionGuideDecl::Create(C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(),
9475 ES: ExplicitSpecifier, NameInfo, T: R, TInfo,
9476 EndLocation: D.getEndLoc());
9477 } else if (DC->isRecord()) {
9478 // If the name of the function is the same as the name of the record,
9479 // then this must be an invalid constructor that has a return type.
9480 // (The parser checks for a return type and makes the declarator a
9481 // constructor if it has no return type).
9482 if (Name.getAsIdentifierInfo() &&
9483 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(Val: DC)->getIdentifier()){
9484 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9485 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9486 << SourceRange(D.getIdentifierLoc());
9487 return nullptr;
9488 }
9489
9490 // This is a C++ method declaration.
9491 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9492 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9493 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9494 ConstexprKind, EndLocation: SourceLocation(), TrailingRequiresClause);
9495 IsVirtualOkay = !Ret->isStatic();
9496 return Ret;
9497 } else {
9498 bool isFriend =
9499 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9500 if (!isFriend && SemaRef.CurContext->isRecord())
9501 return nullptr;
9502
9503 // Determine whether the function was written with a
9504 // prototype. This true when:
9505 // - we're in C++ (where every function has a prototype),
9506 return FunctionDecl::Create(
9507 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9508 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9509 hasWrittenPrototype: true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9510 }
9511}
9512
9513enum OpenCLParamType {
9514 ValidKernelParam,
9515 PtrPtrKernelParam,
9516 PtrKernelParam,
9517 InvalidAddrSpacePtrKernelParam,
9518 InvalidKernelParam,
9519 RecordKernelParam
9520};
9521
9522static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9523 // Size dependent types are just typedefs to normal integer types
9524 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9525 // integers other than by their names.
9526 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9527
9528 // Remove typedefs one by one until we reach a typedef
9529 // for a size dependent type.
9530 QualType DesugaredTy = Ty;
9531 do {
9532 ArrayRef<StringRef> Names(SizeTypeNames);
9533 auto Match = llvm::find(Range&: Names, Val: DesugaredTy.getUnqualifiedType().getAsString());
9534 if (Names.end() != Match)
9535 return true;
9536
9537 Ty = DesugaredTy;
9538 DesugaredTy = Ty.getSingleStepDesugaredType(Context: C);
9539 } while (DesugaredTy != Ty);
9540
9541 return false;
9542}
9543
9544static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9545 if (PT->isDependentType())
9546 return InvalidKernelParam;
9547
9548 if (PT->isPointerType() || PT->isReferenceType()) {
9549 QualType PointeeType = PT->getPointeeType();
9550 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9551 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9552 PointeeType.getAddressSpace() == LangAS::Default)
9553 return InvalidAddrSpacePtrKernelParam;
9554
9555 if (PointeeType->isPointerType()) {
9556 // This is a pointer to pointer parameter.
9557 // Recursively check inner type.
9558 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PT: PointeeType);
9559 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9560 ParamKind == InvalidKernelParam)
9561 return ParamKind;
9562
9563 // OpenCL v3.0 s6.11.a:
9564 // A restriction to pass pointers to pointers only applies to OpenCL C
9565 // v1.2 or below.
9566 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9567 return ValidKernelParam;
9568
9569 return PtrPtrKernelParam;
9570 }
9571
9572 // C++ for OpenCL v1.0 s2.4:
9573 // Moreover the types used in parameters of the kernel functions must be:
9574 // Standard layout types for pointer parameters. The same applies to
9575 // reference if an implementation supports them in kernel parameters.
9576 if (S.getLangOpts().OpenCLCPlusPlus &&
9577 !S.getOpenCLOptions().isAvailableOption(
9578 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts())) {
9579 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9580 bool IsStandardLayoutType = true;
9581 if (CXXRec) {
9582 // If template type is not ODR-used its definition is only available
9583 // in the template definition not its instantiation.
9584 // FIXME: This logic doesn't work for types that depend on template
9585 // parameter (PR58590).
9586 if (!CXXRec->hasDefinition())
9587 CXXRec = CXXRec->getTemplateInstantiationPattern();
9588 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9589 IsStandardLayoutType = false;
9590 }
9591 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9592 !IsStandardLayoutType)
9593 return InvalidKernelParam;
9594 }
9595
9596 // OpenCL v1.2 s6.9.p:
9597 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9598 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9599 return ValidKernelParam;
9600
9601 return PtrKernelParam;
9602 }
9603
9604 // OpenCL v1.2 s6.9.k:
9605 // Arguments to kernel functions in a program cannot be declared with the
9606 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9607 // uintptr_t or a struct and/or union that contain fields declared to be one
9608 // of these built-in scalar types.
9609 if (isOpenCLSizeDependentType(C&: S.getASTContext(), Ty: PT))
9610 return InvalidKernelParam;
9611
9612 if (PT->isImageType())
9613 return PtrKernelParam;
9614
9615 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9616 return InvalidKernelParam;
9617
9618 // OpenCL extension spec v1.2 s9.5:
9619 // This extension adds support for half scalar and vector types as built-in
9620 // types that can be used for arithmetic operations, conversions etc.
9621 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: S.getLangOpts()) &&
9622 PT->isHalfType())
9623 return InvalidKernelParam;
9624
9625 // Look into an array argument to check if it has a forbidden type.
9626 if (PT->isArrayType()) {
9627 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9628 // Call ourself to check an underlying type of an array. Since the
9629 // getPointeeOrArrayElementType returns an innermost type which is not an
9630 // array, this recursive call only happens once.
9631 return getOpenCLKernelParameterType(S, PT: QualType(UnderlyingTy, 0));
9632 }
9633
9634 // C++ for OpenCL v1.0 s2.4:
9635 // Moreover the types used in parameters of the kernel functions must be:
9636 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9637 // types) for parameters passed by value;
9638 if (S.getLangOpts().OpenCLCPlusPlus &&
9639 !S.getOpenCLOptions().isAvailableOption(
9640 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts()) &&
9641 !PT->isOpenCLSpecificType() && !PT.isPODType(Context: S.Context))
9642 return InvalidKernelParam;
9643
9644 if (PT->isRecordType())
9645 return RecordKernelParam;
9646
9647 return ValidKernelParam;
9648}
9649
9650static void checkIsValidOpenCLKernelParameter(
9651 Sema &S,
9652 Declarator &D,
9653 ParmVarDecl *Param,
9654 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9655 QualType PT = Param->getType();
9656
9657 // Cache the valid types we encounter to avoid rechecking structs that are
9658 // used again
9659 if (ValidTypes.count(Ptr: PT.getTypePtr()))
9660 return;
9661
9662 switch (getOpenCLKernelParameterType(S, PT)) {
9663 case PtrPtrKernelParam:
9664 // OpenCL v3.0 s6.11.a:
9665 // A kernel function argument cannot be declared as a pointer to a pointer
9666 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9667 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9668 D.setInvalidType();
9669 return;
9670
9671 case InvalidAddrSpacePtrKernelParam:
9672 // OpenCL v1.0 s6.5:
9673 // __kernel function arguments declared to be a pointer of a type can point
9674 // to one of the following address spaces only : __global, __local or
9675 // __constant.
9676 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9677 D.setInvalidType();
9678 return;
9679
9680 // OpenCL v1.2 s6.9.k:
9681 // Arguments to kernel functions in a program cannot be declared with the
9682 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9683 // uintptr_t or a struct and/or union that contain fields declared to be
9684 // one of these built-in scalar types.
9685
9686 case InvalidKernelParam:
9687 // OpenCL v1.2 s6.8 n:
9688 // A kernel function argument cannot be declared
9689 // of event_t type.
9690 // Do not diagnose half type since it is diagnosed as invalid argument
9691 // type for any function elsewhere.
9692 if (!PT->isHalfType()) {
9693 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9694
9695 // Explain what typedefs are involved.
9696 const TypedefType *Typedef = nullptr;
9697 while ((Typedef = PT->getAs<TypedefType>())) {
9698 SourceLocation Loc = Typedef->getDecl()->getLocation();
9699 // SourceLocation may be invalid for a built-in type.
9700 if (Loc.isValid())
9701 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9702 PT = Typedef->desugar();
9703 }
9704 }
9705
9706 D.setInvalidType();
9707 return;
9708
9709 case PtrKernelParam:
9710 case ValidKernelParam:
9711 ValidTypes.insert(Ptr: PT.getTypePtr());
9712 return;
9713
9714 case RecordKernelParam:
9715 break;
9716 }
9717
9718 // Track nested structs we will inspect
9719 SmallVector<const Decl *, 4> VisitStack;
9720
9721 // Track where we are in the nested structs. Items will migrate from
9722 // VisitStack to HistoryStack as we do the DFS for bad field.
9723 SmallVector<const FieldDecl *, 4> HistoryStack;
9724 HistoryStack.push_back(Elt: nullptr);
9725
9726 // At this point we already handled everything except of a RecordType or
9727 // an ArrayType of a RecordType.
9728 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9729 const RecordType *RecTy =
9730 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9731 const RecordDecl *OrigRecDecl = RecTy->getDecl();
9732
9733 VisitStack.push_back(RecTy->getDecl());
9734 assert(VisitStack.back() && "First decl null?");
9735
9736 do {
9737 const Decl *Next = VisitStack.pop_back_val();
9738 if (!Next) {
9739 assert(!HistoryStack.empty());
9740 // Found a marker, we have gone up a level
9741 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9742 ValidTypes.insert(Hist->getType().getTypePtr());
9743
9744 continue;
9745 }
9746
9747 // Adds everything except the original parameter declaration (which is not a
9748 // field itself) to the history stack.
9749 const RecordDecl *RD;
9750 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: Next)) {
9751 HistoryStack.push_back(Elt: Field);
9752
9753 QualType FieldTy = Field->getType();
9754 // Other field types (known to be valid or invalid) are handled while we
9755 // walk around RecordDecl::fields().
9756 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9757 "Unexpected type.");
9758 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9759
9760 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9761 } else {
9762 RD = cast<RecordDecl>(Val: Next);
9763 }
9764
9765 // Add a null marker so we know when we've gone back up a level
9766 VisitStack.push_back(Elt: nullptr);
9767
9768 for (const auto *FD : RD->fields()) {
9769 QualType QT = FD->getType();
9770
9771 if (ValidTypes.count(Ptr: QT.getTypePtr()))
9772 continue;
9773
9774 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, PT: QT);
9775 if (ParamType == ValidKernelParam)
9776 continue;
9777
9778 if (ParamType == RecordKernelParam) {
9779 VisitStack.push_back(FD);
9780 continue;
9781 }
9782
9783 // OpenCL v1.2 s6.9.p:
9784 // Arguments to kernel functions that are declared to be a struct or union
9785 // do not allow OpenCL objects to be passed as elements of the struct or
9786 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9787 // of SVM.
9788 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9789 ParamType == InvalidAddrSpacePtrKernelParam) {
9790 S.Diag(Param->getLocation(),
9791 diag::err_record_with_pointers_kernel_param)
9792 << PT->isUnionType()
9793 << PT;
9794 } else {
9795 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9796 }
9797
9798 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9799 << OrigRecDecl->getDeclName();
9800
9801 // We have an error, now let's go back up through history and show where
9802 // the offending field came from
9803 for (ArrayRef<const FieldDecl *>::const_iterator
9804 I = HistoryStack.begin() + 1,
9805 E = HistoryStack.end();
9806 I != E; ++I) {
9807 const FieldDecl *OuterField = *I;
9808 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9809 << OuterField->getType();
9810 }
9811
9812 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9813 << QT->isPointerType()
9814 << QT;
9815 D.setInvalidType();
9816 return;
9817 }
9818 } while (!VisitStack.empty());
9819}
9820
9821/// Find the DeclContext in which a tag is implicitly declared if we see an
9822/// elaborated type specifier in the specified context, and lookup finds
9823/// nothing.
9824static DeclContext *getTagInjectionContext(DeclContext *DC) {
9825 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9826 DC = DC->getParent();
9827 return DC;
9828}
9829
9830/// Find the Scope in which a tag is implicitly declared if we see an
9831/// elaborated type specifier in the specified context, and lookup finds
9832/// nothing.
9833static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9834 while (S->isClassScope() ||
9835 (LangOpts.CPlusPlus &&
9836 S->isFunctionPrototypeScope()) ||
9837 ((S->getFlags() & Scope::DeclScope) == 0) ||
9838 (S->getEntity() && S->getEntity()->isTransparentContext()))
9839 S = S->getParent();
9840 return S;
9841}
9842
9843/// Determine whether a declaration matches a known function in namespace std.
9844static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9845 unsigned BuiltinID) {
9846 switch (BuiltinID) {
9847 case Builtin::BI__GetExceptionInfo:
9848 // No type checking whatsoever.
9849 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9850
9851 case Builtin::BIaddressof:
9852 case Builtin::BI__addressof:
9853 case Builtin::BIforward:
9854 case Builtin::BIforward_like:
9855 case Builtin::BImove:
9856 case Builtin::BImove_if_noexcept:
9857 case Builtin::BIas_const: {
9858 // Ensure that we don't treat the algorithm
9859 // OutputIt std::move(InputIt, InputIt, OutputIt)
9860 // as the builtin std::move.
9861 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9862 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9863 }
9864
9865 default:
9866 return false;
9867 }
9868}
9869
9870NamedDecl*
9871Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9872 TypeSourceInfo *TInfo, LookupResult &Previous,
9873 MultiTemplateParamsArg TemplateParamListsRef,
9874 bool &AddToScope) {
9875 QualType R = TInfo->getType();
9876
9877 assert(R->isFunctionType());
9878 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9879 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9880
9881 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9882 llvm::append_range(C&: TemplateParamLists, R&: TemplateParamListsRef);
9883 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9884 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9885 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9886 TemplateParamLists.back() = Invented;
9887 else
9888 TemplateParamLists.push_back(Elt: Invented);
9889 }
9890
9891 // TODO: consider using NameInfo for diagnostic.
9892 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9893 DeclarationName Name = NameInfo.getName();
9894 StorageClass SC = getFunctionStorageClass(SemaRef&: *this, D);
9895
9896 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9897 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9898 diag::err_invalid_thread)
9899 << DeclSpec::getSpecifierName(TSCS);
9900
9901 if (D.isFirstDeclarationOfMember())
9902 adjustMemberFunctionCC(
9903 T&: R, HasThisPointer: !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
9904 IsCtorOrDtor: D.isCtorOrDtor(), Loc: D.getIdentifierLoc());
9905
9906 bool isFriend = false;
9907 FunctionTemplateDecl *FunctionTemplate = nullptr;
9908 bool isMemberSpecialization = false;
9909 bool isFunctionTemplateSpecialization = false;
9910
9911 bool HasExplicitTemplateArgs = false;
9912 TemplateArgumentListInfo TemplateArgs;
9913
9914 bool isVirtualOkay = false;
9915
9916 DeclContext *OriginalDC = DC;
9917 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9918
9919 FunctionDecl *NewFD = CreateNewFunctionDecl(SemaRef&: *this, D, DC, R, TInfo, SC,
9920 IsVirtualOkay&: isVirtualOkay);
9921 if (!NewFD) return nullptr;
9922
9923 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9924 NewFD->setTopLevelDeclInObjCContainer();
9925
9926 // Set the lexical context. If this is a function-scope declaration, or has a
9927 // C++ scope specifier, or is the object of a friend declaration, the lexical
9928 // context will be different from the semantic context.
9929 NewFD->setLexicalDeclContext(CurContext);
9930
9931 if (IsLocalExternDecl)
9932 NewFD->setLocalExternDecl();
9933
9934 if (getLangOpts().CPlusPlus) {
9935 // The rules for implicit inlines changed in C++20 for methods and friends
9936 // with an in-class definition (when such a definition is not attached to
9937 // the global module). User-specified 'inline' overrides this (set when
9938 // the function decl is created above).
9939 // FIXME: We need a better way to separate C++ standard and clang modules.
9940 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9941 !NewFD->getOwningModule() ||
9942 NewFD->isFromExplicitGlobalModule() ||
9943 NewFD->getOwningModule()->isHeaderLikeModule();
9944 bool isInline = D.getDeclSpec().isInlineSpecified();
9945 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9946 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9947 isFriend = D.getDeclSpec().isFriendSpecified();
9948 if (isFriend && !isInline && D.isFunctionDefinition()) {
9949 // Pre-C++20 [class.friend]p5
9950 // A function can be defined in a friend declaration of a
9951 // class . . . . Such a function is implicitly inline.
9952 // Post C++20 [class.friend]p7
9953 // Such a function is implicitly an inline function if it is attached
9954 // to the global module.
9955 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9956 }
9957
9958 // If this is a method defined in an __interface, and is not a constructor
9959 // or an overloaded operator, then set the pure flag (isVirtual will already
9960 // return true).
9961 if (const CXXRecordDecl *Parent =
9962 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9963 if (Parent->isInterface() && cast<CXXMethodDecl>(Val: NewFD)->isUserProvided())
9964 NewFD->setIsPureVirtual(true);
9965
9966 // C++ [class.union]p2
9967 // A union can have member functions, but not virtual functions.
9968 if (isVirtual && Parent->isUnion()) {
9969 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9970 NewFD->setInvalidDecl();
9971 }
9972 if ((Parent->isClass() || Parent->isStruct()) &&
9973 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9974 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9975 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9976 if (auto *Def = Parent->getDefinition())
9977 Def->setInitMethod(true);
9978 }
9979 }
9980
9981 SetNestedNameSpecifier(*this, NewFD, D);
9982 isMemberSpecialization = false;
9983 isFunctionTemplateSpecialization = false;
9984 if (D.isInvalidType())
9985 NewFD->setInvalidDecl();
9986
9987 // Match up the template parameter lists with the scope specifier, then
9988 // determine whether we have a template or a template specialization.
9989 bool Invalid = false;
9990 TemplateIdAnnotation *TemplateId =
9991 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9992 ? D.getName().TemplateId
9993 : nullptr;
9994 TemplateParameterList *TemplateParams =
9995 MatchTemplateParametersToScopeSpecifier(
9996 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
9997 SS: D.getCXXScopeSpec(), TemplateId, ParamLists: TemplateParamLists, IsFriend: isFriend,
9998 IsMemberSpecialization&: isMemberSpecialization, Invalid);
9999 if (TemplateParams) {
10000 // Check that we can declare a template here.
10001 if (CheckTemplateDeclScope(S, TemplateParams))
10002 NewFD->setInvalidDecl();
10003
10004 if (TemplateParams->size() > 0) {
10005 // This is a function template
10006
10007 // A destructor cannot be a template.
10008 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
10009 Diag(NewFD->getLocation(), diag::err_destructor_template);
10010 NewFD->setInvalidDecl();
10011 // Function template with explicit template arguments.
10012 } else if (TemplateId) {
10013 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10014 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10015 NewFD->setInvalidDecl();
10016 }
10017
10018 // If we're adding a template to a dependent context, we may need to
10019 // rebuilding some of the types used within the template parameter list,
10020 // now that we know what the current instantiation is.
10021 if (DC->isDependentContext()) {
10022 ContextRAII SavedContext(*this, DC);
10023 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
10024 Invalid = true;
10025 }
10026
10027 FunctionTemplate = FunctionTemplateDecl::Create(C&: Context, DC,
10028 L: NewFD->getLocation(),
10029 Name, Params: TemplateParams,
10030 Decl: NewFD);
10031 FunctionTemplate->setLexicalDeclContext(CurContext);
10032 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
10033
10034 // For source fidelity, store the other template param lists.
10035 if (TemplateParamLists.size() > 1) {
10036 NewFD->setTemplateParameterListsInfo(Context,
10037 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10038 .drop_back(N: 1));
10039 }
10040 } else {
10041 // This is a function template specialization.
10042 isFunctionTemplateSpecialization = true;
10043 // For source fidelity, store all the template param lists.
10044 if (TemplateParamLists.size() > 0)
10045 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10046
10047 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10048 if (isFriend) {
10049 // We want to remove the "template<>", found here.
10050 SourceRange RemoveRange = TemplateParams->getSourceRange();
10051
10052 // If we remove the template<> and the name is not a
10053 // template-id, we're actually silently creating a problem:
10054 // the friend declaration will refer to an untemplated decl,
10055 // and clearly the user wants a template specialization. So
10056 // we need to insert '<>' after the name.
10057 SourceLocation InsertLoc;
10058 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10059 InsertLoc = D.getName().getSourceRange().getEnd();
10060 InsertLoc = getLocForEndOfToken(Loc: InsertLoc);
10061 }
10062
10063 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10064 << Name << RemoveRange
10065 << FixItHint::CreateRemoval(RemoveRange)
10066 << FixItHint::CreateInsertion(InsertLoc, "<>");
10067 Invalid = true;
10068
10069 // Recover by faking up an empty template argument list.
10070 HasExplicitTemplateArgs = true;
10071 TemplateArgs.setLAngleLoc(InsertLoc);
10072 TemplateArgs.setRAngleLoc(InsertLoc);
10073 }
10074 }
10075 } else {
10076 // Check that we can declare a template here.
10077 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10078 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
10079 NewFD->setInvalidDecl();
10080
10081 // All template param lists were matched against the scope specifier:
10082 // this is NOT (an explicit specialization of) a template.
10083 if (TemplateParamLists.size() > 0)
10084 // For source fidelity, store all the template param lists.
10085 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10086
10087 // "friend void foo<>(int);" is an implicit specialization decl.
10088 if (isFriend && TemplateId)
10089 isFunctionTemplateSpecialization = true;
10090 }
10091
10092 // If this is a function template specialization and the unqualified-id of
10093 // the declarator-id is a template-id, convert the template argument list
10094 // into our AST format and check for unexpanded packs.
10095 if (isFunctionTemplateSpecialization && TemplateId) {
10096 HasExplicitTemplateArgs = true;
10097
10098 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10099 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10100 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10101 TemplateId->NumArgs);
10102 translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgs);
10103
10104 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10105 // declaration of a function template partial specialization? Should we
10106 // consider the unexpanded pack context to be a partial specialization?
10107 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10108 if (DiagnoseUnexpandedParameterPack(
10109 Arg: ArgLoc, UPPC: isFriend ? UPPC_FriendDeclaration
10110 : UPPC_ExplicitSpecialization))
10111 NewFD->setInvalidDecl();
10112 }
10113 }
10114
10115 if (Invalid) {
10116 NewFD->setInvalidDecl();
10117 if (FunctionTemplate)
10118 FunctionTemplate->setInvalidDecl();
10119 }
10120
10121 // C++ [dcl.fct.spec]p5:
10122 // The virtual specifier shall only be used in declarations of
10123 // nonstatic class member functions that appear within a
10124 // member-specification of a class declaration; see 10.3.
10125 //
10126 if (isVirtual && !NewFD->isInvalidDecl()) {
10127 if (!isVirtualOkay) {
10128 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10129 diag::err_virtual_non_function);
10130 } else if (!CurContext->isRecord()) {
10131 // 'virtual' was specified outside of the class.
10132 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10133 diag::err_virtual_out_of_class)
10134 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10135 } else if (NewFD->getDescribedFunctionTemplate()) {
10136 // C++ [temp.mem]p3:
10137 // A member function template shall not be virtual.
10138 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10139 diag::err_virtual_member_function_template)
10140 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10141 } else {
10142 // Okay: Add virtual to the method.
10143 NewFD->setVirtualAsWritten(true);
10144 }
10145
10146 if (getLangOpts().CPlusPlus14 &&
10147 NewFD->getReturnType()->isUndeducedType())
10148 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10149 }
10150
10151 // C++ [dcl.fct.spec]p3:
10152 // The inline specifier shall not appear on a block scope function
10153 // declaration.
10154 if (isInline && !NewFD->isInvalidDecl()) {
10155 if (CurContext->isFunctionOrMethod()) {
10156 // 'inline' is not allowed on block scope function declaration.
10157 Diag(D.getDeclSpec().getInlineSpecLoc(),
10158 diag::err_inline_declaration_block_scope) << Name
10159 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10160 }
10161 }
10162
10163 // C++ [dcl.fct.spec]p6:
10164 // The explicit specifier shall be used only in the declaration of a
10165 // constructor or conversion function within its class definition;
10166 // see 12.3.1 and 12.3.2.
10167 if (hasExplicit && !NewFD->isInvalidDecl() &&
10168 !isa<CXXDeductionGuideDecl>(Val: NewFD)) {
10169 if (!CurContext->isRecord()) {
10170 // 'explicit' was specified outside of the class.
10171 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10172 diag::err_explicit_out_of_class)
10173 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10174 } else if (!isa<CXXConstructorDecl>(Val: NewFD) &&
10175 !isa<CXXConversionDecl>(Val: NewFD)) {
10176 // 'explicit' was specified on a function that wasn't a constructor
10177 // or conversion function.
10178 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10179 diag::err_explicit_non_ctor_or_conv_function)
10180 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10181 }
10182 }
10183
10184 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10185 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10186 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10187 // are implicitly inline.
10188 NewFD->setImplicitlyInline();
10189
10190 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10191 // be either constructors or to return a literal type. Therefore,
10192 // destructors cannot be declared constexpr.
10193 if (isa<CXXDestructorDecl>(Val: NewFD) &&
10194 (!getLangOpts().CPlusPlus20 ||
10195 ConstexprKind == ConstexprSpecKind::Consteval)) {
10196 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10197 << static_cast<int>(ConstexprKind);
10198 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10199 ? ConstexprSpecKind::Unspecified
10200 : ConstexprSpecKind::Constexpr);
10201 }
10202 // C++20 [dcl.constexpr]p2: An allocation function, or a
10203 // deallocation function shall not be declared with the consteval
10204 // specifier.
10205 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10206 (NewFD->getOverloadedOperator() == OO_New ||
10207 NewFD->getOverloadedOperator() == OO_Array_New ||
10208 NewFD->getOverloadedOperator() == OO_Delete ||
10209 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
10210 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10211 diag::err_invalid_consteval_decl_kind)
10212 << NewFD;
10213 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10214 }
10215 }
10216
10217 // If __module_private__ was specified, mark the function accordingly.
10218 if (D.getDeclSpec().isModulePrivateSpecified()) {
10219 if (isFunctionTemplateSpecialization) {
10220 SourceLocation ModulePrivateLoc
10221 = D.getDeclSpec().getModulePrivateSpecLoc();
10222 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10223 << 0
10224 << FixItHint::CreateRemoval(ModulePrivateLoc);
10225 } else {
10226 NewFD->setModulePrivate();
10227 if (FunctionTemplate)
10228 FunctionTemplate->setModulePrivate();
10229 }
10230 }
10231
10232 if (isFriend) {
10233 if (FunctionTemplate) {
10234 FunctionTemplate->setObjectOfFriendDecl();
10235 FunctionTemplate->setAccess(AS_public);
10236 }
10237 NewFD->setObjectOfFriendDecl();
10238 NewFD->setAccess(AS_public);
10239 }
10240
10241 // If a function is defined as defaulted or deleted, mark it as such now.
10242 // We'll do the relevant checks on defaulted / deleted functions later.
10243 switch (D.getFunctionDefinitionKind()) {
10244 case FunctionDefinitionKind::Declaration:
10245 case FunctionDefinitionKind::Definition:
10246 break;
10247
10248 case FunctionDefinitionKind::Defaulted:
10249 NewFD->setDefaulted();
10250 break;
10251
10252 case FunctionDefinitionKind::Deleted:
10253 NewFD->setDeletedAsWritten();
10254 break;
10255 }
10256
10257 if (isa<CXXMethodDecl>(Val: NewFD) && DC == CurContext &&
10258 D.isFunctionDefinition() && !isInline) {
10259 // Pre C++20 [class.mfct]p2:
10260 // A member function may be defined (8.4) in its class definition, in
10261 // which case it is an inline member function (7.1.2)
10262 // Post C++20 [class.mfct]p1:
10263 // If a member function is attached to the global module and is defined
10264 // in its class definition, it is inline.
10265 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10266 }
10267
10268 if (SC == SC_Static && isa<CXXMethodDecl>(Val: NewFD) &&
10269 !CurContext->isRecord()) {
10270 // C++ [class.static]p1:
10271 // A data or function member of a class may be declared static
10272 // in a class definition, in which case it is a static member of
10273 // the class.
10274
10275 // Complain about the 'static' specifier if it's on an out-of-line
10276 // member function definition.
10277
10278 // MSVC permits the use of a 'static' storage specifier on an out-of-line
10279 // member function template declaration and class member template
10280 // declaration (MSVC versions before 2015), warn about this.
10281 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10282 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10283 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10284 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
10285 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
10286 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10287 }
10288
10289 // C++11 [except.spec]p15:
10290 // A deallocation function with no exception-specification is treated
10291 // as if it were specified with noexcept(true).
10292 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10293 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10294 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10295 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10296 NewFD->setType(Context.getFunctionType(
10297 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
10298 EPI: FPT->getExtProtoInfo().withExceptionSpec(ESI: EST_BasicNoexcept)));
10299
10300 // C++20 [dcl.inline]/7
10301 // If an inline function or variable that is attached to a named module
10302 // is declared in a definition domain, it shall be defined in that
10303 // domain.
10304 // So, if the current declaration does not have a definition, we must
10305 // check at the end of the TU (or when the PMF starts) to see that we
10306 // have a definition at that point.
10307 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10308 NewFD->hasOwningModule() && NewFD->getOwningModule()->isNamedModule()) {
10309 PendingInlineFuncDecls.insert(Ptr: NewFD);
10310 }
10311 }
10312
10313 // Filter out previous declarations that don't match the scope.
10314 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(FD: NewFD),
10315 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
10316 isMemberSpecialization ||
10317 isFunctionTemplateSpecialization);
10318
10319 // Handle GNU asm-label extension (encoded as an attribute).
10320 if (Expr *E = (Expr*) D.getAsmLabel()) {
10321 // The parser guarantees this is a string.
10322 StringLiteral *SE = cast<StringLiteral>(Val: E);
10323 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10324 /*IsLiteralLabel=*/true,
10325 SE->getStrTokenLoc(0)));
10326 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10327 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10328 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
10329 if (I != ExtnameUndeclaredIdentifiers.end()) {
10330 if (isDeclExternC(NewFD)) {
10331 NewFD->addAttr(A: I->second);
10332 ExtnameUndeclaredIdentifiers.erase(I);
10333 } else
10334 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10335 << /*Variable*/0 << NewFD;
10336 }
10337 }
10338
10339 // Copy the parameter declarations from the declarator D to the function
10340 // declaration NewFD, if they are available. First scavenge them into Params.
10341 SmallVector<ParmVarDecl*, 16> Params;
10342 unsigned FTIIdx;
10343 if (D.isFunctionDeclarator(idx&: FTIIdx)) {
10344 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(i: FTIIdx).Fun;
10345
10346 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10347 // function that takes no arguments, not a function that takes a
10348 // single void argument.
10349 // We let through "const void" here because Sema::GetTypeForDeclarator
10350 // already checks for that case.
10351 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10352 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10353 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
10354 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10355 Param->setDeclContext(NewFD);
10356 Params.push_back(Elt: Param);
10357
10358 if (Param->isInvalidDecl())
10359 NewFD->setInvalidDecl();
10360 }
10361 }
10362
10363 if (!getLangOpts().CPlusPlus) {
10364 // In C, find all the tag declarations from the prototype and move them
10365 // into the function DeclContext. Remove them from the surrounding tag
10366 // injection context of the function, which is typically but not always
10367 // the TU.
10368 DeclContext *PrototypeTagContext =
10369 getTagInjectionContext(NewFD->getLexicalDeclContext());
10370 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10371 auto *TD = dyn_cast<TagDecl>(Val: NonParmDecl);
10372
10373 // We don't want to reparent enumerators. Look at their parent enum
10374 // instead.
10375 if (!TD) {
10376 if (auto *ECD = dyn_cast<EnumConstantDecl>(Val: NonParmDecl))
10377 TD = cast<EnumDecl>(ECD->getDeclContext());
10378 }
10379 if (!TD)
10380 continue;
10381 DeclContext *TagDC = TD->getLexicalDeclContext();
10382 if (!TagDC->containsDecl(TD))
10383 continue;
10384 TagDC->removeDecl(TD);
10385 TD->setDeclContext(NewFD);
10386 NewFD->addDecl(TD);
10387
10388 // Preserve the lexical DeclContext if it is not the surrounding tag
10389 // injection context of the FD. In this example, the semantic context of
10390 // E will be f and the lexical context will be S, while both the
10391 // semantic and lexical contexts of S will be f:
10392 // void f(struct S { enum E { a } f; } s);
10393 if (TagDC != PrototypeTagContext)
10394 TD->setLexicalDeclContext(TagDC);
10395 }
10396 }
10397 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10398 // When we're declaring a function with a typedef, typeof, etc as in the
10399 // following example, we'll need to synthesize (unnamed)
10400 // parameters for use in the declaration.
10401 //
10402 // @code
10403 // typedef void fn(int);
10404 // fn f;
10405 // @endcode
10406
10407 // Synthesize a parameter for each argument type.
10408 for (const auto &AI : FT->param_types()) {
10409 ParmVarDecl *Param =
10410 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10411 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
10412 Params.push_back(Elt: Param);
10413 }
10414 } else {
10415 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10416 "Should not need args for typedef of non-prototype fn");
10417 }
10418
10419 // Finally, we know we have the right number of parameters, install them.
10420 NewFD->setParams(Params);
10421
10422 if (D.getDeclSpec().isNoreturnSpecified())
10423 NewFD->addAttr(
10424 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10425
10426 // Functions returning a variably modified type violate C99 6.7.5.2p2
10427 // because all functions have linkage.
10428 if (!NewFD->isInvalidDecl() &&
10429 NewFD->getReturnType()->isVariablyModifiedType()) {
10430 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10431 NewFD->setInvalidDecl();
10432 }
10433
10434 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10435 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10436 !NewFD->hasAttr<SectionAttr>())
10437 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10438 Context, PragmaClangTextSection.SectionName,
10439 PragmaClangTextSection.PragmaLocation));
10440
10441 // Apply an implicit SectionAttr if #pragma code_seg is active.
10442 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10443 !NewFD->hasAttr<SectionAttr>()) {
10444 NewFD->addAttr(SectionAttr::CreateImplicit(
10445 Context, CodeSegStack.CurrentValue->getString(),
10446 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10447 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10448 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10449 ASTContext::PSF_Read,
10450 NewFD))
10451 NewFD->dropAttr<SectionAttr>();
10452 }
10453
10454 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10455 // active.
10456 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10457 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10458 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10459 Context, PragmaClangTextSection.PragmaLocation));
10460
10461 // Apply an implicit CodeSegAttr from class declspec or
10462 // apply an implicit SectionAttr from #pragma code_seg if active.
10463 if (!NewFD->hasAttr<CodeSegAttr>()) {
10464 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(FD: NewFD,
10465 IsDefinition: D.isFunctionDefinition())) {
10466 NewFD->addAttr(SAttr);
10467 }
10468 }
10469
10470 // Handle attributes.
10471 ProcessDeclAttributes(S, NewFD, D);
10472 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10473 if (NewTVA && !NewTVA->isDefaultVersion() &&
10474 !Context.getTargetInfo().hasFeature(Feature: "fmv")) {
10475 // Don't add to scope fmv functions declarations if fmv disabled
10476 AddToScope = false;
10477 return NewFD;
10478 }
10479
10480 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10481 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10482 // type.
10483 //
10484 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10485 // type declaration will generate a compilation error.
10486 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10487 if (AddressSpace != LangAS::Default) {
10488 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10489 NewFD->setInvalidDecl();
10490 }
10491 }
10492
10493 if (!getLangOpts().CPlusPlus) {
10494 // Perform semantic checking on the function declaration.
10495 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10496 CheckMain(FD: NewFD, D: D.getDeclSpec());
10497
10498 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10499 CheckMSVCRTEntryPoint(FD: NewFD);
10500
10501 if (!NewFD->isInvalidDecl())
10502 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10503 IsMemberSpecialization: isMemberSpecialization,
10504 DeclIsDefn: D.isFunctionDefinition()));
10505 else if (!Previous.empty())
10506 // Recover gracefully from an invalid redeclaration.
10507 D.setRedeclaration(true);
10508 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10509 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10510 "previous declaration set still overloaded");
10511
10512 // Diagnose no-prototype function declarations with calling conventions that
10513 // don't support variadic calls. Only do this in C and do it after merging
10514 // possibly prototyped redeclarations.
10515 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10516 if (isa<FunctionNoProtoType>(Val: FT) && !D.isFunctionDefinition()) {
10517 CallingConv CC = FT->getExtInfo().getCC();
10518 if (!supportsVariadicCall(CC)) {
10519 // Windows system headers sometimes accidentally use stdcall without
10520 // (void) parameters, so we relax this to a warning.
10521 int DiagID =
10522 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10523 Diag(NewFD->getLocation(), DiagID)
10524 << FunctionType::getNameForCallConv(CC);
10525 }
10526 }
10527
10528 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10529 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10530 checkNonTrivialCUnion(QT: NewFD->getReturnType(),
10531 Loc: NewFD->getReturnTypeSourceRange().getBegin(),
10532 UseContext: NTCUC_FunctionReturn, NonTrivialKind: NTCUK_Destruct|NTCUK_Copy);
10533 } else {
10534 // C++11 [replacement.functions]p3:
10535 // The program's definitions shall not be specified as inline.
10536 //
10537 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10538 //
10539 // Suppress the diagnostic if the function is __attribute__((used)), since
10540 // that forces an external definition to be emitted.
10541 if (D.getDeclSpec().isInlineSpecified() &&
10542 NewFD->isReplaceableGlobalAllocationFunction() &&
10543 !NewFD->hasAttr<UsedAttr>())
10544 Diag(D.getDeclSpec().getInlineSpecLoc(),
10545 diag::ext_operator_new_delete_declared_inline)
10546 << NewFD->getDeclName();
10547
10548 if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
10549 // C++20 [dcl.decl.general]p4:
10550 // The optional requires-clause in an init-declarator or
10551 // member-declarator shall be present only if the declarator declares a
10552 // templated function.
10553 //
10554 // C++20 [temp.pre]p8:
10555 // An entity is templated if it is
10556 // - a template,
10557 // - an entity defined or created in a templated entity,
10558 // - a member of a templated entity,
10559 // - an enumerator for an enumeration that is a templated entity, or
10560 // - the closure type of a lambda-expression appearing in the
10561 // declaration of a templated entity.
10562 //
10563 // [Note 6: A local class, a local or block variable, or a friend
10564 // function defined in a templated entity is a templated entity.
10565 // — end note]
10566 //
10567 // A templated function is a function template or a function that is
10568 // templated. A templated class is a class template or a class that is
10569 // templated. A templated variable is a variable template or a variable
10570 // that is templated.
10571 if (!FunctionTemplate) {
10572 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10573 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10574 // An explicit specialization shall not have a trailing
10575 // requires-clause unless it declares a function template.
10576 //
10577 // Since a friend function template specialization cannot be
10578 // definition, and since a non-template friend declaration with a
10579 // trailing requires-clause must be a definition, we diagnose
10580 // friend function template specializations with trailing
10581 // requires-clauses on the same path as explicit specializations
10582 // even though they aren't necessarily prohibited by the same
10583 // language rule.
10584 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10585 << isFriend;
10586 } else if (isFriend && NewFD->isTemplated() &&
10587 !D.isFunctionDefinition()) {
10588 // C++ [temp.friend]p9:
10589 // A non-template friend declaration with a requires-clause shall be
10590 // a definition.
10591 Diag(NewFD->getBeginLoc(),
10592 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10593 NewFD->setInvalidDecl();
10594 } else if (!NewFD->isTemplated() ||
10595 !(isa<CXXMethodDecl>(Val: NewFD) || D.isFunctionDefinition())) {
10596 Diag(TRC->getBeginLoc(),
10597 diag::err_constrained_non_templated_function);
10598 }
10599 }
10600 }
10601
10602 // We do not add HD attributes to specializations here because
10603 // they may have different constexpr-ness compared to their
10604 // templates and, after maybeAddHostDeviceAttrs() is applied,
10605 // may end up with different effective targets. Instead, a
10606 // specialization inherits its target attributes from its template
10607 // in the CheckFunctionTemplateSpecialization() call below.
10608 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10609 CUDA().maybeAddHostDeviceAttrs(FD: NewFD, Previous);
10610
10611 // Handle explict specializations of function templates
10612 // and friend function declarations with an explicit
10613 // template argument list.
10614 if (isFunctionTemplateSpecialization) {
10615 bool isDependentSpecialization = false;
10616 if (isFriend) {
10617 // For friend function specializations, this is a dependent
10618 // specialization if its semantic context is dependent, its
10619 // type is dependent, or if its template-id is dependent.
10620 isDependentSpecialization =
10621 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10622 (HasExplicitTemplateArgs &&
10623 TemplateSpecializationType::
10624 anyInstantiationDependentTemplateArguments(
10625 Args: TemplateArgs.arguments()));
10626 assert((!isDependentSpecialization ||
10627 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10628 "dependent friend function specialization without template "
10629 "args");
10630 } else {
10631 // For class-scope explicit specializations of function templates,
10632 // if the lexical context is dependent, then the specialization
10633 // is dependent.
10634 isDependentSpecialization =
10635 CurContext->isRecord() && CurContext->isDependentContext();
10636 }
10637
10638 TemplateArgumentListInfo *ExplicitTemplateArgs =
10639 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10640 if (isDependentSpecialization) {
10641 // If it's a dependent specialization, it may not be possible
10642 // to determine the primary template (for explicit specializations)
10643 // or befriended declaration (for friends) until the enclosing
10644 // template is instantiated. In such cases, we store the declarations
10645 // found by name lookup and defer resolution until instantiation.
10646 if (CheckDependentFunctionTemplateSpecialization(
10647 FD: NewFD, ExplicitTemplateArgs, Previous))
10648 NewFD->setInvalidDecl();
10649 } else if (!NewFD->isInvalidDecl()) {
10650 if (CheckFunctionTemplateSpecialization(FD: NewFD, ExplicitTemplateArgs,
10651 Previous))
10652 NewFD->setInvalidDecl();
10653 }
10654
10655 // C++ [dcl.stc]p1:
10656 // A storage-class-specifier shall not be specified in an explicit
10657 // specialization (14.7.3)
10658 // FIXME: We should be checking this for dependent specializations.
10659 FunctionTemplateSpecializationInfo *Info =
10660 NewFD->getTemplateSpecializationInfo();
10661 if (Info && SC != SC_None) {
10662 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10663 Diag(NewFD->getLocation(),
10664 diag::err_explicit_specialization_inconsistent_storage_class)
10665 << SC
10666 << FixItHint::CreateRemoval(
10667 D.getDeclSpec().getStorageClassSpecLoc());
10668
10669 else
10670 Diag(NewFD->getLocation(),
10671 diag::ext_explicit_specialization_storage_class)
10672 << FixItHint::CreateRemoval(
10673 D.getDeclSpec().getStorageClassSpecLoc());
10674 }
10675 } else if (isMemberSpecialization && isa<CXXMethodDecl>(Val: NewFD)) {
10676 if (CheckMemberSpecialization(NewFD, Previous))
10677 NewFD->setInvalidDecl();
10678 }
10679
10680 // Perform semantic checking on the function declaration.
10681 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10682 CheckMain(FD: NewFD, D: D.getDeclSpec());
10683
10684 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10685 CheckMSVCRTEntryPoint(FD: NewFD);
10686
10687 if (!NewFD->isInvalidDecl())
10688 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10689 IsMemberSpecialization: isMemberSpecialization,
10690 DeclIsDefn: D.isFunctionDefinition()));
10691 else if (!Previous.empty())
10692 // Recover gracefully from an invalid redeclaration.
10693 D.setRedeclaration(true);
10694
10695 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10696 !D.isRedeclaration() ||
10697 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10698 "previous declaration set still overloaded");
10699
10700 NamedDecl *PrincipalDecl = (FunctionTemplate
10701 ? cast<NamedDecl>(Val: FunctionTemplate)
10702 : NewFD);
10703
10704 if (isFriend && NewFD->getPreviousDecl()) {
10705 AccessSpecifier Access = AS_public;
10706 if (!NewFD->isInvalidDecl())
10707 Access = NewFD->getPreviousDecl()->getAccess();
10708
10709 NewFD->setAccess(Access);
10710 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10711 }
10712
10713 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10714 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10715 PrincipalDecl->setNonMemberOperator();
10716
10717 // If we have a function template, check the template parameter
10718 // list. This will check and merge default template arguments.
10719 if (FunctionTemplate) {
10720 FunctionTemplateDecl *PrevTemplate =
10721 FunctionTemplate->getPreviousDecl();
10722 CheckTemplateParameterList(NewParams: FunctionTemplate->getTemplateParameters(),
10723 OldParams: PrevTemplate ? PrevTemplate->getTemplateParameters()
10724 : nullptr,
10725 TPC: D.getDeclSpec().isFriendSpecified()
10726 ? (D.isFunctionDefinition()
10727 ? TPC_FriendFunctionTemplateDefinition
10728 : TPC_FriendFunctionTemplate)
10729 : (D.getCXXScopeSpec().isSet() &&
10730 DC && DC->isRecord() &&
10731 DC->isDependentContext())
10732 ? TPC_ClassTemplateMember
10733 : TPC_FunctionTemplate);
10734 }
10735
10736 if (NewFD->isInvalidDecl()) {
10737 // Ignore all the rest of this.
10738 } else if (!D.isRedeclaration()) {
10739 struct ActOnFDArgs ExtraArgs = { .S: S, .D: D, .TemplateParamLists: TemplateParamLists,
10740 .AddToScope: AddToScope };
10741 // Fake up an access specifier if it's supposed to be a class member.
10742 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10743 NewFD->setAccess(AS_public);
10744
10745 // Qualified decls generally require a previous declaration.
10746 if (D.getCXXScopeSpec().isSet()) {
10747 // ...with the major exception of templated-scope or
10748 // dependent-scope friend declarations.
10749
10750 // TODO: we currently also suppress this check in dependent
10751 // contexts because (1) the parameter depth will be off when
10752 // matching friend templates and (2) we might actually be
10753 // selecting a friend based on a dependent factor. But there
10754 // are situations where these conditions don't apply and we
10755 // can actually do this check immediately.
10756 //
10757 // Unless the scope is dependent, it's always an error if qualified
10758 // redeclaration lookup found nothing at all. Diagnose that now;
10759 // nothing will diagnose that error later.
10760 if (isFriend &&
10761 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10762 (!Previous.empty() && CurContext->isDependentContext()))) {
10763 // ignore these
10764 } else if (NewFD->isCPUDispatchMultiVersion() ||
10765 NewFD->isCPUSpecificMultiVersion()) {
10766 // ignore this, we allow the redeclaration behavior here to create new
10767 // versions of the function.
10768 } else {
10769 // The user tried to provide an out-of-line definition for a
10770 // function that is a member of a class or namespace, but there
10771 // was no such member function declared (C++ [class.mfct]p2,
10772 // C++ [namespace.memdef]p2). For example:
10773 //
10774 // class X {
10775 // void f() const;
10776 // };
10777 //
10778 // void X::f() { } // ill-formed
10779 //
10780 // Complain about this problem, and attempt to suggest close
10781 // matches (e.g., those that differ only in cv-qualifiers and
10782 // whether the parameter types are references).
10783
10784 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10785 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: false, S: nullptr)) {
10786 AddToScope = ExtraArgs.AddToScope;
10787 return Result;
10788 }
10789 }
10790
10791 // Unqualified local friend declarations are required to resolve
10792 // to something.
10793 } else if (isFriend && cast<CXXRecordDecl>(Val: CurContext)->isLocalClass()) {
10794 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10795 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: true, S)) {
10796 AddToScope = ExtraArgs.AddToScope;
10797 return Result;
10798 }
10799 }
10800 } else if (!D.isFunctionDefinition() &&
10801 isa<CXXMethodDecl>(Val: NewFD) && NewFD->isOutOfLine() &&
10802 !isFriend && !isFunctionTemplateSpecialization &&
10803 !isMemberSpecialization) {
10804 // An out-of-line member function declaration must also be a
10805 // definition (C++ [class.mfct]p2).
10806 // Note that this is not the case for explicit specializations of
10807 // function templates or member functions of class templates, per
10808 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10809 // extension for compatibility with old SWIG code which likes to
10810 // generate them.
10811 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10812 << D.getCXXScopeSpec().getRange();
10813 }
10814 }
10815
10816 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10817 // Any top level function could potentially be specified as an entry.
10818 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10819 HLSL().ActOnTopLevelFunction(FD: NewFD);
10820
10821 if (NewFD->hasAttr<HLSLShaderAttr>())
10822 HLSL().CheckEntryPoint(FD: NewFD);
10823 }
10824
10825 // If this is the first declaration of a library builtin function, add
10826 // attributes as appropriate.
10827 if (!D.isRedeclaration()) {
10828 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10829 if (unsigned BuiltinID = II->getBuiltinID()) {
10830 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID);
10831 if (!InStdNamespace &&
10832 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10833 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10834 // Validate the type matches unless this builtin is specified as
10835 // matching regardless of its declared type.
10836 if (Context.BuiltinInfo.allowTypeMismatch(ID: BuiltinID)) {
10837 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10838 } else {
10839 ASTContext::GetBuiltinTypeError Error;
10840 LookupNecessaryTypesForBuiltin(S, ID: BuiltinID);
10841 QualType BuiltinType = Context.GetBuiltinType(ID: BuiltinID, Error);
10842
10843 if (!Error && !BuiltinType.isNull() &&
10844 Context.hasSameFunctionTypeIgnoringExceptionSpec(
10845 NewFD->getType(), BuiltinType))
10846 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10847 }
10848 }
10849 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10850 isStdBuiltin(Ctx&: Context, FD: NewFD, BuiltinID)) {
10851 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10852 }
10853 }
10854 }
10855 }
10856
10857 ProcessPragmaWeak(S, NewFD);
10858 checkAttributesAfterMerging(*this, *NewFD);
10859
10860 AddKnownFunctionAttributes(FD: NewFD);
10861
10862 if (NewFD->hasAttr<OverloadableAttr>() &&
10863 !NewFD->getType()->getAs<FunctionProtoType>()) {
10864 Diag(NewFD->getLocation(),
10865 diag::err_attribute_overloadable_no_prototype)
10866 << NewFD;
10867 NewFD->dropAttr<OverloadableAttr>();
10868 }
10869
10870 // If there's a #pragma GCC visibility in scope, and this isn't a class
10871 // member, set the visibility of this function.
10872 if (!DC->isRecord() && NewFD->isExternallyVisible())
10873 AddPushedVisibilityAttribute(NewFD);
10874
10875 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10876 // marking the function.
10877 AddCFAuditedAttribute(NewFD);
10878
10879 // If this is a function definition, check if we have to apply any
10880 // attributes (i.e. optnone and no_builtin) due to a pragma.
10881 if (D.isFunctionDefinition()) {
10882 AddRangeBasedOptnone(FD: NewFD);
10883 AddImplicitMSFunctionNoBuiltinAttr(FD: NewFD);
10884 AddSectionMSAllocText(FD: NewFD);
10885 ModifyFnAttributesMSPragmaOptimize(FD: NewFD);
10886 }
10887
10888 // If this is the first declaration of an extern C variable, update
10889 // the map of such variables.
10890 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10891 isIncompleteDeclExternC(S&: *this, D: NewFD))
10892 RegisterLocallyScopedExternCDecl(NewFD, S);
10893
10894 // Set this FunctionDecl's range up to the right paren.
10895 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10896
10897 if (D.isRedeclaration() && !Previous.empty()) {
10898 NamedDecl *Prev = Previous.getRepresentativeDecl();
10899 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10900 isMemberSpecialization ||
10901 isFunctionTemplateSpecialization,
10902 D.isFunctionDefinition());
10903 }
10904
10905 if (getLangOpts().CUDA) {
10906 IdentifierInfo *II = NewFD->getIdentifier();
10907 if (II && II->isStr(Str: CUDA().getConfigureFuncName()) &&
10908 !NewFD->isInvalidDecl() &&
10909 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10910 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10911 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10912 << CUDA().getConfigureFuncName();
10913 Context.setcudaConfigureCallDecl(NewFD);
10914 }
10915
10916 // Variadic functions, other than a *declaration* of printf, are not allowed
10917 // in device-side CUDA code, unless someone passed
10918 // -fcuda-allow-variadic-functions.
10919 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10920 (NewFD->hasAttr<CUDADeviceAttr>() ||
10921 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10922 !(II && II->isStr("printf") && NewFD->isExternC() &&
10923 !D.isFunctionDefinition())) {
10924 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10925 }
10926 }
10927
10928 MarkUnusedFileScopedDecl(NewFD);
10929
10930
10931
10932 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10933 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10934 if (SC == SC_Static) {
10935 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10936 D.setInvalidType();
10937 }
10938
10939 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10940 if (!NewFD->getReturnType()->isVoidType()) {
10941 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10942 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10943 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10944 : FixItHint());
10945 D.setInvalidType();
10946 }
10947
10948 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10949 for (auto *Param : NewFD->parameters())
10950 checkIsValidOpenCLKernelParameter(S&: *this, D, Param, ValidTypes);
10951
10952 if (getLangOpts().OpenCLCPlusPlus) {
10953 if (DC->isRecord()) {
10954 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10955 D.setInvalidType();
10956 }
10957 if (FunctionTemplate) {
10958 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10959 D.setInvalidType();
10960 }
10961 }
10962 }
10963
10964 if (getLangOpts().CPlusPlus) {
10965 // Precalculate whether this is a friend function template with a constraint
10966 // that depends on an enclosing template, per [temp.friend]p9.
10967 if (isFriend && FunctionTemplate &&
10968 FriendConstraintsDependOnEnclosingTemplate(FD: NewFD)) {
10969 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
10970
10971 // C++ [temp.friend]p9:
10972 // A friend function template with a constraint that depends on a
10973 // template parameter from an enclosing template shall be a definition.
10974 if (!D.isFunctionDefinition()) {
10975 Diag(NewFD->getBeginLoc(),
10976 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
10977 NewFD->setInvalidDecl();
10978 }
10979 }
10980
10981 if (FunctionTemplate) {
10982 if (NewFD->isInvalidDecl())
10983 FunctionTemplate->setInvalidDecl();
10984 return FunctionTemplate;
10985 }
10986
10987 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10988 CompleteMemberSpecialization(NewFD, Previous);
10989 }
10990
10991 for (const ParmVarDecl *Param : NewFD->parameters()) {
10992 QualType PT = Param->getType();
10993
10994 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10995 // types.
10996 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10997 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10998 QualType ElemTy = PipeTy->getElementType();
10999 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
11000 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
11001 D.setInvalidType();
11002 }
11003 }
11004 }
11005 // WebAssembly tables can't be used as function parameters.
11006 if (Context.getTargetInfo().getTriple().isWasm()) {
11007 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
11008 Diag(Param->getTypeSpecStartLoc(),
11009 diag::err_wasm_table_as_function_parameter);
11010 D.setInvalidType();
11011 }
11012 }
11013 }
11014
11015 // Diagnose availability attributes. Availability cannot be used on functions
11016 // that are run during load/unload.
11017 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11018 if (NewFD->hasAttr<ConstructorAttr>()) {
11019 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11020 << 1;
11021 NewFD->dropAttr<AvailabilityAttr>();
11022 }
11023 if (NewFD->hasAttr<DestructorAttr>()) {
11024 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11025 << 2;
11026 NewFD->dropAttr<AvailabilityAttr>();
11027 }
11028 }
11029
11030 // Diagnose no_builtin attribute on function declaration that are not a
11031 // definition.
11032 // FIXME: We should really be doing this in
11033 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11034 // the FunctionDecl and at this point of the code
11035 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11036 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11037 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11038 switch (D.getFunctionDefinitionKind()) {
11039 case FunctionDefinitionKind::Defaulted:
11040 case FunctionDefinitionKind::Deleted:
11041 Diag(NBA->getLocation(),
11042 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11043 << NBA->getSpelling();
11044 break;
11045 case FunctionDefinitionKind::Declaration:
11046 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11047 << NBA->getSpelling();
11048 break;
11049 case FunctionDefinitionKind::Definition:
11050 break;
11051 }
11052
11053 return NewFD;
11054}
11055
11056/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11057/// when __declspec(code_seg) "is applied to a class, all member functions of
11058/// the class and nested classes -- this includes compiler-generated special
11059/// member functions -- are put in the specified segment."
11060/// The actual behavior is a little more complicated. The Microsoft compiler
11061/// won't check outer classes if there is an active value from #pragma code_seg.
11062/// The CodeSeg is always applied from the direct parent but only from outer
11063/// classes when the #pragma code_seg stack is empty. See:
11064/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11065/// available since MS has removed the page.
11066static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
11067 const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
11068 if (!Method)
11069 return nullptr;
11070 const CXXRecordDecl *Parent = Method->getParent();
11071 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11072 Attr *NewAttr = SAttr->clone(S.getASTContext());
11073 NewAttr->setImplicit(true);
11074 return NewAttr;
11075 }
11076
11077 // The Microsoft compiler won't check outer classes for the CodeSeg
11078 // when the #pragma code_seg stack is active.
11079 if (S.CodeSegStack.CurrentValue)
11080 return nullptr;
11081
11082 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11083 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11084 Attr *NewAttr = SAttr->clone(S.getASTContext());
11085 NewAttr->setImplicit(true);
11086 return NewAttr;
11087 }
11088 }
11089 return nullptr;
11090}
11091
11092/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
11093/// containing class. Otherwise it will return implicit SectionAttr if the
11094/// function is a definition and there is an active value on CodeSegStack
11095/// (from the current #pragma code-seg value).
11096///
11097/// \param FD Function being declared.
11098/// \param IsDefinition Whether it is a definition or just a declaration.
11099/// \returns A CodeSegAttr or SectionAttr to apply to the function or
11100/// nullptr if no attribute should be added.
11101Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
11102 bool IsDefinition) {
11103 if (Attr *A = getImplicitCodeSegAttrFromClass(S&: *this, FD))
11104 return A;
11105 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11106 CodeSegStack.CurrentValue)
11107 return SectionAttr::CreateImplicit(
11108 getASTContext(), CodeSegStack.CurrentValue->getString(),
11109 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11110 return nullptr;
11111}
11112
11113/// Determines if we can perform a correct type check for \p D as a
11114/// redeclaration of \p PrevDecl. If not, we can generally still perform a
11115/// best-effort check.
11116///
11117/// \param NewD The new declaration.
11118/// \param OldD The old declaration.
11119/// \param NewT The portion of the type of the new declaration to check.
11120/// \param OldT The portion of the type of the old declaration to check.
11121bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
11122 QualType NewT, QualType OldT) {
11123 if (!NewD->getLexicalDeclContext()->isDependentContext())
11124 return true;
11125
11126 // For dependently-typed local extern declarations and friends, we can't
11127 // perform a correct type check in general until instantiation:
11128 //
11129 // int f();
11130 // template<typename T> void g() { T f(); }
11131 //
11132 // (valid if g() is only instantiated with T = int).
11133 if (NewT->isDependentType() &&
11134 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11135 return false;
11136
11137 // Similarly, if the previous declaration was a dependent local extern
11138 // declaration, we don't really know its type yet.
11139 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11140 return false;
11141
11142 return true;
11143}
11144
11145/// Checks if the new declaration declared in dependent context must be
11146/// put in the same redeclaration chain as the specified declaration.
11147///
11148/// \param D Declaration that is checked.
11149/// \param PrevDecl Previous declaration found with proper lookup method for the
11150/// same declaration name.
11151/// \returns True if D must be added to the redeclaration chain which PrevDecl
11152/// belongs to.
11153///
11154bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11155 if (!D->getLexicalDeclContext()->isDependentContext())
11156 return true;
11157
11158 // Don't chain dependent friend function definitions until instantiation, to
11159 // permit cases like
11160 //
11161 // void func();
11162 // template<typename T> class C1 { friend void func() {} };
11163 // template<typename T> class C2 { friend void func() {} };
11164 //
11165 // ... which is valid if only one of C1 and C2 is ever instantiated.
11166 //
11167 // FIXME: This need only apply to function definitions. For now, we proxy
11168 // this by checking for a file-scope function. We do not want this to apply
11169 // to friend declarations nominating member functions, because that gets in
11170 // the way of access checks.
11171 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11172 return false;
11173
11174 auto *VD = dyn_cast<ValueDecl>(Val: D);
11175 auto *PrevVD = dyn_cast<ValueDecl>(Val: PrevDecl);
11176 return !VD || !PrevVD ||
11177 canFullyTypeCheckRedeclaration(NewD: VD, OldD: PrevVD, NewT: VD->getType(),
11178 OldT: PrevVD->getType());
11179}
11180
11181/// Check the target or target_version attribute of the function for
11182/// MultiVersion validity.
11183///
11184/// Returns true if there was an error, false otherwise.
11185static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11186 const auto *TA = FD->getAttr<TargetAttr>();
11187 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11188 assert(
11189 (TA || TVA) &&
11190 "MultiVersion candidate requires a target or target_version attribute");
11191 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11192 enum ErrType { Feature = 0, Architecture = 1 };
11193
11194 if (TA) {
11195 ParsedTargetAttr ParseInfo =
11196 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TA->getFeaturesStr());
11197 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(Name: ParseInfo.CPU)) {
11198 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11199 << Architecture << ParseInfo.CPU;
11200 return true;
11201 }
11202 for (const auto &Feat : ParseInfo.Features) {
11203 auto BareFeat = StringRef{Feat}.substr(1);
11204 if (Feat[0] == '-') {
11205 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11206 << Feature << ("no-" + BareFeat).str();
11207 return true;
11208 }
11209
11210 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11211 !TargetInfo.isValidFeatureName(BareFeat)) {
11212 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11213 << Feature << BareFeat;
11214 return true;
11215 }
11216 }
11217 }
11218
11219 if (TVA) {
11220 llvm::SmallVector<StringRef, 8> Feats;
11221 TVA->getFeatures(Feats);
11222 for (const auto &Feat : Feats) {
11223 if (!TargetInfo.validateCpuSupports(Name: Feat)) {
11224 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11225 << Feature << Feat;
11226 return true;
11227 }
11228 }
11229 }
11230 return false;
11231}
11232
11233// Provide a white-list of attributes that are allowed to be combined with
11234// multiversion functions.
11235static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11236 MultiVersionKind MVKind) {
11237 // Note: this list/diagnosis must match the list in
11238 // checkMultiversionAttributesAllSame.
11239 switch (Kind) {
11240 default:
11241 return false;
11242 case attr::Used:
11243 return MVKind == MultiVersionKind::Target;
11244 case attr::NonNull:
11245 case attr::NoThrow:
11246 return true;
11247 }
11248}
11249
11250static bool checkNonMultiVersionCompatAttributes(Sema &S,
11251 const FunctionDecl *FD,
11252 const FunctionDecl *CausedFD,
11253 MultiVersionKind MVKind) {
11254 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11255 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11256 << static_cast<unsigned>(MVKind) << A;
11257 if (CausedFD)
11258 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11259 return true;
11260 };
11261
11262 for (const Attr *A : FD->attrs()) {
11263 switch (A->getKind()) {
11264 case attr::CPUDispatch:
11265 case attr::CPUSpecific:
11266 if (MVKind != MultiVersionKind::CPUDispatch &&
11267 MVKind != MultiVersionKind::CPUSpecific)
11268 return Diagnose(S, A);
11269 break;
11270 case attr::Target:
11271 if (MVKind != MultiVersionKind::Target)
11272 return Diagnose(S, A);
11273 break;
11274 case attr::TargetVersion:
11275 if (MVKind != MultiVersionKind::TargetVersion &&
11276 MVKind != MultiVersionKind::TargetClones)
11277 return Diagnose(S, A);
11278 break;
11279 case attr::TargetClones:
11280 if (MVKind != MultiVersionKind::TargetClones &&
11281 MVKind != MultiVersionKind::TargetVersion)
11282 return Diagnose(S, A);
11283 break;
11284 default:
11285 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11286 return Diagnose(S, A);
11287 break;
11288 }
11289 }
11290 return false;
11291}
11292
11293bool Sema::areMultiversionVariantFunctionsCompatible(
11294 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11295 const PartialDiagnostic &NoProtoDiagID,
11296 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11297 const PartialDiagnosticAt &NoSupportDiagIDAt,
11298 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11299 bool ConstexprSupported, bool CLinkageMayDiffer) {
11300 enum DoesntSupport {
11301 FuncTemplates = 0,
11302 VirtFuncs = 1,
11303 DeducedReturn = 2,
11304 Constructors = 3,
11305 Destructors = 4,
11306 DeletedFuncs = 5,
11307 DefaultedFuncs = 6,
11308 ConstexprFuncs = 7,
11309 ConstevalFuncs = 8,
11310 Lambda = 9,
11311 };
11312 enum Different {
11313 CallingConv = 0,
11314 ReturnType = 1,
11315 ConstexprSpec = 2,
11316 InlineSpec = 3,
11317 Linkage = 4,
11318 LanguageLinkage = 5,
11319 };
11320
11321 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11322 !OldFD->getType()->getAs<FunctionProtoType>()) {
11323 Diag(OldFD->getLocation(), NoProtoDiagID);
11324 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11325 return true;
11326 }
11327
11328 if (NoProtoDiagID.getDiagID() != 0 &&
11329 !NewFD->getType()->getAs<FunctionProtoType>())
11330 return Diag(NewFD->getLocation(), NoProtoDiagID);
11331
11332 if (!TemplatesSupported &&
11333 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11334 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11335 << FuncTemplates;
11336
11337 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
11338 if (NewCXXFD->isVirtual())
11339 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11340 << VirtFuncs;
11341
11342 if (isa<CXXConstructorDecl>(Val: NewCXXFD))
11343 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11344 << Constructors;
11345
11346 if (isa<CXXDestructorDecl>(Val: NewCXXFD))
11347 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11348 << Destructors;
11349 }
11350
11351 if (NewFD->isDeleted())
11352 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11353 << DeletedFuncs;
11354
11355 if (NewFD->isDefaulted())
11356 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11357 << DefaultedFuncs;
11358
11359 if (!ConstexprSupported && NewFD->isConstexpr())
11360 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11361 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11362
11363 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11364 const auto *NewType = cast<FunctionType>(Val&: NewQType);
11365 QualType NewReturnType = NewType->getReturnType();
11366
11367 if (NewReturnType->isUndeducedType())
11368 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11369 << DeducedReturn;
11370
11371 // Ensure the return type is identical.
11372 if (OldFD) {
11373 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11374 const auto *OldType = cast<FunctionType>(Val&: OldQType);
11375 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11376 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11377
11378 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
11379 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11380
11381 QualType OldReturnType = OldType->getReturnType();
11382
11383 if (OldReturnType != NewReturnType)
11384 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11385
11386 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11387 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11388
11389 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11390 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11391
11392 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11393 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11394
11395 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11396 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11397
11398 if (CheckEquivalentExceptionSpec(
11399 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
11400 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
11401 return true;
11402 }
11403 return false;
11404}
11405
11406static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11407 const FunctionDecl *NewFD,
11408 bool CausesMV,
11409 MultiVersionKind MVKind) {
11410 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11411 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11412 if (OldFD)
11413 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11414 return true;
11415 }
11416
11417 bool IsCPUSpecificCPUDispatchMVKind =
11418 MVKind == MultiVersionKind::CPUDispatch ||
11419 MVKind == MultiVersionKind::CPUSpecific;
11420
11421 if (CausesMV && OldFD &&
11422 checkNonMultiVersionCompatAttributes(S, FD: OldFD, CausedFD: NewFD, MVKind))
11423 return true;
11424
11425 if (checkNonMultiVersionCompatAttributes(S, FD: NewFD, CausedFD: nullptr, MVKind))
11426 return true;
11427
11428 // Only allow transition to MultiVersion if it hasn't been used.
11429 if (OldFD && CausesMV && OldFD->isUsed(false))
11430 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11431
11432 return S.areMultiversionVariantFunctionsCompatible(
11433 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11434 PartialDiagnosticAt(NewFD->getLocation(),
11435 S.PDiag(diag::note_multiversioning_caused_here)),
11436 PartialDiagnosticAt(NewFD->getLocation(),
11437 S.PDiag(diag::err_multiversion_doesnt_support)
11438 << static_cast<unsigned>(MVKind)),
11439 PartialDiagnosticAt(NewFD->getLocation(),
11440 S.PDiag(diag::err_multiversion_diff)),
11441 /*TemplatesSupported=*/false,
11442 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11443 /*CLinkageMayDiffer=*/false);
11444}
11445
11446/// Check the validity of a multiversion function declaration that is the
11447/// first of its kind. Also sets the multiversion'ness' of the function itself.
11448///
11449/// This sets NewFD->isInvalidDecl() to true if there was an error.
11450///
11451/// Returns true if there was an error, false otherwise.
11452static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11453 MultiVersionKind MVKind = FD->getMultiVersionKind();
11454 assert(MVKind != MultiVersionKind::None &&
11455 "Function lacks multiversion attribute");
11456 const auto *TA = FD->getAttr<TargetAttr>();
11457 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11458 // The target attribute only causes MV if this declaration is the default,
11459 // otherwise it is treated as a normal function.
11460 if (TA && !TA->isDefaultVersion())
11461 return false;
11462
11463 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11464 FD->setInvalidDecl();
11465 return true;
11466 }
11467
11468 if (CheckMultiVersionAdditionalRules(S, OldFD: nullptr, NewFD: FD, CausesMV: true, MVKind)) {
11469 FD->setInvalidDecl();
11470 return true;
11471 }
11472
11473 FD->setIsMultiVersion();
11474 return false;
11475}
11476
11477static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11478 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11479 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11480 return true;
11481 }
11482
11483 return false;
11484}
11485
11486static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
11487 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64())
11488 return;
11489
11490 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11491 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11492
11493 if (MVKindTo == MultiVersionKind::None &&
11494 (MVKindFrom == MultiVersionKind::TargetVersion ||
11495 MVKindFrom == MultiVersionKind::TargetClones)) {
11496 To->setIsMultiVersion();
11497 To->addAttr(TargetVersionAttr::CreateImplicit(
11498 To->getASTContext(), "default", To->getSourceRange()));
11499 }
11500}
11501
11502static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11503 FunctionDecl *NewFD,
11504 bool &Redeclaration,
11505 NamedDecl *&OldDecl,
11506 LookupResult &Previous) {
11507 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11508
11509 // The definitions should be allowed in any order. If we have discovered
11510 // a new target version and the preceeding was the default, then add the
11511 // corresponding attribute to it.
11512 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11513
11514 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11515 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11516 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11517 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11518 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11519 // to change, this is a simple redeclaration.
11520 if ((NewTA && !NewTA->isDefaultVersion() &&
11521 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) ||
11522 (NewTVA && !NewTVA->isDefaultVersion() &&
11523 (!OldTVA || OldTVA->getName() == NewTVA->getName())))
11524 return false;
11525
11526 // Otherwise, this decl causes MultiVersioning.
11527 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11528 NewTVA ? MultiVersionKind::TargetVersion
11529 : MultiVersionKind::Target)) {
11530 NewFD->setInvalidDecl();
11531 return true;
11532 }
11533
11534 if (CheckMultiVersionValue(S, FD: NewFD)) {
11535 NewFD->setInvalidDecl();
11536 return true;
11537 }
11538
11539 // If this is 'default', permit the forward declaration.
11540 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11541 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11542 Redeclaration = true;
11543 OldDecl = OldFD;
11544 OldFD->setIsMultiVersion();
11545 NewFD->setIsMultiVersion();
11546 return false;
11547 }
11548
11549 if (CheckMultiVersionValue(S, FD: OldFD)) {
11550 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11551 NewFD->setInvalidDecl();
11552 return true;
11553 }
11554
11555 if (NewTA) {
11556 ParsedTargetAttr OldParsed =
11557 S.getASTContext().getTargetInfo().parseTargetAttr(
11558 Str: OldTA->getFeaturesStr());
11559 llvm::sort(C&: OldParsed.Features);
11560 ParsedTargetAttr NewParsed =
11561 S.getASTContext().getTargetInfo().parseTargetAttr(
11562 Str: NewTA->getFeaturesStr());
11563 // Sort order doesn't matter, it just needs to be consistent.
11564 llvm::sort(C&: NewParsed.Features);
11565 if (OldParsed == NewParsed) {
11566 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11567 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11568 NewFD->setInvalidDecl();
11569 return true;
11570 }
11571 }
11572
11573 if (NewTVA) {
11574 llvm::SmallVector<StringRef, 8> Feats;
11575 OldTVA->getFeatures(Feats);
11576 llvm::sort(C&: Feats);
11577 llvm::SmallVector<StringRef, 8> NewFeats;
11578 NewTVA->getFeatures(NewFeats);
11579 llvm::sort(C&: NewFeats);
11580
11581 if (Feats == NewFeats) {
11582 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11583 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11584 NewFD->setInvalidDecl();
11585 return true;
11586 }
11587 }
11588
11589 for (const auto *FD : OldFD->redecls()) {
11590 const auto *CurTA = FD->getAttr<TargetAttr>();
11591 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11592 // We allow forward declarations before ANY multiversioning attributes, but
11593 // nothing after the fact.
11594 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11595 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11596 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11597 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11598 << (NewTA ? 0 : 2);
11599 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11600 NewFD->setInvalidDecl();
11601 return true;
11602 }
11603 }
11604
11605 OldFD->setIsMultiVersion();
11606 NewFD->setIsMultiVersion();
11607 Redeclaration = false;
11608 OldDecl = nullptr;
11609 Previous.clear();
11610 return false;
11611}
11612
11613static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {
11614 MultiVersionKind OldKind = Old->getMultiVersionKind();
11615 MultiVersionKind NewKind = New->getMultiVersionKind();
11616
11617 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11618 NewKind == MultiVersionKind::None)
11619 return true;
11620
11621 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11622 switch (OldKind) {
11623 case MultiVersionKind::TargetVersion:
11624 return NewKind == MultiVersionKind::TargetClones;
11625 case MultiVersionKind::TargetClones:
11626 return NewKind == MultiVersionKind::TargetVersion;
11627 default:
11628 return false;
11629 }
11630 } else {
11631 switch (OldKind) {
11632 case MultiVersionKind::CPUDispatch:
11633 return NewKind == MultiVersionKind::CPUSpecific;
11634 case MultiVersionKind::CPUSpecific:
11635 return NewKind == MultiVersionKind::CPUDispatch;
11636 default:
11637 return false;
11638 }
11639 }
11640}
11641
11642/// Check the validity of a new function declaration being added to an existing
11643/// multiversioned declaration collection.
11644static bool CheckMultiVersionAdditionalDecl(
11645 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11646 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11647 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11648 LookupResult &Previous) {
11649
11650 // Disallow mixing of multiversioning types.
11651 if (!MultiVersionTypesCompatible(Old: OldFD, New: NewFD)) {
11652 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11653 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11654 NewFD->setInvalidDecl();
11655 return true;
11656 }
11657
11658 // Add the default target_version attribute if it's missing.
11659 patchDefaultTargetVersion(From: OldFD, To: NewFD);
11660 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11661
11662 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11663 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11664 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11665 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11666
11667 ParsedTargetAttr NewParsed;
11668 if (NewTA) {
11669 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11670 Str: NewTA->getFeaturesStr());
11671 llvm::sort(C&: NewParsed.Features);
11672 }
11673 llvm::SmallVector<StringRef, 8> NewFeats;
11674 if (NewTVA) {
11675 NewTVA->getFeatures(NewFeats);
11676 llvm::sort(C&: NewFeats);
11677 }
11678
11679 bool UseMemberUsingDeclRules =
11680 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11681
11682 bool MayNeedOverloadableChecks =
11683 AllowOverloadingOfFunction(Previous, Context&: S.Context, New: NewFD);
11684
11685 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11686 // of a previous member of the MultiVersion set.
11687 for (NamedDecl *ND : Previous) {
11688 FunctionDecl *CurFD = ND->getAsFunction();
11689 if (!CurFD || CurFD->isInvalidDecl())
11690 continue;
11691 if (MayNeedOverloadableChecks &&
11692 S.IsOverload(New: NewFD, Old: CurFD, UseMemberUsingDeclRules))
11693 continue;
11694
11695 switch (NewMVKind) {
11696 case MultiVersionKind::None:
11697 assert(OldMVKind == MultiVersionKind::TargetClones &&
11698 "Only target_clones can be omitted in subsequent declarations");
11699 break;
11700 case MultiVersionKind::Target: {
11701 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11702 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11703 NewFD->setIsMultiVersion();
11704 Redeclaration = true;
11705 OldDecl = ND;
11706 return false;
11707 }
11708
11709 ParsedTargetAttr CurParsed =
11710 S.getASTContext().getTargetInfo().parseTargetAttr(
11711 Str: CurTA->getFeaturesStr());
11712 llvm::sort(C&: CurParsed.Features);
11713 if (CurParsed == NewParsed) {
11714 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11715 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11716 NewFD->setInvalidDecl();
11717 return true;
11718 }
11719 break;
11720 }
11721 case MultiVersionKind::TargetVersion: {
11722 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11723 if (CurTVA->getName() == NewTVA->getName()) {
11724 NewFD->setIsMultiVersion();
11725 Redeclaration = true;
11726 OldDecl = ND;
11727 return false;
11728 }
11729 llvm::SmallVector<StringRef, 8> CurFeats;
11730 CurTVA->getFeatures(CurFeats);
11731 llvm::sort(C&: CurFeats);
11732
11733 if (CurFeats == NewFeats) {
11734 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11735 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11736 NewFD->setInvalidDecl();
11737 return true;
11738 }
11739 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11740 // Default
11741 if (NewFeats.empty())
11742 break;
11743
11744 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11745 llvm::SmallVector<StringRef, 8> CurFeats;
11746 CurClones->getFeatures(CurFeats, I);
11747 llvm::sort(C&: CurFeats);
11748
11749 if (CurFeats == NewFeats) {
11750 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11751 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11752 NewFD->setInvalidDecl();
11753 return true;
11754 }
11755 }
11756 }
11757 break;
11758 }
11759 case MultiVersionKind::TargetClones: {
11760 assert(NewClones && "MultiVersionKind does not match attribute type");
11761 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11762 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11763 !std::equal(CurClones->featuresStrs_begin(),
11764 CurClones->featuresStrs_end(),
11765 NewClones->featuresStrs_begin())) {
11766 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11767 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11768 NewFD->setInvalidDecl();
11769 return true;
11770 }
11771 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11772 llvm::SmallVector<StringRef, 8> CurFeats;
11773 CurTVA->getFeatures(CurFeats);
11774 llvm::sort(C&: CurFeats);
11775
11776 // Default
11777 if (CurFeats.empty())
11778 break;
11779
11780 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11781 NewFeats.clear();
11782 NewClones->getFeatures(NewFeats, I);
11783 llvm::sort(C&: NewFeats);
11784
11785 if (CurFeats == NewFeats) {
11786 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11787 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11788 NewFD->setInvalidDecl();
11789 return true;
11790 }
11791 }
11792 break;
11793 }
11794 Redeclaration = true;
11795 OldDecl = CurFD;
11796 NewFD->setIsMultiVersion();
11797 return false;
11798 }
11799 case MultiVersionKind::CPUSpecific:
11800 case MultiVersionKind::CPUDispatch: {
11801 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11802 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11803 // Handle CPUDispatch/CPUSpecific versions.
11804 // Only 1 CPUDispatch function is allowed, this will make it go through
11805 // the redeclaration errors.
11806 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11807 CurFD->hasAttr<CPUDispatchAttr>()) {
11808 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11809 std::equal(
11810 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11811 NewCPUDisp->cpus_begin(),
11812 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11813 return Cur->getName() == New->getName();
11814 })) {
11815 NewFD->setIsMultiVersion();
11816 Redeclaration = true;
11817 OldDecl = ND;
11818 return false;
11819 }
11820
11821 // If the declarations don't match, this is an error condition.
11822 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11823 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11824 NewFD->setInvalidDecl();
11825 return true;
11826 }
11827 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11828 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11829 std::equal(
11830 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11831 NewCPUSpec->cpus_begin(),
11832 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11833 return Cur->getName() == New->getName();
11834 })) {
11835 NewFD->setIsMultiVersion();
11836 Redeclaration = true;
11837 OldDecl = ND;
11838 return false;
11839 }
11840
11841 // Only 1 version of CPUSpecific is allowed for each CPU.
11842 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11843 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11844 if (CurII == NewII) {
11845 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11846 << NewII;
11847 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11848 NewFD->setInvalidDecl();
11849 return true;
11850 }
11851 }
11852 }
11853 }
11854 break;
11855 }
11856 }
11857 }
11858
11859 // Else, this is simply a non-redecl case. Checking the 'value' is only
11860 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11861 // handled in the attribute adding step.
11862 if ((NewMVKind == MultiVersionKind::TargetVersion ||
11863 NewMVKind == MultiVersionKind::Target) &&
11864 CheckMultiVersionValue(S, FD: NewFD)) {
11865 NewFD->setInvalidDecl();
11866 return true;
11867 }
11868
11869 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11870 CausesMV: !OldFD->isMultiVersion(), MVKind: NewMVKind)) {
11871 NewFD->setInvalidDecl();
11872 return true;
11873 }
11874
11875 // Permit forward declarations in the case where these two are compatible.
11876 if (!OldFD->isMultiVersion()) {
11877 OldFD->setIsMultiVersion();
11878 NewFD->setIsMultiVersion();
11879 Redeclaration = true;
11880 OldDecl = OldFD;
11881 return false;
11882 }
11883
11884 NewFD->setIsMultiVersion();
11885 Redeclaration = false;
11886 OldDecl = nullptr;
11887 Previous.clear();
11888 return false;
11889}
11890
11891/// Check the validity of a mulitversion function declaration.
11892/// Also sets the multiversion'ness' of the function itself.
11893///
11894/// This sets NewFD->isInvalidDecl() to true if there was an error.
11895///
11896/// Returns true if there was an error, false otherwise.
11897static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11898 bool &Redeclaration, NamedDecl *&OldDecl,
11899 LookupResult &Previous) {
11900 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11901 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11902 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11903 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11904 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11905 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11906
11907 // Main isn't allowed to become a multiversion function, however it IS
11908 // permitted to have 'main' be marked with the 'target' optimization hint,
11909 // for 'target_version' only default is allowed.
11910 if (NewFD->isMain()) {
11911 if (MVKind != MultiVersionKind::None &&
11912 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11913 !(MVKind == MultiVersionKind::TargetVersion &&
11914 NewTVA->isDefaultVersion())) {
11915 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11916 NewFD->setInvalidDecl();
11917 return true;
11918 }
11919 return false;
11920 }
11921
11922 const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
11923
11924 // Target attribute on AArch64 is not used for multiversioning
11925 if (NewTA && T.isAArch64())
11926 return false;
11927
11928 // Target attribute on RISCV is not used for multiversioning
11929 if (NewTA && T.isRISCV())
11930 return false;
11931
11932 if (!OldDecl || !OldDecl->getAsFunction() ||
11933 OldDecl->getDeclContext()->getRedeclContext() !=
11934 NewFD->getDeclContext()->getRedeclContext()) {
11935 // If there's no previous declaration, AND this isn't attempting to cause
11936 // multiversioning, this isn't an error condition.
11937 if (MVKind == MultiVersionKind::None)
11938 return false;
11939 return CheckMultiVersionFirstFunction(S, FD: NewFD);
11940 }
11941
11942 FunctionDecl *OldFD = OldDecl->getAsFunction();
11943
11944 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) {
11945 if (NewTVA || !OldFD->getAttr<TargetVersionAttr>())
11946 return false;
11947 if (!NewFD->getType()->getAs<FunctionProtoType>()) {
11948 // Multiversion declaration doesn't have prototype.
11949 S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
11950 NewFD->setInvalidDecl();
11951 } else {
11952 // No "target_version" attribute is equivalent to "default" attribute.
11953 NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11954 S.Context, "default", NewFD->getSourceRange()));
11955 NewFD->setIsMultiVersion();
11956 OldFD->setIsMultiVersion();
11957 OldDecl = OldFD;
11958 Redeclaration = true;
11959 }
11960 return true;
11961 }
11962
11963 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11964 // for target_clones and target_version.
11965 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11966 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
11967 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
11968 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11969 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11970 NewFD->setInvalidDecl();
11971 return true;
11972 }
11973
11974 if (!OldFD->isMultiVersion()) {
11975 switch (MVKind) {
11976 case MultiVersionKind::Target:
11977 case MultiVersionKind::TargetVersion:
11978 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration,
11979 OldDecl, Previous);
11980 case MultiVersionKind::TargetClones:
11981 if (OldFD->isUsed(false)) {
11982 NewFD->setInvalidDecl();
11983 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11984 }
11985 OldFD->setIsMultiVersion();
11986 break;
11987
11988 case MultiVersionKind::CPUDispatch:
11989 case MultiVersionKind::CPUSpecific:
11990 case MultiVersionKind::None:
11991 break;
11992 }
11993 }
11994
11995 // At this point, we have a multiversion function decl (in OldFD) AND an
11996 // appropriate attribute in the current function decl. Resolve that these are
11997 // still compatible with previous declarations.
11998 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
11999 NewCPUSpec, NewClones, Redeclaration,
12000 OldDecl, Previous);
12001}
12002
12003static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {
12004 bool IsPure = NewFD->hasAttr<PureAttr>();
12005 bool IsConst = NewFD->hasAttr<ConstAttr>();
12006
12007 // If there are no pure or const attributes, there's nothing to check.
12008 if (!IsPure && !IsConst)
12009 return;
12010
12011 // If the function is marked both pure and const, we retain the const
12012 // attribute because it makes stronger guarantees than the pure attribute, and
12013 // we drop the pure attribute explicitly to prevent later confusion about
12014 // semantics.
12015 if (IsPure && IsConst) {
12016 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12017 NewFD->dropAttrs<PureAttr>();
12018 }
12019
12020 // Constructors and destructors are functions which return void, so are
12021 // handled here as well.
12022 if (NewFD->getReturnType()->isVoidType()) {
12023 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12024 << IsConst;
12025 NewFD->dropAttrs<PureAttr, ConstAttr>();
12026 }
12027}
12028
12029/// Perform semantic checking of a new function declaration.
12030///
12031/// Performs semantic analysis of the new function declaration
12032/// NewFD. This routine performs all semantic checking that does not
12033/// require the actual declarator involved in the declaration, and is
12034/// used both for the declaration of functions as they are parsed
12035/// (called via ActOnDeclarator) and for the declaration of functions
12036/// that have been instantiated via C++ template instantiation (called
12037/// via InstantiateDecl).
12038///
12039/// \param IsMemberSpecialization whether this new function declaration is
12040/// a member specialization (that replaces any definition provided by the
12041/// previous declaration).
12042///
12043/// This sets NewFD->isInvalidDecl() to true if there was an error.
12044///
12045/// \returns true if the function declaration is a redeclaration.
12046bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
12047 LookupResult &Previous,
12048 bool IsMemberSpecialization,
12049 bool DeclIsDefn) {
12050 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12051 "Variably modified return types are not handled here");
12052
12053 // Determine whether the type of this function should be merged with
12054 // a previous visible declaration. This never happens for functions in C++,
12055 // and always happens in C if the previous declaration was visible.
12056 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12057 !Previous.isShadowed();
12058
12059 bool Redeclaration = false;
12060 NamedDecl *OldDecl = nullptr;
12061 bool MayNeedOverloadableChecks = false;
12062
12063 // Merge or overload the declaration with an existing declaration of
12064 // the same name, if appropriate.
12065 if (!Previous.empty()) {
12066 // Determine whether NewFD is an overload of PrevDecl or
12067 // a declaration that requires merging. If it's an overload,
12068 // there's no more work to do here; we'll just add the new
12069 // function to the scope.
12070 if (!AllowOverloadingOfFunction(Previous, Context, New: NewFD)) {
12071 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12072 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12073 Redeclaration = true;
12074 OldDecl = Candidate;
12075 }
12076 } else {
12077 MayNeedOverloadableChecks = true;
12078 switch (CheckOverload(S, New: NewFD, OldDecls: Previous, OldDecl,
12079 /*NewIsUsingDecl*/ UseMemberUsingDeclRules: false)) {
12080 case Ovl_Match:
12081 Redeclaration = true;
12082 break;
12083
12084 case Ovl_NonFunction:
12085 Redeclaration = true;
12086 break;
12087
12088 case Ovl_Overload:
12089 Redeclaration = false;
12090 break;
12091 }
12092 }
12093 }
12094
12095 // Check for a previous extern "C" declaration with this name.
12096 if (!Redeclaration &&
12097 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewFD, Previous)) {
12098 if (!Previous.empty()) {
12099 // This is an extern "C" declaration with the same name as a previous
12100 // declaration, and thus redeclares that entity...
12101 Redeclaration = true;
12102 OldDecl = Previous.getFoundDecl();
12103 MergeTypeWithPrevious = false;
12104
12105 // ... except in the presence of __attribute__((overloadable)).
12106 if (OldDecl->hasAttr<OverloadableAttr>() ||
12107 NewFD->hasAttr<OverloadableAttr>()) {
12108 if (IsOverload(New: NewFD, Old: cast<FunctionDecl>(Val: OldDecl), UseMemberUsingDeclRules: false)) {
12109 MayNeedOverloadableChecks = true;
12110 Redeclaration = false;
12111 OldDecl = nullptr;
12112 }
12113 }
12114 }
12115 }
12116
12117 if (CheckMultiVersionFunction(S&: *this, NewFD, Redeclaration, OldDecl, Previous))
12118 return Redeclaration;
12119
12120 // PPC MMA non-pointer types are not allowed as function return types.
12121 if (Context.getTargetInfo().getTriple().isPPC64() &&
12122 CheckPPCMMAType(Type: NewFD->getReturnType(), TypeLoc: NewFD->getLocation())) {
12123 NewFD->setInvalidDecl();
12124 }
12125
12126 CheckConstPureAttributesUsage(S&: *this, NewFD);
12127
12128 // C++ [dcl.spec.auto.general]p12:
12129 // Return type deduction for a templated function with a placeholder in its
12130 // declared type occurs when the definition is instantiated even if the
12131 // function body contains a return statement with a non-type-dependent
12132 // operand.
12133 //
12134 // C++ [temp.dep.expr]p3:
12135 // An id-expression is type-dependent if it is a template-id that is not a
12136 // concept-id and is dependent; or if its terminal name is:
12137 // - [...]
12138 // - associated by name lookup with one or more declarations of member
12139 // functions of a class that is the current instantiation declared with a
12140 // return type that contains a placeholder type,
12141 // - [...]
12142 //
12143 // If this is a templated function with a placeholder in its return type,
12144 // make the placeholder type dependent since it won't be deduced until the
12145 // definition is instantiated. We do this here because it needs to happen
12146 // for implicitly instantiated member functions/member function templates.
12147 if (getLangOpts().CPlusPlus14 &&
12148 (NewFD->isDependentContext() &&
12149 NewFD->getReturnType()->isUndeducedType())) {
12150 const FunctionProtoType *FPT =
12151 NewFD->getType()->castAs<FunctionProtoType>();
12152 QualType NewReturnType = SubstAutoTypeDependent(TypeWithAuto: FPT->getReturnType());
12153 NewFD->setType(Context.getFunctionType(ResultTy: NewReturnType, Args: FPT->getParamTypes(),
12154 EPI: FPT->getExtProtoInfo()));
12155 }
12156
12157 // C++11 [dcl.constexpr]p8:
12158 // A constexpr specifier for a non-static member function that is not
12159 // a constructor declares that member function to be const.
12160 //
12161 // This needs to be delayed until we know whether this is an out-of-line
12162 // definition of a static member function.
12163 //
12164 // This rule is not present in C++1y, so we produce a backwards
12165 // compatibility warning whenever it happens in C++11.
12166 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
12167 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12168 !MD->isStatic() && !isa<CXXConstructorDecl>(Val: MD) &&
12169 !isa<CXXDestructorDecl>(Val: MD) && !MD->getMethodQualifiers().hasConst()) {
12170 CXXMethodDecl *OldMD = nullptr;
12171 if (OldDecl)
12172 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12173 if (!OldMD || !OldMD->isStatic()) {
12174 const FunctionProtoType *FPT =
12175 MD->getType()->castAs<FunctionProtoType>();
12176 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12177 EPI.TypeQuals.addConst();
12178 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
12179 Args: FPT->getParamTypes(), EPI));
12180
12181 // Warn that we did this, if we're not performing template instantiation.
12182 // In that case, we'll have warned already when the template was defined.
12183 if (!inTemplateInstantiation()) {
12184 SourceLocation AddConstLoc;
12185 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
12186 .IgnoreParens().getAs<FunctionTypeLoc>())
12187 AddConstLoc = getLocForEndOfToken(Loc: FTL.getRParenLoc());
12188
12189 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12190 << FixItHint::CreateInsertion(AddConstLoc, " const");
12191 }
12192 }
12193 }
12194
12195 if (Redeclaration) {
12196 // NewFD and OldDecl represent declarations that need to be
12197 // merged.
12198 if (MergeFunctionDecl(New: NewFD, OldD&: OldDecl, S, MergeTypeWithOld: MergeTypeWithPrevious,
12199 NewDeclIsDefn: DeclIsDefn)) {
12200 NewFD->setInvalidDecl();
12201 return Redeclaration;
12202 }
12203
12204 Previous.clear();
12205 Previous.addDecl(D: OldDecl);
12206
12207 if (FunctionTemplateDecl *OldTemplateDecl =
12208 dyn_cast<FunctionTemplateDecl>(Val: OldDecl)) {
12209 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12210 FunctionTemplateDecl *NewTemplateDecl
12211 = NewFD->getDescribedFunctionTemplate();
12212 assert(NewTemplateDecl && "Template/non-template mismatch");
12213
12214 // The call to MergeFunctionDecl above may have created some state in
12215 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12216 // can add it as a redeclaration.
12217 NewTemplateDecl->mergePrevDecl(Prev: OldTemplateDecl);
12218
12219 NewFD->setPreviousDeclaration(OldFD);
12220 if (NewFD->isCXXClassMember()) {
12221 NewFD->setAccess(OldTemplateDecl->getAccess());
12222 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12223 }
12224
12225 // If this is an explicit specialization of a member that is a function
12226 // template, mark it as a member specialization.
12227 if (IsMemberSpecialization &&
12228 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12229 NewTemplateDecl->setMemberSpecialization();
12230 assert(OldTemplateDecl->isMemberSpecialization());
12231 // Explicit specializations of a member template do not inherit deleted
12232 // status from the parent member template that they are specializing.
12233 if (OldFD->isDeleted()) {
12234 // FIXME: This assert will not hold in the presence of modules.
12235 assert(OldFD->getCanonicalDecl() == OldFD);
12236 // FIXME: We need an update record for this AST mutation.
12237 OldFD->setDeletedAsWritten(D: false);
12238 }
12239 }
12240
12241 } else {
12242 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12243 auto *OldFD = cast<FunctionDecl>(Val: OldDecl);
12244 // This needs to happen first so that 'inline' propagates.
12245 NewFD->setPreviousDeclaration(OldFD);
12246 if (NewFD->isCXXClassMember())
12247 NewFD->setAccess(OldFD->getAccess());
12248 }
12249 }
12250 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12251 !NewFD->getAttr<OverloadableAttr>()) {
12252 assert((Previous.empty() ||
12253 llvm::any_of(Previous,
12254 [](const NamedDecl *ND) {
12255 return ND->hasAttr<OverloadableAttr>();
12256 })) &&
12257 "Non-redecls shouldn't happen without overloadable present");
12258
12259 auto OtherUnmarkedIter = llvm::find_if(Range&: Previous, P: [](const NamedDecl *ND) {
12260 const auto *FD = dyn_cast<FunctionDecl>(Val: ND);
12261 return FD && !FD->hasAttr<OverloadableAttr>();
12262 });
12263
12264 if (OtherUnmarkedIter != Previous.end()) {
12265 Diag(NewFD->getLocation(),
12266 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12267 Diag((*OtherUnmarkedIter)->getLocation(),
12268 diag::note_attribute_overloadable_prev_overload)
12269 << false;
12270
12271 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12272 }
12273 }
12274
12275 if (LangOpts.OpenMP)
12276 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
12277
12278 // Semantic checking for this function declaration (in isolation).
12279
12280 if (getLangOpts().CPlusPlus) {
12281 // C++-specific checks.
12282 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: NewFD)) {
12283 CheckConstructor(Constructor);
12284 } else if (CXXDestructorDecl *Destructor =
12285 dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
12286 // We check here for invalid destructor names.
12287 // If we have a friend destructor declaration that is dependent, we can't
12288 // diagnose right away because cases like this are still valid:
12289 // template <class T> struct A { friend T::X::~Y(); };
12290 // struct B { struct Y { ~Y(); }; using X = Y; };
12291 // template struct A<B>;
12292 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12293 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12294 CXXRecordDecl *Record = Destructor->getParent();
12295 QualType ClassType = Context.getTypeDeclType(Record);
12296
12297 DeclarationName Name = Context.DeclarationNames.getCXXDestructorName(
12298 Ty: Context.getCanonicalType(T: ClassType));
12299 if (NewFD->getDeclName() != Name) {
12300 Diag(NewFD->getLocation(), diag::err_destructor_name);
12301 NewFD->setInvalidDecl();
12302 return Redeclaration;
12303 }
12304 }
12305 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: NewFD)) {
12306 if (auto *TD = Guide->getDescribedFunctionTemplate())
12307 CheckDeductionGuideTemplate(TD: TD);
12308
12309 // A deduction guide is not on the list of entities that can be
12310 // explicitly specialized.
12311 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12312 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12313 << /*explicit specialization*/ 1;
12314 }
12315
12316 // Find any virtual functions that this function overrides.
12317 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
12318 if (!Method->isFunctionTemplateSpecialization() &&
12319 !Method->getDescribedFunctionTemplate() &&
12320 Method->isCanonicalDecl()) {
12321 AddOverriddenMethods(DC: Method->getParent(), MD: Method);
12322 }
12323 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12324 // C++2a [class.virtual]p6
12325 // A virtual method shall not have a requires-clause.
12326 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
12327 diag::err_constrained_virtual_method);
12328
12329 if (Method->isStatic())
12330 checkThisInStaticMemberFunctionType(Method);
12331 }
12332
12333 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: NewFD))
12334 ActOnConversionDeclarator(Conversion);
12335
12336 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12337 if (NewFD->isOverloadedOperator() &&
12338 CheckOverloadedOperatorDeclaration(FnDecl: NewFD)) {
12339 NewFD->setInvalidDecl();
12340 return Redeclaration;
12341 }
12342
12343 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12344 if (NewFD->getLiteralIdentifier() &&
12345 CheckLiteralOperatorDeclaration(FnDecl: NewFD)) {
12346 NewFD->setInvalidDecl();
12347 return Redeclaration;
12348 }
12349
12350 // In C++, check default arguments now that we have merged decls. Unless
12351 // the lexical context is the class, because in this case this is done
12352 // during delayed parsing anyway.
12353 if (!CurContext->isRecord())
12354 CheckCXXDefaultArguments(FD: NewFD);
12355
12356 // If this function is declared as being extern "C", then check to see if
12357 // the function returns a UDT (class, struct, or union type) that is not C
12358 // compatible, and if it does, warn the user.
12359 // But, issue any diagnostic on the first declaration only.
12360 if (Previous.empty() && NewFD->isExternC()) {
12361 QualType R = NewFD->getReturnType();
12362 if (R->isIncompleteType() && !R->isVoidType())
12363 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12364 << NewFD << R;
12365 else if (!R.isPODType(Context) && !R->isVoidType() &&
12366 !R->isObjCObjectPointerType())
12367 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12368 }
12369
12370 // C++1z [dcl.fct]p6:
12371 // [...] whether the function has a non-throwing exception-specification
12372 // [is] part of the function type
12373 //
12374 // This results in an ABI break between C++14 and C++17 for functions whose
12375 // declared type includes an exception-specification in a parameter or
12376 // return type. (Exception specifications on the function itself are OK in
12377 // most cases, and exception specifications are not permitted in most other
12378 // contexts where they could make it into a mangling.)
12379 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12380 auto HasNoexcept = [&](QualType T) -> bool {
12381 // Strip off declarator chunks that could be between us and a function
12382 // type. We don't need to look far, exception specifications are very
12383 // restricted prior to C++17.
12384 if (auto *RT = T->getAs<ReferenceType>())
12385 T = RT->getPointeeType();
12386 else if (T->isAnyPointerType())
12387 T = T->getPointeeType();
12388 else if (auto *MPT = T->getAs<MemberPointerType>())
12389 T = MPT->getPointeeType();
12390 if (auto *FPT = T->getAs<FunctionProtoType>())
12391 if (FPT->isNothrow())
12392 return true;
12393 return false;
12394 };
12395
12396 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12397 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12398 for (QualType T : FPT->param_types())
12399 AnyNoexcept |= HasNoexcept(T);
12400 if (AnyNoexcept)
12401 Diag(NewFD->getLocation(),
12402 diag::warn_cxx17_compat_exception_spec_in_signature)
12403 << NewFD;
12404 }
12405
12406 if (!Redeclaration && LangOpts.CUDA)
12407 CUDA().checkTargetOverload(NewFD, Previous);
12408 }
12409
12410 // Check if the function definition uses any AArch64 SME features without
12411 // having the '+sme' feature enabled and warn user if sme locally streaming
12412 // function returns or uses arguments with VL-based types.
12413 if (DeclIsDefn) {
12414 const auto *Attr = NewFD->getAttr<ArmNewAttr>();
12415 bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>();
12416 bool UsesZA = Attr && Attr->isNewZA();
12417 bool UsesZT0 = Attr && Attr->isNewZT0();
12418
12419 if (NewFD->hasAttr<ArmLocallyStreamingAttr>()) {
12420 if (NewFD->getReturnType()->isSizelessVectorType())
12421 Diag(NewFD->getLocation(),
12422 diag::warn_sme_locally_streaming_has_vl_args_returns)
12423 << /*IsArg=*/false;
12424 if (llvm::any_of(NewFD->parameters(), [](ParmVarDecl *P) {
12425 return P->getOriginalType()->isSizelessVectorType();
12426 }))
12427 Diag(NewFD->getLocation(),
12428 diag::warn_sme_locally_streaming_has_vl_args_returns)
12429 << /*IsArg=*/true;
12430 }
12431 if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) {
12432 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12433 UsesSM |=
12434 EPI.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;
12435 UsesZA |= FunctionType::getArmZAState(AttrBits: EPI.AArch64SMEAttributes) !=
12436 FunctionType::ARM_None;
12437 UsesZT0 |= FunctionType::getArmZT0State(AttrBits: EPI.AArch64SMEAttributes) !=
12438 FunctionType::ARM_None;
12439 }
12440
12441 if (UsesSM || UsesZA) {
12442 llvm::StringMap<bool> FeatureMap;
12443 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12444 if (!FeatureMap.contains(Key: "sme")) {
12445 if (UsesSM)
12446 Diag(NewFD->getLocation(),
12447 diag::err_sme_definition_using_sm_in_non_sme_target);
12448 else
12449 Diag(NewFD->getLocation(),
12450 diag::err_sme_definition_using_za_in_non_sme_target);
12451 }
12452 }
12453 if (UsesZT0) {
12454 llvm::StringMap<bool> FeatureMap;
12455 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12456 if (!FeatureMap.contains(Key: "sme2")) {
12457 Diag(NewFD->getLocation(),
12458 diag::err_sme_definition_using_zt0_in_non_sme2_target);
12459 }
12460 }
12461 }
12462
12463 return Redeclaration;
12464}
12465
12466void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
12467 // C++11 [basic.start.main]p3:
12468 // A program that [...] declares main to be inline, static or
12469 // constexpr is ill-formed.
12470 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12471 // appear in a declaration of main.
12472 // static main is not an error under C99, but we should warn about it.
12473 // We accept _Noreturn main as an extension.
12474 if (FD->getStorageClass() == SC_Static)
12475 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
12476 ? diag::err_static_main : diag::warn_static_main)
12477 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12478 if (FD->isInlineSpecified())
12479 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12480 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
12481 if (DS.isNoreturnSpecified()) {
12482 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12483 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(Loc: NoreturnLoc));
12484 Diag(NoreturnLoc, diag::ext_noreturn_main);
12485 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12486 << FixItHint::CreateRemoval(NoreturnRange);
12487 }
12488 if (FD->isConstexpr()) {
12489 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12490 << FD->isConsteval()
12491 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
12492 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12493 }
12494
12495 if (getLangOpts().OpenCL) {
12496 Diag(FD->getLocation(), diag::err_opencl_no_main)
12497 << FD->hasAttr<OpenCLKernelAttr>();
12498 FD->setInvalidDecl();
12499 return;
12500 }
12501
12502 // Functions named main in hlsl are default entries, but don't have specific
12503 // signatures they are required to conform to.
12504 if (getLangOpts().HLSL)
12505 return;
12506
12507 QualType T = FD->getType();
12508 assert(T->isFunctionType() && "function decl is not of function type");
12509 const FunctionType* FT = T->castAs<FunctionType>();
12510
12511 // Set default calling convention for main()
12512 if (FT->getCallConv() != CC_C) {
12513 FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12514 FD->setType(QualType(FT, 0));
12515 T = Context.getCanonicalType(FD->getType());
12516 }
12517
12518 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12519 // In C with GNU extensions we allow main() to have non-integer return
12520 // type, but we should warn about the extension, and we disable the
12521 // implicit-return-zero rule.
12522
12523 // GCC in C mode accepts qualified 'int'.
12524 if (Context.hasSameUnqualifiedType(T1: FT->getReturnType(), T2: Context.IntTy))
12525 FD->setHasImplicitReturnZero(true);
12526 else {
12527 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12528 SourceRange RTRange = FD->getReturnTypeSourceRange();
12529 if (RTRange.isValid())
12530 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12531 << FixItHint::CreateReplacement(RTRange, "int");
12532 }
12533 } else {
12534 // In C and C++, main magically returns 0 if you fall off the end;
12535 // set the flag which tells us that.
12536 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12537
12538 // All the standards say that main() should return 'int'.
12539 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12540 FD->setHasImplicitReturnZero(true);
12541 else {
12542 // Otherwise, this is just a flat-out error.
12543 SourceRange RTRange = FD->getReturnTypeSourceRange();
12544 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12545 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12546 : FixItHint());
12547 FD->setInvalidDecl(true);
12548 }
12549 }
12550
12551 // Treat protoless main() as nullary.
12552 if (isa<FunctionNoProtoType>(Val: FT)) return;
12553
12554 const FunctionProtoType* FTP = cast<const FunctionProtoType>(Val: FT);
12555 unsigned nparams = FTP->getNumParams();
12556 assert(FD->getNumParams() == nparams);
12557
12558 bool HasExtraParameters = (nparams > 3);
12559
12560 if (FTP->isVariadic()) {
12561 Diag(FD->getLocation(), diag::ext_variadic_main);
12562 // FIXME: if we had information about the location of the ellipsis, we
12563 // could add a FixIt hint to remove it as a parameter.
12564 }
12565
12566 // Darwin passes an undocumented fourth argument of type char**. If
12567 // other platforms start sprouting these, the logic below will start
12568 // getting shifty.
12569 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12570 HasExtraParameters = false;
12571
12572 if (HasExtraParameters) {
12573 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12574 FD->setInvalidDecl(true);
12575 nparams = 3;
12576 }
12577
12578 // FIXME: a lot of the following diagnostics would be improved
12579 // if we had some location information about types.
12580
12581 QualType CharPP =
12582 Context.getPointerType(Context.getPointerType(Context.CharTy));
12583 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12584
12585 for (unsigned i = 0; i < nparams; ++i) {
12586 QualType AT = FTP->getParamType(i);
12587
12588 bool mismatch = true;
12589
12590 if (Context.hasSameUnqualifiedType(T1: AT, T2: Expected[i]))
12591 mismatch = false;
12592 else if (Expected[i] == CharPP) {
12593 // As an extension, the following forms are okay:
12594 // char const **
12595 // char const * const *
12596 // char * const *
12597
12598 QualifierCollector qs;
12599 const PointerType* PT;
12600 if ((PT = qs.strip(type: AT)->getAs<PointerType>()) &&
12601 (PT = qs.strip(type: PT->getPointeeType())->getAs<PointerType>()) &&
12602 Context.hasSameType(QualType(qs.strip(type: PT->getPointeeType()), 0),
12603 Context.CharTy)) {
12604 qs.removeConst();
12605 mismatch = !qs.empty();
12606 }
12607 }
12608
12609 if (mismatch) {
12610 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12611 // TODO: suggest replacing given type with expected type
12612 FD->setInvalidDecl(true);
12613 }
12614 }
12615
12616 if (nparams == 1 && !FD->isInvalidDecl()) {
12617 Diag(FD->getLocation(), diag::warn_main_one_arg);
12618 }
12619
12620 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12621 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12622 FD->setInvalidDecl();
12623 }
12624}
12625
12626static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12627
12628 // Default calling convention for main and wmain is __cdecl
12629 if (FD->getName() == "main" || FD->getName() == "wmain")
12630 return false;
12631
12632 // Default calling convention for MinGW is __cdecl
12633 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12634 if (T.isWindowsGNUEnvironment())
12635 return false;
12636
12637 // Default calling convention for WinMain, wWinMain and DllMain
12638 // is __stdcall on 32 bit Windows
12639 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12640 return true;
12641
12642 return false;
12643}
12644
12645void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12646 QualType T = FD->getType();
12647 assert(T->isFunctionType() && "function decl is not of function type");
12648 const FunctionType *FT = T->castAs<FunctionType>();
12649
12650 // Set an implicit return of 'zero' if the function can return some integral,
12651 // enumeration, pointer or nullptr type.
12652 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12653 FT->getReturnType()->isAnyPointerType() ||
12654 FT->getReturnType()->isNullPtrType())
12655 // DllMain is exempt because a return value of zero means it failed.
12656 if (FD->getName() != "DllMain")
12657 FD->setHasImplicitReturnZero(true);
12658
12659 // Explicity specified calling conventions are applied to MSVC entry points
12660 if (!hasExplicitCallingConv(T)) {
12661 if (isDefaultStdCall(FD, S&: *this)) {
12662 if (FT->getCallConv() != CC_X86StdCall) {
12663 FT = Context.adjustFunctionType(
12664 Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_X86StdCall));
12665 FD->setType(QualType(FT, 0));
12666 }
12667 } else if (FT->getCallConv() != CC_C) {
12668 FT = Context.adjustFunctionType(Fn: FT,
12669 EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12670 FD->setType(QualType(FT, 0));
12671 }
12672 }
12673
12674 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12675 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12676 FD->setInvalidDecl();
12677 }
12678}
12679
12680bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {
12681 // FIXME: Need strict checking. In C89, we need to check for
12682 // any assignment, increment, decrement, function-calls, or
12683 // commas outside of a sizeof. In C99, it's the same list,
12684 // except that the aforementioned are allowed in unevaluated
12685 // expressions. Everything else falls under the
12686 // "may accept other forms of constant expressions" exception.
12687 //
12688 // Regular C++ code will not end up here (exceptions: language extensions,
12689 // OpenCL C++ etc), so the constant expression rules there don't matter.
12690 if (Init->isValueDependent()) {
12691 assert(Init->containsErrors() &&
12692 "Dependent code should only occur in error-recovery path.");
12693 return true;
12694 }
12695 const Expr *Culprit;
12696 if (Init->isConstantInitializer(Ctx&: Context, ForRef: false, Culprit: &Culprit))
12697 return false;
12698 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12699 return true;
12700}
12701
12702namespace {
12703 // Visits an initialization expression to see if OrigDecl is evaluated in
12704 // its own initialization and throws a warning if it does.
12705 class SelfReferenceChecker
12706 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12707 Sema &S;
12708 Decl *OrigDecl;
12709 bool isRecordType;
12710 bool isPODType;
12711 bool isReferenceType;
12712
12713 bool isInitList;
12714 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12715
12716 public:
12717 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12718
12719 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12720 S(S), OrigDecl(OrigDecl) {
12721 isPODType = false;
12722 isRecordType = false;
12723 isReferenceType = false;
12724 isInitList = false;
12725 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: OrigDecl)) {
12726 isPODType = VD->getType().isPODType(Context: S.Context);
12727 isRecordType = VD->getType()->isRecordType();
12728 isReferenceType = VD->getType()->isReferenceType();
12729 }
12730 }
12731
12732 // For most expressions, just call the visitor. For initializer lists,
12733 // track the index of the field being initialized since fields are
12734 // initialized in order allowing use of previously initialized fields.
12735 void CheckExpr(Expr *E) {
12736 InitListExpr *InitList = dyn_cast<InitListExpr>(Val: E);
12737 if (!InitList) {
12738 Visit(E);
12739 return;
12740 }
12741
12742 // Track and increment the index here.
12743 isInitList = true;
12744 InitFieldIndex.push_back(Elt: 0);
12745 for (auto *Child : InitList->children()) {
12746 CheckExpr(E: cast<Expr>(Val: Child));
12747 ++InitFieldIndex.back();
12748 }
12749 InitFieldIndex.pop_back();
12750 }
12751
12752 // Returns true if MemberExpr is checked and no further checking is needed.
12753 // Returns false if additional checking is required.
12754 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12755 llvm::SmallVector<FieldDecl*, 4> Fields;
12756 Expr *Base = E;
12757 bool ReferenceField = false;
12758
12759 // Get the field members used.
12760 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
12761 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
12762 if (!FD)
12763 return false;
12764 Fields.push_back(Elt: FD);
12765 if (FD->getType()->isReferenceType())
12766 ReferenceField = true;
12767 Base = ME->getBase()->IgnoreParenImpCasts();
12768 }
12769
12770 // Keep checking only if the base Decl is the same.
12771 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base);
12772 if (!DRE || DRE->getDecl() != OrigDecl)
12773 return false;
12774
12775 // A reference field can be bound to an unininitialized field.
12776 if (CheckReference && !ReferenceField)
12777 return true;
12778
12779 // Convert FieldDecls to their index number.
12780 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12781 for (const FieldDecl *I : llvm::reverse(C&: Fields))
12782 UsedFieldIndex.push_back(Elt: I->getFieldIndex());
12783
12784 // See if a warning is needed by checking the first difference in index
12785 // numbers. If field being used has index less than the field being
12786 // initialized, then the use is safe.
12787 for (auto UsedIter = UsedFieldIndex.begin(),
12788 UsedEnd = UsedFieldIndex.end(),
12789 OrigIter = InitFieldIndex.begin(),
12790 OrigEnd = InitFieldIndex.end();
12791 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12792 if (*UsedIter < *OrigIter)
12793 return true;
12794 if (*UsedIter > *OrigIter)
12795 break;
12796 }
12797
12798 // TODO: Add a different warning which will print the field names.
12799 HandleDeclRefExpr(DRE);
12800 return true;
12801 }
12802
12803 // For most expressions, the cast is directly above the DeclRefExpr.
12804 // For conditional operators, the cast can be outside the conditional
12805 // operator if both expressions are DeclRefExpr's.
12806 void HandleValue(Expr *E) {
12807 E = E->IgnoreParens();
12808 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Val: E)) {
12809 HandleDeclRefExpr(DRE);
12810 return;
12811 }
12812
12813 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
12814 Visit(CO->getCond());
12815 HandleValue(E: CO->getTrueExpr());
12816 HandleValue(E: CO->getFalseExpr());
12817 return;
12818 }
12819
12820 if (BinaryConditionalOperator *BCO =
12821 dyn_cast<BinaryConditionalOperator>(Val: E)) {
12822 Visit(BCO->getCond());
12823 HandleValue(E: BCO->getFalseExpr());
12824 return;
12825 }
12826
12827 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
12828 if (Expr *SE = OVE->getSourceExpr())
12829 HandleValue(E: SE);
12830 return;
12831 }
12832
12833 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
12834 if (BO->getOpcode() == BO_Comma) {
12835 Visit(BO->getLHS());
12836 HandleValue(E: BO->getRHS());
12837 return;
12838 }
12839 }
12840
12841 if (isa<MemberExpr>(Val: E)) {
12842 if (isInitList) {
12843 if (CheckInitListMemberExpr(E: cast<MemberExpr>(Val: E),
12844 CheckReference: false /*CheckReference*/))
12845 return;
12846 }
12847
12848 Expr *Base = E->IgnoreParenImpCasts();
12849 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
12850 // Check for static member variables and don't warn on them.
12851 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
12852 return;
12853 Base = ME->getBase()->IgnoreParenImpCasts();
12854 }
12855 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base))
12856 HandleDeclRefExpr(DRE);
12857 return;
12858 }
12859
12860 Visit(E);
12861 }
12862
12863 // Reference types not handled in HandleValue are handled here since all
12864 // uses of references are bad, not just r-value uses.
12865 void VisitDeclRefExpr(DeclRefExpr *E) {
12866 if (isReferenceType)
12867 HandleDeclRefExpr(DRE: E);
12868 }
12869
12870 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12871 if (E->getCastKind() == CK_LValueToRValue) {
12872 HandleValue(E: E->getSubExpr());
12873 return;
12874 }
12875
12876 Inherited::VisitImplicitCastExpr(E);
12877 }
12878
12879 void VisitMemberExpr(MemberExpr *E) {
12880 if (isInitList) {
12881 if (CheckInitListMemberExpr(E, CheckReference: true /*CheckReference*/))
12882 return;
12883 }
12884
12885 // Don't warn on arrays since they can be treated as pointers.
12886 if (E->getType()->canDecayToPointerType()) return;
12887
12888 // Warn when a non-static method call is followed by non-static member
12889 // field accesses, which is followed by a DeclRefExpr.
12890 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl());
12891 bool Warn = (MD && !MD->isStatic());
12892 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12893 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
12894 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
12895 Warn = false;
12896 Base = ME->getBase()->IgnoreParenImpCasts();
12897 }
12898
12899 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base)) {
12900 if (Warn)
12901 HandleDeclRefExpr(DRE);
12902 return;
12903 }
12904
12905 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12906 // Visit that expression.
12907 Visit(Base);
12908 }
12909
12910 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12911 Expr *Callee = E->getCallee();
12912
12913 if (isa<UnresolvedLookupExpr>(Callee))
12914 return Inherited::VisitCXXOperatorCallExpr(E);
12915
12916 Visit(Callee);
12917 for (auto Arg: E->arguments())
12918 HandleValue(Arg->IgnoreParenImpCasts());
12919 }
12920
12921 void VisitUnaryOperator(UnaryOperator *E) {
12922 // For POD record types, addresses of its own members are well-defined.
12923 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12924 isa<MemberExpr>(Val: E->getSubExpr()->IgnoreParens())) {
12925 if (!isPODType)
12926 HandleValue(E: E->getSubExpr());
12927 return;
12928 }
12929
12930 if (E->isIncrementDecrementOp()) {
12931 HandleValue(E: E->getSubExpr());
12932 return;
12933 }
12934
12935 Inherited::VisitUnaryOperator(E);
12936 }
12937
12938 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12939
12940 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12941 if (E->getConstructor()->isCopyConstructor()) {
12942 Expr *ArgExpr = E->getArg(Arg: 0);
12943 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
12944 if (ILE->getNumInits() == 1)
12945 ArgExpr = ILE->getInit(Init: 0);
12946 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
12947 if (ICE->getCastKind() == CK_NoOp)
12948 ArgExpr = ICE->getSubExpr();
12949 HandleValue(E: ArgExpr);
12950 return;
12951 }
12952 Inherited::VisitCXXConstructExpr(E);
12953 }
12954
12955 void VisitCallExpr(CallExpr *E) {
12956 // Treat std::move as a use.
12957 if (E->isCallToStdMove()) {
12958 HandleValue(E: E->getArg(Arg: 0));
12959 return;
12960 }
12961
12962 Inherited::VisitCallExpr(CE: E);
12963 }
12964
12965 void VisitBinaryOperator(BinaryOperator *E) {
12966 if (E->isCompoundAssignmentOp()) {
12967 HandleValue(E: E->getLHS());
12968 Visit(E->getRHS());
12969 return;
12970 }
12971
12972 Inherited::VisitBinaryOperator(E);
12973 }
12974
12975 // A custom visitor for BinaryConditionalOperator is needed because the
12976 // regular visitor would check the condition and true expression separately
12977 // but both point to the same place giving duplicate diagnostics.
12978 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12979 Visit(E->getCond());
12980 Visit(E->getFalseExpr());
12981 }
12982
12983 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12984 Decl* ReferenceDecl = DRE->getDecl();
12985 if (OrigDecl != ReferenceDecl) return;
12986 unsigned diag;
12987 if (isReferenceType) {
12988 diag = diag::warn_uninit_self_reference_in_reference_init;
12989 } else if (cast<VarDecl>(Val: OrigDecl)->isStaticLocal()) {
12990 diag = diag::warn_static_self_reference_in_init;
12991 } else if (isa<TranslationUnitDecl>(Val: OrigDecl->getDeclContext()) ||
12992 isa<NamespaceDecl>(Val: OrigDecl->getDeclContext()) ||
12993 DRE->getDecl()->getType()->isRecordType()) {
12994 diag = diag::warn_uninit_self_reference_in_init;
12995 } else {
12996 // Local variables will be handled by the CFG analysis.
12997 return;
12998 }
12999
13000 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13001 S.PDiag(DiagID: diag)
13002 << DRE->getDecl() << OrigDecl->getLocation()
13003 << DRE->getSourceRange());
13004 }
13005 };
13006
13007 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13008 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13009 bool DirectInit) {
13010 // Parameters arguments are occassionially constructed with itself,
13011 // for instance, in recursive functions. Skip them.
13012 if (isa<ParmVarDecl>(Val: OrigDecl))
13013 return;
13014
13015 E = E->IgnoreParens();
13016
13017 // Skip checking T a = a where T is not a record or reference type.
13018 // Doing so is a way to silence uninitialized warnings.
13019 if (!DirectInit && !cast<VarDecl>(Val: OrigDecl)->getType()->isRecordType())
13020 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
13021 if (ICE->getCastKind() == CK_LValueToRValue)
13022 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13023 if (DRE->getDecl() == OrigDecl)
13024 return;
13025
13026 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13027 }
13028} // end anonymous namespace
13029
13030namespace {
13031 // Simple wrapper to add the name of a variable or (if no variable is
13032 // available) a DeclarationName into a diagnostic.
13033 struct VarDeclOrName {
13034 VarDecl *VDecl;
13035 DeclarationName Name;
13036
13037 friend const Sema::SemaDiagnosticBuilder &
13038 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13039 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13040 }
13041 };
13042} // end anonymous namespace
13043
13044QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
13045 DeclarationName Name, QualType Type,
13046 TypeSourceInfo *TSI,
13047 SourceRange Range, bool DirectInit,
13048 Expr *Init) {
13049 bool IsInitCapture = !VDecl;
13050 assert((!VDecl || !VDecl->isInitCapture()) &&
13051 "init captures are expected to be deduced prior to initialization");
13052
13053 VarDeclOrName VN{.VDecl: VDecl, .Name: Name};
13054
13055 DeducedType *Deduced = Type->getContainedDeducedType();
13056 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13057
13058 // Diagnose auto array declarations in C23, unless it's a supported extension.
13059 if (getLangOpts().C23 && Type->isArrayType() &&
13060 !isa_and_present<StringLiteral, InitListExpr>(Val: Init)) {
13061 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13062 << (int)Deduced->getContainedAutoType()->getKeyword()
13063 << /*in array decl*/ 23 << Range;
13064 return QualType();
13065 }
13066
13067 // C++11 [dcl.spec.auto]p3
13068 if (!Init) {
13069 assert(VDecl && "no init for init capture deduction?");
13070
13071 // Except for class argument deduction, and then for an initializing
13072 // declaration only, i.e. no static at class scope or extern.
13073 if (!isa<DeducedTemplateSpecializationType>(Val: Deduced) ||
13074 VDecl->hasExternalStorage() ||
13075 VDecl->isStaticDataMember()) {
13076 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13077 << VDecl->getDeclName() << Type;
13078 return QualType();
13079 }
13080 }
13081
13082 ArrayRef<Expr*> DeduceInits;
13083 if (Init)
13084 DeduceInits = Init;
13085
13086 auto *PL = dyn_cast_if_present<ParenListExpr>(Val: Init);
13087 if (DirectInit && PL)
13088 DeduceInits = PL->exprs();
13089
13090 if (isa<DeducedTemplateSpecializationType>(Val: Deduced)) {
13091 assert(VDecl && "non-auto type for init capture deduction?");
13092 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13093 InitializationKind Kind = InitializationKind::CreateForInit(
13094 Loc: VDecl->getLocation(), DirectInit, Init);
13095 // FIXME: Initialization should not be taking a mutable list of inits.
13096 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
13097 return DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind,
13098 Init: InitsCopy);
13099 }
13100
13101 if (DirectInit) {
13102 if (auto *IL = dyn_cast<InitListExpr>(Val: Init))
13103 DeduceInits = IL->inits();
13104 }
13105
13106 // Deduction only works if we have exactly one source expression.
13107 if (DeduceInits.empty()) {
13108 // It isn't possible to write this directly, but it is possible to
13109 // end up in this situation with "auto x(some_pack...);"
13110 Diag(Init->getBeginLoc(), IsInitCapture
13111 ? diag::err_init_capture_no_expression
13112 : diag::err_auto_var_init_no_expression)
13113 << VN << Type << Range;
13114 return QualType();
13115 }
13116
13117 if (DeduceInits.size() > 1) {
13118 Diag(DeduceInits[1]->getBeginLoc(),
13119 IsInitCapture ? diag::err_init_capture_multiple_expressions
13120 : diag::err_auto_var_init_multiple_expressions)
13121 << VN << Type << Range;
13122 return QualType();
13123 }
13124
13125 Expr *DeduceInit = DeduceInits[0];
13126 if (DirectInit && isa<InitListExpr>(Val: DeduceInit)) {
13127 Diag(Init->getBeginLoc(), IsInitCapture
13128 ? diag::err_init_capture_paren_braces
13129 : diag::err_auto_var_init_paren_braces)
13130 << isa<InitListExpr>(Init) << VN << Type << Range;
13131 return QualType();
13132 }
13133
13134 // Expressions default to 'id' when we're in a debugger.
13135 bool DefaultedAnyToId = false;
13136 if (getLangOpts().DebuggerCastResultToId &&
13137 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13138 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13139 if (Result.isInvalid()) {
13140 return QualType();
13141 }
13142 Init = Result.get();
13143 DefaultedAnyToId = true;
13144 }
13145
13146 // C++ [dcl.decomp]p1:
13147 // If the assignment-expression [...] has array type A and no ref-qualifier
13148 // is present, e has type cv A
13149 if (VDecl && isa<DecompositionDecl>(Val: VDecl) &&
13150 Context.hasSameUnqualifiedType(T1: Type, T2: Context.getAutoDeductType()) &&
13151 DeduceInit->getType()->isConstantArrayType())
13152 return Context.getQualifiedType(T: DeduceInit->getType(),
13153 Qs: Type.getQualifiers());
13154
13155 QualType DeducedType;
13156 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13157 TemplateDeductionResult Result =
13158 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeduceInit, Result&: DeducedType, Info);
13159 if (Result != TemplateDeductionResult::Success &&
13160 Result != TemplateDeductionResult::AlreadyDiagnosed) {
13161 if (!IsInitCapture)
13162 DiagnoseAutoDeductionFailure(VDecl, Init: DeduceInit);
13163 else if (isa<InitListExpr>(Init))
13164 Diag(Range.getBegin(),
13165 diag::err_init_capture_deduction_failure_from_init_list)
13166 << VN
13167 << (DeduceInit->getType().isNull() ? TSI->getType()
13168 : DeduceInit->getType())
13169 << DeduceInit->getSourceRange();
13170 else
13171 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13172 << VN << TSI->getType()
13173 << (DeduceInit->getType().isNull() ? TSI->getType()
13174 : DeduceInit->getType())
13175 << DeduceInit->getSourceRange();
13176 }
13177
13178 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13179 // 'id' instead of a specific object type prevents most of our usual
13180 // checks.
13181 // We only want to warn outside of template instantiations, though:
13182 // inside a template, the 'id' could have come from a parameter.
13183 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13184 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13185 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13186 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13187 }
13188
13189 return DeducedType;
13190}
13191
13192bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13193 Expr *Init) {
13194 assert(!Init || !Init->containsErrors());
13195 QualType DeducedType = deduceVarTypeFromInitializer(
13196 VDecl, Name: VDecl->getDeclName(), Type: VDecl->getType(), TSI: VDecl->getTypeSourceInfo(),
13197 Range: VDecl->getSourceRange(), DirectInit, Init);
13198 if (DeducedType.isNull()) {
13199 VDecl->setInvalidDecl();
13200 return true;
13201 }
13202
13203 VDecl->setType(DeducedType);
13204 assert(VDecl->isLinkageValid());
13205
13206 // In ARC, infer lifetime.
13207 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
13208 VDecl->setInvalidDecl();
13209
13210 if (getLangOpts().OpenCL)
13211 deduceOpenCLAddressSpace(VDecl);
13212
13213 // If this is a redeclaration, check that the type we just deduced matches
13214 // the previously declared type.
13215 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13216 // We never need to merge the type, because we cannot form an incomplete
13217 // array of auto, nor deduce such a type.
13218 MergeVarDeclTypes(New: VDecl, Old, /*MergeTypeWithPrevious*/ MergeTypeWithOld: false);
13219 }
13220
13221 // Check the deduced type is valid for a variable declaration.
13222 CheckVariableDeclarationType(NewVD: VDecl);
13223 return VDecl->isInvalidDecl();
13224}
13225
13226void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13227 SourceLocation Loc) {
13228 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Init))
13229 Init = EWC->getSubExpr();
13230
13231 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init))
13232 Init = CE->getSubExpr();
13233
13234 QualType InitType = Init->getType();
13235 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13236 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13237 "shouldn't be called if type doesn't have a non-trivial C struct");
13238 if (auto *ILE = dyn_cast<InitListExpr>(Val: Init)) {
13239 for (auto *I : ILE->inits()) {
13240 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13241 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13242 continue;
13243 SourceLocation SL = I->getExprLoc();
13244 checkNonTrivialCUnionInInitializer(Init: I, Loc: SL.isValid() ? SL : Loc);
13245 }
13246 return;
13247 }
13248
13249 if (isa<ImplicitValueInitExpr>(Val: Init)) {
13250 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13251 checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NTCUC_DefaultInitializedObject,
13252 NonTrivialKind: NTCUK_Init);
13253 } else {
13254 // Assume all other explicit initializers involving copying some existing
13255 // object.
13256 // TODO: ignore any explicit initializers where we can guarantee
13257 // copy-elision.
13258 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13259 checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NTCUC_CopyInit, NonTrivialKind: NTCUK_Copy);
13260 }
13261}
13262
13263namespace {
13264
13265bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13266 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13267 // in the source code or implicitly by the compiler if it is in a union
13268 // defined in a system header and has non-trivial ObjC ownership
13269 // qualifications. We don't want those fields to participate in determining
13270 // whether the containing union is non-trivial.
13271 return FD->hasAttr<UnavailableAttr>();
13272}
13273
13274struct DiagNonTrivalCUnionDefaultInitializeVisitor
13275 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13276 void> {
13277 using Super =
13278 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13279 void>;
13280
13281 DiagNonTrivalCUnionDefaultInitializeVisitor(
13282 QualType OrigTy, SourceLocation OrigLoc,
13283 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13284 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13285
13286 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13287 const FieldDecl *FD, bool InNonTrivialUnion) {
13288 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13289 return this->asDerived().visit(S.Context.getBaseElementType(VAT: AT), FD,
13290 InNonTrivialUnion);
13291 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13292 }
13293
13294 void visitARCStrong(QualType QT, const FieldDecl *FD,
13295 bool InNonTrivialUnion) {
13296 if (InNonTrivialUnion)
13297 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13298 << 1 << 0 << QT << FD->getName();
13299 }
13300
13301 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13302 if (InNonTrivialUnion)
13303 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13304 << 1 << 0 << QT << FD->getName();
13305 }
13306
13307 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13308 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13309 if (RD->isUnion()) {
13310 if (OrigLoc.isValid()) {
13311 bool IsUnion = false;
13312 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13313 IsUnion = OrigRD->isUnion();
13314 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13315 << 0 << OrigTy << IsUnion << UseContext;
13316 // Reset OrigLoc so that this diagnostic is emitted only once.
13317 OrigLoc = SourceLocation();
13318 }
13319 InNonTrivialUnion = true;
13320 }
13321
13322 if (InNonTrivialUnion)
13323 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13324 << 0 << 0 << QT.getUnqualifiedType() << "";
13325
13326 for (const FieldDecl *FD : RD->fields())
13327 if (!shouldIgnoreForRecordTriviality(FD))
13328 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13329 }
13330
13331 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13332
13333 // The non-trivial C union type or the struct/union type that contains a
13334 // non-trivial C union.
13335 QualType OrigTy;
13336 SourceLocation OrigLoc;
13337 Sema::NonTrivialCUnionContext UseContext;
13338 Sema &S;
13339};
13340
13341struct DiagNonTrivalCUnionDestructedTypeVisitor
13342 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13343 using Super =
13344 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13345
13346 DiagNonTrivalCUnionDestructedTypeVisitor(
13347 QualType OrigTy, SourceLocation OrigLoc,
13348 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13349 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13350
13351 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13352 const FieldDecl *FD, bool InNonTrivialUnion) {
13353 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13354 return this->asDerived().visit(S.Context.getBaseElementType(VAT: AT), FD,
13355 InNonTrivialUnion);
13356 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13357 }
13358
13359 void visitARCStrong(QualType QT, const FieldDecl *FD,
13360 bool InNonTrivialUnion) {
13361 if (InNonTrivialUnion)
13362 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13363 << 1 << 1 << QT << FD->getName();
13364 }
13365
13366 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13367 if (InNonTrivialUnion)
13368 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13369 << 1 << 1 << QT << FD->getName();
13370 }
13371
13372 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13373 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13374 if (RD->isUnion()) {
13375 if (OrigLoc.isValid()) {
13376 bool IsUnion = false;
13377 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13378 IsUnion = OrigRD->isUnion();
13379 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13380 << 1 << OrigTy << IsUnion << UseContext;
13381 // Reset OrigLoc so that this diagnostic is emitted only once.
13382 OrigLoc = SourceLocation();
13383 }
13384 InNonTrivialUnion = true;
13385 }
13386
13387 if (InNonTrivialUnion)
13388 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13389 << 0 << 1 << QT.getUnqualifiedType() << "";
13390
13391 for (const FieldDecl *FD : RD->fields())
13392 if (!shouldIgnoreForRecordTriviality(FD))
13393 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13394 }
13395
13396 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13397 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13398 bool InNonTrivialUnion) {}
13399
13400 // The non-trivial C union type or the struct/union type that contains a
13401 // non-trivial C union.
13402 QualType OrigTy;
13403 SourceLocation OrigLoc;
13404 Sema::NonTrivialCUnionContext UseContext;
13405 Sema &S;
13406};
13407
13408struct DiagNonTrivalCUnionCopyVisitor
13409 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13410 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13411
13412 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13413 Sema::NonTrivialCUnionContext UseContext,
13414 Sema &S)
13415 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13416
13417 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13418 const FieldDecl *FD, bool InNonTrivialUnion) {
13419 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13420 return this->asDerived().visit(S.Context.getBaseElementType(VAT: AT), FD,
13421 InNonTrivialUnion);
13422 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13423 }
13424
13425 void visitARCStrong(QualType QT, const FieldDecl *FD,
13426 bool InNonTrivialUnion) {
13427 if (InNonTrivialUnion)
13428 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13429 << 1 << 2 << QT << FD->getName();
13430 }
13431
13432 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13433 if (InNonTrivialUnion)
13434 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13435 << 1 << 2 << QT << FD->getName();
13436 }
13437
13438 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13439 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13440 if (RD->isUnion()) {
13441 if (OrigLoc.isValid()) {
13442 bool IsUnion = false;
13443 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13444 IsUnion = OrigRD->isUnion();
13445 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13446 << 2 << OrigTy << IsUnion << UseContext;
13447 // Reset OrigLoc so that this diagnostic is emitted only once.
13448 OrigLoc = SourceLocation();
13449 }
13450 InNonTrivialUnion = true;
13451 }
13452
13453 if (InNonTrivialUnion)
13454 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13455 << 0 << 2 << QT.getUnqualifiedType() << "";
13456
13457 for (const FieldDecl *FD : RD->fields())
13458 if (!shouldIgnoreForRecordTriviality(FD))
13459 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13460 }
13461
13462 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13463 const FieldDecl *FD, bool InNonTrivialUnion) {}
13464 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13465 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13466 bool InNonTrivialUnion) {}
13467
13468 // The non-trivial C union type or the struct/union type that contains a
13469 // non-trivial C union.
13470 QualType OrigTy;
13471 SourceLocation OrigLoc;
13472 Sema::NonTrivialCUnionContext UseContext;
13473 Sema &S;
13474};
13475
13476} // namespace
13477
13478void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13479 NonTrivialCUnionContext UseContext,
13480 unsigned NonTrivialKind) {
13481 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13482 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13483 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13484 "shouldn't be called if type doesn't have a non-trivial C union");
13485
13486 if ((NonTrivialKind & NTCUK_Init) &&
13487 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13488 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13489 .visit(QT, nullptr, false);
13490 if ((NonTrivialKind & NTCUK_Destruct) &&
13491 QT.hasNonTrivialToPrimitiveDestructCUnion())
13492 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13493 .visit(QT, nullptr, false);
13494 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13495 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13496 .visit(QT, nullptr, false);
13497}
13498
13499/// AddInitializerToDecl - Adds the initializer Init to the
13500/// declaration dcl. If DirectInit is true, this is C++ direct
13501/// initialization rather than copy initialization.
13502void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13503 // If there is no declaration, there was an error parsing it. Just ignore
13504 // the initializer.
13505 if (!RealDecl || RealDecl->isInvalidDecl()) {
13506 CorrectDelayedTyposInExpr(E: Init, InitDecl: dyn_cast_or_null<VarDecl>(Val: RealDecl));
13507 return;
13508 }
13509
13510 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: RealDecl)) {
13511 // Pure-specifiers are handled in ActOnPureSpecifier.
13512 Diag(Method->getLocation(), diag::err_member_function_initialization)
13513 << Method->getDeclName() << Init->getSourceRange();
13514 Method->setInvalidDecl();
13515 return;
13516 }
13517
13518 VarDecl *VDecl = dyn_cast<VarDecl>(Val: RealDecl);
13519 if (!VDecl) {
13520 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13521 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13522 RealDecl->setInvalidDecl();
13523 return;
13524 }
13525
13526 // WebAssembly tables can't be used to initialise a variable.
13527 if (Init && !Init->getType().isNull() &&
13528 Init->getType()->isWebAssemblyTableType()) {
13529 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13530 VDecl->setInvalidDecl();
13531 return;
13532 }
13533
13534 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13535 if (VDecl->getType()->isUndeducedType()) {
13536 // Attempt typo correction early so that the type of the init expression can
13537 // be deduced based on the chosen correction if the original init contains a
13538 // TypoExpr.
13539 ExprResult Res = CorrectDelayedTyposInExpr(E: Init, InitDecl: VDecl);
13540 if (!Res.isUsable()) {
13541 // There are unresolved typos in Init, just drop them.
13542 // FIXME: improve the recovery strategy to preserve the Init.
13543 RealDecl->setInvalidDecl();
13544 return;
13545 }
13546 if (Res.get()->containsErrors()) {
13547 // Invalidate the decl as we don't know the type for recovery-expr yet.
13548 RealDecl->setInvalidDecl();
13549 VDecl->setInit(Res.get());
13550 return;
13551 }
13552 Init = Res.get();
13553
13554 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
13555 return;
13556 }
13557
13558 // dllimport cannot be used on variable definitions.
13559 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13560 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13561 VDecl->setInvalidDecl();
13562 return;
13563 }
13564
13565 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13566 // the identifier has external or internal linkage, the declaration shall
13567 // have no initializer for the identifier.
13568 // C++14 [dcl.init]p5 is the same restriction for C++.
13569 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13570 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13571 VDecl->setInvalidDecl();
13572 return;
13573 }
13574
13575 if (!VDecl->getType()->isDependentType()) {
13576 // A definition must end up with a complete type, which means it must be
13577 // complete with the restriction that an array type might be completed by
13578 // the initializer; note that later code assumes this restriction.
13579 QualType BaseDeclType = VDecl->getType();
13580 if (const ArrayType *Array = Context.getAsIncompleteArrayType(T: BaseDeclType))
13581 BaseDeclType = Array->getElementType();
13582 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13583 diag::err_typecheck_decl_incomplete_type)) {
13584 RealDecl->setInvalidDecl();
13585 return;
13586 }
13587
13588 // The variable can not have an abstract class type.
13589 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13590 diag::err_abstract_type_in_decl,
13591 AbstractVariableType))
13592 VDecl->setInvalidDecl();
13593 }
13594
13595 // C++ [module.import/6] external definitions are not permitted in header
13596 // units.
13597 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13598 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13599 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13600 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(Val: VDecl)) {
13601 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13602 VDecl->setInvalidDecl();
13603 }
13604
13605 // If adding the initializer will turn this declaration into a definition,
13606 // and we already have a definition for this variable, diagnose or otherwise
13607 // handle the situation.
13608 if (VarDecl *Def = VDecl->getDefinition())
13609 if (Def != VDecl &&
13610 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13611 !VDecl->isThisDeclarationADemotedDefinition() &&
13612 checkVarDeclRedefinition(Old: Def, New: VDecl))
13613 return;
13614
13615 if (getLangOpts().CPlusPlus) {
13616 // C++ [class.static.data]p4
13617 // If a static data member is of const integral or const
13618 // enumeration type, its declaration in the class definition can
13619 // specify a constant-initializer which shall be an integral
13620 // constant expression (5.19). In that case, the member can appear
13621 // in integral constant expressions. The member shall still be
13622 // defined in a namespace scope if it is used in the program and the
13623 // namespace scope definition shall not contain an initializer.
13624 //
13625 // We already performed a redefinition check above, but for static
13626 // data members we also need to check whether there was an in-class
13627 // declaration with an initializer.
13628 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13629 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13630 << VDecl->getDeclName();
13631 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13632 diag::note_previous_initializer)
13633 << 0;
13634 return;
13635 }
13636
13637 if (VDecl->hasLocalStorage())
13638 setFunctionHasBranchProtectedScope();
13639
13640 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer)) {
13641 VDecl->setInvalidDecl();
13642 return;
13643 }
13644 }
13645
13646 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13647 // a kernel function cannot be initialized."
13648 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13649 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13650 VDecl->setInvalidDecl();
13651 return;
13652 }
13653
13654 // The LoaderUninitialized attribute acts as a definition (of undef).
13655 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13656 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13657 VDecl->setInvalidDecl();
13658 return;
13659 }
13660
13661 // Get the decls type and save a reference for later, since
13662 // CheckInitializerTypes may change it.
13663 QualType DclT = VDecl->getType(), SavT = DclT;
13664
13665 // Expressions default to 'id' when we're in a debugger
13666 // and we are assigning it to a variable of Objective-C pointer type.
13667 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13668 Init->getType() == Context.UnknownAnyTy) {
13669 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13670 if (Result.isInvalid()) {
13671 VDecl->setInvalidDecl();
13672 return;
13673 }
13674 Init = Result.get();
13675 }
13676
13677 // Perform the initialization.
13678 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Val: Init);
13679 bool IsParenListInit = false;
13680 if (!VDecl->isInvalidDecl()) {
13681 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13682 InitializationKind Kind = InitializationKind::CreateForInit(
13683 Loc: VDecl->getLocation(), DirectInit, Init);
13684
13685 MultiExprArg Args = Init;
13686 if (CXXDirectInit)
13687 Args = MultiExprArg(CXXDirectInit->getExprs(),
13688 CXXDirectInit->getNumExprs());
13689
13690 // Try to correct any TypoExprs in the initialization arguments.
13691 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13692 ExprResult Res = CorrectDelayedTyposInExpr(
13693 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13694 [this, Entity, Kind](Expr *E) {
13695 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13696 return Init.Failed() ? ExprError() : E;
13697 });
13698 if (Res.isInvalid()) {
13699 VDecl->setInvalidDecl();
13700 } else if (Res.get() != Args[Idx]) {
13701 Args[Idx] = Res.get();
13702 }
13703 }
13704 if (VDecl->isInvalidDecl())
13705 return;
13706
13707 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13708 /*TopLevelOfInitList=*/false,
13709 /*TreatUnavailableAsInvalid=*/false);
13710 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args, ResultType: &DclT);
13711 if (Result.isInvalid()) {
13712 // If the provided initializer fails to initialize the var decl,
13713 // we attach a recovery expr for better recovery.
13714 auto RecoveryExpr =
13715 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: Args);
13716 if (RecoveryExpr.get())
13717 VDecl->setInit(RecoveryExpr.get());
13718 // In general, for error recovery purposes, the initalizer doesn't play
13719 // part in the valid bit of the declaration. There are a few exceptions:
13720 // 1) if the var decl has a deduced auto type, and the type cannot be
13721 // deduced by an invalid initializer;
13722 // 2) if the var decl is decompsition decl with a non-deduced type, and
13723 // the initialization fails (e.g. `int [a] = {1, 2};`);
13724 // Case 1) was already handled elsewhere.
13725 if (isa<DecompositionDecl>(Val: VDecl)) // Case 2)
13726 VDecl->setInvalidDecl();
13727 return;
13728 }
13729
13730 Init = Result.getAs<Expr>();
13731 IsParenListInit = !InitSeq.steps().empty() &&
13732 InitSeq.step_begin()->Kind ==
13733 InitializationSequence::SK_ParenthesizedListInit;
13734 QualType VDeclType = VDecl->getType();
13735 if (Init && !Init->getType().isNull() &&
13736 !Init->getType()->isDependentType() && !VDeclType->isDependentType() &&
13737 Context.getAsIncompleteArrayType(T: VDeclType) &&
13738 Context.getAsIncompleteArrayType(T: Init->getType())) {
13739 // Bail out if it is not possible to deduce array size from the
13740 // initializer.
13741 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13742 << VDeclType;
13743 VDecl->setInvalidDecl();
13744 return;
13745 }
13746 }
13747
13748 // Check for self-references within variable initializers.
13749 // Variables declared within a function/method body (except for references)
13750 // are handled by a dataflow analysis.
13751 // This is undefined behavior in C++, but valid in C.
13752 if (getLangOpts().CPlusPlus)
13753 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13754 VDecl->getType()->isReferenceType())
13755 CheckSelfReference(S&: *this, OrigDecl: RealDecl, E: Init, DirectInit);
13756
13757 // If the type changed, it means we had an incomplete type that was
13758 // completed by the initializer. For example:
13759 // int ary[] = { 1, 3, 5 };
13760 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13761 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13762 VDecl->setType(DclT);
13763
13764 if (!VDecl->isInvalidDecl()) {
13765 checkUnsafeAssigns(Loc: VDecl->getLocation(), LHS: VDecl->getType(), RHS: Init);
13766
13767 if (VDecl->hasAttr<BlocksAttr>())
13768 checkRetainCycles(Var: VDecl, Init);
13769
13770 // It is safe to assign a weak reference into a strong variable.
13771 // Although this code can still have problems:
13772 // id x = self.weakProp;
13773 // id y = self.weakProp;
13774 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13775 // paths through the function. This should be revisited if
13776 // -Wrepeated-use-of-weak is made flow-sensitive.
13777 if (FunctionScopeInfo *FSI = getCurFunction())
13778 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13779 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
13780 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13781 Init->getBeginLoc()))
13782 FSI->markSafeWeakUse(E: Init);
13783 }
13784
13785 // The initialization is usually a full-expression.
13786 //
13787 // FIXME: If this is a braced initialization of an aggregate, it is not
13788 // an expression, and each individual field initializer is a separate
13789 // full-expression. For instance, in:
13790 //
13791 // struct Temp { ~Temp(); };
13792 // struct S { S(Temp); };
13793 // struct T { S a, b; } t = { Temp(), Temp() }
13794 //
13795 // we should destroy the first Temp before constructing the second.
13796 ExprResult Result =
13797 ActOnFinishFullExpr(Init, VDecl->getLocation(),
13798 /*DiscardedValue*/ false, VDecl->isConstexpr());
13799 if (Result.isInvalid()) {
13800 VDecl->setInvalidDecl();
13801 return;
13802 }
13803 Init = Result.get();
13804
13805 // Attach the initializer to the decl.
13806 VDecl->setInit(Init);
13807
13808 if (VDecl->isLocalVarDecl()) {
13809 // Don't check the initializer if the declaration is malformed.
13810 if (VDecl->isInvalidDecl()) {
13811 // do nothing
13812
13813 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13814 // This is true even in C++ for OpenCL.
13815 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13816 CheckForConstantInitializer(Init);
13817
13818 // Otherwise, C++ does not restrict the initializer.
13819 } else if (getLangOpts().CPlusPlus) {
13820 // do nothing
13821
13822 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13823 // static storage duration shall be constant expressions or string literals.
13824 } else if (VDecl->getStorageClass() == SC_Static) {
13825 CheckForConstantInitializer(Init);
13826
13827 // C89 is stricter than C99 for aggregate initializers.
13828 // C89 6.5.7p3: All the expressions [...] in an initializer list
13829 // for an object that has aggregate or union type shall be
13830 // constant expressions.
13831 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13832 isa<InitListExpr>(Val: Init)) {
13833 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
13834 }
13835
13836 if (auto *E = dyn_cast<ExprWithCleanups>(Val: Init))
13837 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13838 if (VDecl->hasLocalStorage())
13839 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13840 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13841 VDecl->getLexicalDeclContext()->isRecord()) {
13842 // This is an in-class initialization for a static data member, e.g.,
13843 //
13844 // struct S {
13845 // static const int value = 17;
13846 // };
13847
13848 // C++ [class.mem]p4:
13849 // A member-declarator can contain a constant-initializer only
13850 // if it declares a static member (9.4) of const integral or
13851 // const enumeration type, see 9.4.2.
13852 //
13853 // C++11 [class.static.data]p3:
13854 // If a non-volatile non-inline const static data member is of integral
13855 // or enumeration type, its declaration in the class definition can
13856 // specify a brace-or-equal-initializer in which every initializer-clause
13857 // that is an assignment-expression is a constant expression. A static
13858 // data member of literal type can be declared in the class definition
13859 // with the constexpr specifier; if so, its declaration shall specify a
13860 // brace-or-equal-initializer in which every initializer-clause that is
13861 // an assignment-expression is a constant expression.
13862
13863 // Do nothing on dependent types.
13864 if (DclT->isDependentType()) {
13865
13866 // Allow any 'static constexpr' members, whether or not they are of literal
13867 // type. We separately check that every constexpr variable is of literal
13868 // type.
13869 } else if (VDecl->isConstexpr()) {
13870
13871 // Require constness.
13872 } else if (!DclT.isConstQualified()) {
13873 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13874 << Init->getSourceRange();
13875 VDecl->setInvalidDecl();
13876
13877 // We allow integer constant expressions in all cases.
13878 } else if (DclT->isIntegralOrEnumerationType()) {
13879 // Check whether the expression is a constant expression.
13880 SourceLocation Loc;
13881 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
13882 // In C++11, a non-constexpr const static data member with an
13883 // in-class initializer cannot be volatile.
13884 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13885 else if (Init->isValueDependent())
13886 ; // Nothing to check.
13887 else if (Init->isIntegerConstantExpr(Ctx: Context, Loc: &Loc))
13888 ; // Ok, it's an ICE!
13889 else if (Init->getType()->isScopedEnumeralType() &&
13890 Init->isCXX11ConstantExpr(Ctx: Context))
13891 ; // Ok, it is a scoped-enum constant expression.
13892 else if (Init->isEvaluatable(Ctx: Context)) {
13893 // If we can constant fold the initializer through heroics, accept it,
13894 // but report this as a use of an extension for -pedantic.
13895 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13896 << Init->getSourceRange();
13897 } else {
13898 // Otherwise, this is some crazy unknown case. Report the issue at the
13899 // location provided by the isIntegerConstantExpr failed check.
13900 Diag(Loc, diag::err_in_class_initializer_non_constant)
13901 << Init->getSourceRange();
13902 VDecl->setInvalidDecl();
13903 }
13904
13905 // We allow foldable floating-point constants as an extension.
13906 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13907 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13908 // it anyway and provide a fixit to add the 'constexpr'.
13909 if (getLangOpts().CPlusPlus11) {
13910 Diag(VDecl->getLocation(),
13911 diag::ext_in_class_initializer_float_type_cxx11)
13912 << DclT << Init->getSourceRange();
13913 Diag(VDecl->getBeginLoc(),
13914 diag::note_in_class_initializer_float_type_cxx11)
13915 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13916 } else {
13917 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13918 << DclT << Init->getSourceRange();
13919
13920 if (!Init->isValueDependent() && !Init->isEvaluatable(Ctx: Context)) {
13921 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13922 << Init->getSourceRange();
13923 VDecl->setInvalidDecl();
13924 }
13925 }
13926
13927 // Suggest adding 'constexpr' in C++11 for literal types.
13928 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Ctx: Context)) {
13929 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13930 << DclT << Init->getSourceRange()
13931 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13932 VDecl->setConstexpr(true);
13933
13934 } else {
13935 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13936 << DclT << Init->getSourceRange();
13937 VDecl->setInvalidDecl();
13938 }
13939 } else if (VDecl->isFileVarDecl()) {
13940 // In C, extern is typically used to avoid tentative definitions when
13941 // declaring variables in headers, but adding an intializer makes it a
13942 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13943 // In C++, extern is often used to give implictly static const variables
13944 // external linkage, so don't warn in that case. If selectany is present,
13945 // this might be header code intended for C and C++ inclusion, so apply the
13946 // C++ rules.
13947 if (VDecl->getStorageClass() == SC_Extern &&
13948 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13949 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
13950 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13951 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
13952 Diag(VDecl->getLocation(), diag::warn_extern_init);
13953
13954 // In Microsoft C++ mode, a const variable defined in namespace scope has
13955 // external linkage by default if the variable is declared with
13956 // __declspec(dllexport).
13957 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13958 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
13959 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13960 VDecl->setStorageClass(SC_Extern);
13961
13962 // C99 6.7.8p4. All file scoped initializers need to be constant.
13963 // Avoid duplicate diagnostics for constexpr variables.
13964 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
13965 !VDecl->isConstexpr())
13966 CheckForConstantInitializer(Init);
13967 }
13968
13969 QualType InitType = Init->getType();
13970 if (!InitType.isNull() &&
13971 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13972 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
13973 checkNonTrivialCUnionInInitializer(Init, Loc: Init->getExprLoc());
13974
13975 // We will represent direct-initialization similarly to copy-initialization:
13976 // int x(1); -as-> int x = 1;
13977 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13978 //
13979 // Clients that want to distinguish between the two forms, can check for
13980 // direct initializer using VarDecl::getInitStyle().
13981 // A major benefit is that clients that don't particularly care about which
13982 // exactly form was it (like the CodeGen) can handle both cases without
13983 // special case code.
13984
13985 // C++ 8.5p11:
13986 // The form of initialization (using parentheses or '=') is generally
13987 // insignificant, but does matter when the entity being initialized has a
13988 // class type.
13989 if (CXXDirectInit) {
13990 assert(DirectInit && "Call-style initializer must be direct init.");
13991 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13992 : VarDecl::CallInit);
13993 } else if (DirectInit) {
13994 // This must be list-initialization. No other way is direct-initialization.
13995 VDecl->setInitStyle(VarDecl::ListInit);
13996 }
13997
13998 if (LangOpts.OpenMP &&
13999 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14000 VDecl->isFileVarDecl())
14001 DeclsToCheckForDeferredDiags.insert(VDecl);
14002 CheckCompleteVariableDeclaration(VD: VDecl);
14003}
14004
14005/// ActOnInitializerError - Given that there was an error parsing an
14006/// initializer for the given declaration, try to at least re-establish
14007/// invariants such as whether a variable's type is either dependent or
14008/// complete.
14009void Sema::ActOnInitializerError(Decl *D) {
14010 // Our main concern here is re-establishing invariants like "a
14011 // variable's type is either dependent or complete".
14012 if (!D || D->isInvalidDecl()) return;
14013
14014 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14015 if (!VD) return;
14016
14017 // Bindings are not usable if we can't make sense of the initializer.
14018 if (auto *DD = dyn_cast<DecompositionDecl>(Val: D))
14019 for (auto *BD : DD->bindings())
14020 BD->setInvalidDecl();
14021
14022 // Auto types are meaningless if we can't make sense of the initializer.
14023 if (VD->getType()->isUndeducedType()) {
14024 D->setInvalidDecl();
14025 return;
14026 }
14027
14028 QualType Ty = VD->getType();
14029 if (Ty->isDependentType()) return;
14030
14031 // Require a complete type.
14032 if (RequireCompleteType(VD->getLocation(),
14033 Context.getBaseElementType(Ty),
14034 diag::err_typecheck_decl_incomplete_type)) {
14035 VD->setInvalidDecl();
14036 return;
14037 }
14038
14039 // Require a non-abstract type.
14040 if (RequireNonAbstractType(VD->getLocation(), Ty,
14041 diag::err_abstract_type_in_decl,
14042 AbstractVariableType)) {
14043 VD->setInvalidDecl();
14044 return;
14045 }
14046
14047 // Don't bother complaining about constructors or destructors,
14048 // though.
14049}
14050
14051void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
14052 // If there is no declaration, there was an error parsing it. Just ignore it.
14053 if (!RealDecl)
14054 return;
14055
14056 if (VarDecl *Var = dyn_cast<VarDecl>(Val: RealDecl)) {
14057 QualType Type = Var->getType();
14058
14059 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14060 if (isa<DecompositionDecl>(Val: RealDecl)) {
14061 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
14062 Var->setInvalidDecl();
14063 return;
14064 }
14065
14066 if (Type->isUndeducedType() &&
14067 DeduceVariableDeclarationType(VDecl: Var, DirectInit: false, Init: nullptr))
14068 return;
14069
14070 // C++11 [class.static.data]p3: A static data member can be declared with
14071 // the constexpr specifier; if so, its declaration shall specify
14072 // a brace-or-equal-initializer.
14073 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14074 // the definition of a variable [...] or the declaration of a static data
14075 // member.
14076 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14077 !Var->isThisDeclarationADemotedDefinition()) {
14078 if (Var->isStaticDataMember()) {
14079 // C++1z removes the relevant rule; the in-class declaration is always
14080 // a definition there.
14081 if (!getLangOpts().CPlusPlus17 &&
14082 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14083 Diag(Var->getLocation(),
14084 diag::err_constexpr_static_mem_var_requires_init)
14085 << Var;
14086 Var->setInvalidDecl();
14087 return;
14088 }
14089 } else {
14090 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14091 Var->setInvalidDecl();
14092 return;
14093 }
14094 }
14095
14096 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14097 // be initialized.
14098 if (!Var->isInvalidDecl() &&
14099 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14100 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14101 bool HasConstExprDefaultConstructor = false;
14102 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14103 for (auto *Ctor : RD->ctors()) {
14104 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14105 Ctor->getMethodQualifiers().getAddressSpace() ==
14106 LangAS::opencl_constant) {
14107 HasConstExprDefaultConstructor = true;
14108 }
14109 }
14110 }
14111 if (!HasConstExprDefaultConstructor) {
14112 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14113 Var->setInvalidDecl();
14114 return;
14115 }
14116 }
14117
14118 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14119 if (Var->getStorageClass() == SC_Extern) {
14120 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14121 << Var;
14122 Var->setInvalidDecl();
14123 return;
14124 }
14125 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14126 diag::err_typecheck_decl_incomplete_type)) {
14127 Var->setInvalidDecl();
14128 return;
14129 }
14130 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14131 if (!RD->hasTrivialDefaultConstructor()) {
14132 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14133 Var->setInvalidDecl();
14134 return;
14135 }
14136 }
14137 // The declaration is unitialized, no need for further checks.
14138 return;
14139 }
14140
14141 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14142 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14143 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14144 checkNonTrivialCUnion(QT: Var->getType(), Loc: Var->getLocation(),
14145 UseContext: NTCUC_DefaultInitializedObject, NonTrivialKind: NTCUK_Init);
14146
14147
14148 switch (DefKind) {
14149 case VarDecl::Definition:
14150 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14151 break;
14152
14153 // We have an out-of-line definition of a static data member
14154 // that has an in-class initializer, so we type-check this like
14155 // a declaration.
14156 //
14157 [[fallthrough]];
14158
14159 case VarDecl::DeclarationOnly:
14160 // It's only a declaration.
14161
14162 // Block scope. C99 6.7p7: If an identifier for an object is
14163 // declared with no linkage (C99 6.2.2p6), the type for the
14164 // object shall be complete.
14165 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14166 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14167 RequireCompleteType(Var->getLocation(), Type,
14168 diag::err_typecheck_decl_incomplete_type))
14169 Var->setInvalidDecl();
14170
14171 // Make sure that the type is not abstract.
14172 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14173 RequireNonAbstractType(Var->getLocation(), Type,
14174 diag::err_abstract_type_in_decl,
14175 AbstractVariableType))
14176 Var->setInvalidDecl();
14177 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14178 Var->getStorageClass() == SC_PrivateExtern) {
14179 Diag(Var->getLocation(), diag::warn_private_extern);
14180 Diag(Var->getLocation(), diag::note_private_extern);
14181 }
14182
14183 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14184 !Var->isInvalidDecl())
14185 ExternalDeclarations.push_back(Elt: Var);
14186
14187 return;
14188
14189 case VarDecl::TentativeDefinition:
14190 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14191 // object that has file scope without an initializer, and without a
14192 // storage-class specifier or with the storage-class specifier "static",
14193 // constitutes a tentative definition. Note: A tentative definition with
14194 // external linkage is valid (C99 6.2.2p5).
14195 if (!Var->isInvalidDecl()) {
14196 if (const IncompleteArrayType *ArrayT
14197 = Context.getAsIncompleteArrayType(T: Type)) {
14198 if (RequireCompleteSizedType(
14199 Var->getLocation(), ArrayT->getElementType(),
14200 diag::err_array_incomplete_or_sizeless_type))
14201 Var->setInvalidDecl();
14202 } else if (Var->getStorageClass() == SC_Static) {
14203 // C99 6.9.2p3: If the declaration of an identifier for an object is
14204 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14205 // declared type shall not be an incomplete type.
14206 // NOTE: code such as the following
14207 // static struct s;
14208 // struct s { int a; };
14209 // is accepted by gcc. Hence here we issue a warning instead of
14210 // an error and we do not invalidate the static declaration.
14211 // NOTE: to avoid multiple warnings, only check the first declaration.
14212 if (Var->isFirstDecl())
14213 RequireCompleteType(Var->getLocation(), Type,
14214 diag::ext_typecheck_decl_incomplete_type);
14215 }
14216 }
14217
14218 // Record the tentative definition; we're done.
14219 if (!Var->isInvalidDecl())
14220 TentativeDefinitions.push_back(LocalValue: Var);
14221 return;
14222 }
14223
14224 // Provide a specific diagnostic for uninitialized variable
14225 // definitions with incomplete array type.
14226 if (Type->isIncompleteArrayType()) {
14227 if (Var->isConstexpr())
14228 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14229 << Var;
14230 else
14231 Diag(Var->getLocation(),
14232 diag::err_typecheck_incomplete_array_needs_initializer);
14233 Var->setInvalidDecl();
14234 return;
14235 }
14236
14237 // Provide a specific diagnostic for uninitialized variable
14238 // definitions with reference type.
14239 if (Type->isReferenceType()) {
14240 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14241 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14242 return;
14243 }
14244
14245 // Do not attempt to type-check the default initializer for a
14246 // variable with dependent type.
14247 if (Type->isDependentType())
14248 return;
14249
14250 if (Var->isInvalidDecl())
14251 return;
14252
14253 if (!Var->hasAttr<AliasAttr>()) {
14254 if (RequireCompleteType(Var->getLocation(),
14255 Context.getBaseElementType(Type),
14256 diag::err_typecheck_decl_incomplete_type)) {
14257 Var->setInvalidDecl();
14258 return;
14259 }
14260 } else {
14261 return;
14262 }
14263
14264 // The variable can not have an abstract class type.
14265 if (RequireNonAbstractType(Var->getLocation(), Type,
14266 diag::err_abstract_type_in_decl,
14267 AbstractVariableType)) {
14268 Var->setInvalidDecl();
14269 return;
14270 }
14271
14272 // Check for jumps past the implicit initializer. C++0x
14273 // clarifies that this applies to a "variable with automatic
14274 // storage duration", not a "local variable".
14275 // C++11 [stmt.dcl]p3
14276 // A program that jumps from a point where a variable with automatic
14277 // storage duration is not in scope to a point where it is in scope is
14278 // ill-formed unless the variable has scalar type, class type with a
14279 // trivial default constructor and a trivial destructor, a cv-qualified
14280 // version of one of these types, or an array of one of the preceding
14281 // types and is declared without an initializer.
14282 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14283 if (const RecordType *Record
14284 = Context.getBaseElementType(QT: Type)->getAs<RecordType>()) {
14285 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record->getDecl());
14286 // Mark the function (if we're in one) for further checking even if the
14287 // looser rules of C++11 do not require such checks, so that we can
14288 // diagnose incompatibilities with C++98.
14289 if (!CXXRecord->isPOD())
14290 setFunctionHasBranchProtectedScope();
14291 }
14292 }
14293 // In OpenCL, we can't initialize objects in the __local address space,
14294 // even implicitly, so don't synthesize an implicit initializer.
14295 if (getLangOpts().OpenCL &&
14296 Var->getType().getAddressSpace() == LangAS::opencl_local)
14297 return;
14298 // C++03 [dcl.init]p9:
14299 // If no initializer is specified for an object, and the
14300 // object is of (possibly cv-qualified) non-POD class type (or
14301 // array thereof), the object shall be default-initialized; if
14302 // the object is of const-qualified type, the underlying class
14303 // type shall have a user-declared default
14304 // constructor. Otherwise, if no initializer is specified for
14305 // a non- static object, the object and its subobjects, if
14306 // any, have an indeterminate initial value); if the object
14307 // or any of its subobjects are of const-qualified type, the
14308 // program is ill-formed.
14309 // C++0x [dcl.init]p11:
14310 // If no initializer is specified for an object, the object is
14311 // default-initialized; [...].
14312 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14313 InitializationKind Kind
14314 = InitializationKind::CreateDefault(InitLoc: Var->getLocation());
14315
14316 InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
14317 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: std::nullopt);
14318
14319 if (Init.get()) {
14320 Var->setInit(MaybeCreateExprWithCleanups(SubExpr: Init.get()));
14321 // This is important for template substitution.
14322 Var->setInitStyle(VarDecl::CallInit);
14323 } else if (Init.isInvalid()) {
14324 // If default-init fails, attach a recovery-expr initializer to track
14325 // that initialization was attempted and failed.
14326 auto RecoveryExpr =
14327 CreateRecoveryExpr(Begin: Var->getLocation(), End: Var->getLocation(), SubExprs: {});
14328 if (RecoveryExpr.get())
14329 Var->setInit(RecoveryExpr.get());
14330 }
14331
14332 CheckCompleteVariableDeclaration(VD: Var);
14333 }
14334}
14335
14336void Sema::ActOnCXXForRangeDecl(Decl *D) {
14337 // If there is no declaration, there was an error parsing it. Ignore it.
14338 if (!D)
14339 return;
14340
14341 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14342 if (!VD) {
14343 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14344 D->setInvalidDecl();
14345 return;
14346 }
14347
14348 VD->setCXXForRangeDecl(true);
14349
14350 // for-range-declaration cannot be given a storage class specifier.
14351 int Error = -1;
14352 switch (VD->getStorageClass()) {
14353 case SC_None:
14354 break;
14355 case SC_Extern:
14356 Error = 0;
14357 break;
14358 case SC_Static:
14359 Error = 1;
14360 break;
14361 case SC_PrivateExtern:
14362 Error = 2;
14363 break;
14364 case SC_Auto:
14365 Error = 3;
14366 break;
14367 case SC_Register:
14368 Error = 4;
14369 break;
14370 }
14371
14372 // for-range-declaration cannot be given a storage class specifier con't.
14373 switch (VD->getTSCSpec()) {
14374 case TSCS_thread_local:
14375 Error = 6;
14376 break;
14377 case TSCS___thread:
14378 case TSCS__Thread_local:
14379 case TSCS_unspecified:
14380 break;
14381 }
14382
14383 if (Error != -1) {
14384 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14385 << VD << Error;
14386 D->setInvalidDecl();
14387 }
14388}
14389
14390StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
14391 IdentifierInfo *Ident,
14392 ParsedAttributes &Attrs) {
14393 // C++1y [stmt.iter]p1:
14394 // A range-based for statement of the form
14395 // for ( for-range-identifier : for-range-initializer ) statement
14396 // is equivalent to
14397 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14398 DeclSpec DS(Attrs.getPool().getFactory());
14399
14400 const char *PrevSpec;
14401 unsigned DiagID;
14402 DS.SetTypeSpecType(T: DeclSpec::TST_auto, Loc: IdentLoc, PrevSpec, DiagID,
14403 Policy: getPrintingPolicy());
14404
14405 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14406 D.SetIdentifier(Id: Ident, IdLoc: IdentLoc);
14407 D.takeAttributes(attrs&: Attrs);
14408
14409 D.AddTypeInfo(TI: DeclaratorChunk::getReference(TypeQuals: 0, Loc: IdentLoc, /*lvalue*/ false),
14410 EndLoc: IdentLoc);
14411 Decl *Var = ActOnDeclarator(S, D);
14412 cast<VarDecl>(Val: Var)->setCXXForRangeDecl(true);
14413 FinalizeDeclaration(D: Var);
14414 return ActOnDeclStmt(Decl: FinalizeDeclaratorGroup(S, DS, Group: Var), StartLoc: IdentLoc,
14415 EndLoc: Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14416 : IdentLoc);
14417}
14418
14419void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14420 if (var->isInvalidDecl()) return;
14421
14422 CUDA().MaybeAddConstantAttr(VD: var);
14423
14424 if (getLangOpts().OpenCL) {
14425 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14426 // initialiser
14427 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14428 !var->hasInit()) {
14429 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14430 << 1 /*Init*/;
14431 var->setInvalidDecl();
14432 return;
14433 }
14434 }
14435
14436 // In Objective-C, don't allow jumps past the implicit initialization of a
14437 // local retaining variable.
14438 if (getLangOpts().ObjC &&
14439 var->hasLocalStorage()) {
14440 switch (var->getType().getObjCLifetime()) {
14441 case Qualifiers::OCL_None:
14442 case Qualifiers::OCL_ExplicitNone:
14443 case Qualifiers::OCL_Autoreleasing:
14444 break;
14445
14446 case Qualifiers::OCL_Weak:
14447 case Qualifiers::OCL_Strong:
14448 setFunctionHasBranchProtectedScope();
14449 break;
14450 }
14451 }
14452
14453 if (var->hasLocalStorage() &&
14454 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14455 setFunctionHasBranchProtectedScope();
14456
14457 // Warn about externally-visible variables being defined without a
14458 // prior declaration. We only want to do this for global
14459 // declarations, but we also specifically need to avoid doing it for
14460 // class members because the linkage of an anonymous class can
14461 // change if it's later given a typedef name.
14462 if (var->isThisDeclarationADefinition() &&
14463 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14464 var->isExternallyVisible() && var->hasLinkage() &&
14465 !var->isInline() && !var->getDescribedVarTemplate() &&
14466 var->getStorageClass() != SC_Register &&
14467 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14468 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14469 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14470 var->getLocation())) {
14471 // Find a previous declaration that's not a definition.
14472 VarDecl *prev = var->getPreviousDecl();
14473 while (prev && prev->isThisDeclarationADefinition())
14474 prev = prev->getPreviousDecl();
14475
14476 if (!prev) {
14477 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14478 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14479 << /* variable */ 0;
14480 }
14481 }
14482
14483 // Cache the result of checking for constant initialization.
14484 std::optional<bool> CacheHasConstInit;
14485 const Expr *CacheCulprit = nullptr;
14486 auto checkConstInit = [&]() mutable {
14487 if (!CacheHasConstInit)
14488 CacheHasConstInit = var->getInit()->isConstantInitializer(
14489 Ctx&: Context, ForRef: var->getType()->isReferenceType(), Culprit: &CacheCulprit);
14490 return *CacheHasConstInit;
14491 };
14492
14493 if (var->getTLSKind() == VarDecl::TLS_Static) {
14494 if (var->getType().isDestructedType()) {
14495 // GNU C++98 edits for __thread, [basic.start.term]p3:
14496 // The type of an object with thread storage duration shall not
14497 // have a non-trivial destructor.
14498 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14499 if (getLangOpts().CPlusPlus11)
14500 Diag(var->getLocation(), diag::note_use_thread_local);
14501 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14502 if (!checkConstInit()) {
14503 // GNU C++98 edits for __thread, [basic.start.init]p4:
14504 // An object of thread storage duration shall not require dynamic
14505 // initialization.
14506 // FIXME: Need strict checking here.
14507 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14508 << CacheCulprit->getSourceRange();
14509 if (getLangOpts().CPlusPlus11)
14510 Diag(var->getLocation(), diag::note_use_thread_local);
14511 }
14512 }
14513 }
14514
14515
14516 if (!var->getType()->isStructureType() && var->hasInit() &&
14517 isa<InitListExpr>(Val: var->getInit())) {
14518 const auto *ILE = cast<InitListExpr>(Val: var->getInit());
14519 unsigned NumInits = ILE->getNumInits();
14520 if (NumInits > 2)
14521 for (unsigned I = 0; I < NumInits; ++I) {
14522 const auto *Init = ILE->getInit(Init: I);
14523 if (!Init)
14524 break;
14525 const auto *SL = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
14526 if (!SL)
14527 break;
14528
14529 unsigned NumConcat = SL->getNumConcatenated();
14530 // Diagnose missing comma in string array initialization.
14531 // Do not warn when all the elements in the initializer are concatenated
14532 // together. Do not warn for macros too.
14533 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14534 bool OnlyOneMissingComma = true;
14535 for (unsigned J = I + 1; J < NumInits; ++J) {
14536 const auto *Init = ILE->getInit(Init: J);
14537 if (!Init)
14538 break;
14539 const auto *SLJ = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
14540 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14541 OnlyOneMissingComma = false;
14542 break;
14543 }
14544 }
14545
14546 if (OnlyOneMissingComma) {
14547 SmallVector<FixItHint, 1> Hints;
14548 for (unsigned i = 0; i < NumConcat - 1; ++i)
14549 Hints.push_back(Elt: FixItHint::CreateInsertion(
14550 InsertionLoc: PP.getLocForEndOfToken(Loc: SL->getStrTokenLoc(TokNum: i)), Code: ","));
14551
14552 Diag(SL->getStrTokenLoc(1),
14553 diag::warn_concatenated_literal_array_init)
14554 << Hints;
14555 Diag(SL->getBeginLoc(),
14556 diag::note_concatenated_string_literal_silence);
14557 }
14558 // In any case, stop now.
14559 break;
14560 }
14561 }
14562 }
14563
14564
14565 QualType type = var->getType();
14566
14567 if (var->hasAttr<BlocksAttr>())
14568 getCurFunction()->addByrefBlockVar(VD: var);
14569
14570 Expr *Init = var->getInit();
14571 bool GlobalStorage = var->hasGlobalStorage();
14572 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14573 QualType baseType = Context.getBaseElementType(QT: type);
14574 bool HasConstInit = true;
14575
14576 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14577 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14578 << var;
14579
14580 // Check whether the initializer is sufficiently constant.
14581 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14582 !type->isDependentType() && Init && !Init->isValueDependent() &&
14583 (GlobalStorage || var->isConstexpr() ||
14584 var->mightBeUsableInConstantExpressions(C: Context))) {
14585 // If this variable might have a constant initializer or might be usable in
14586 // constant expressions, check whether or not it actually is now. We can't
14587 // do this lazily, because the result might depend on things that change
14588 // later, such as which constexpr functions happen to be defined.
14589 SmallVector<PartialDiagnosticAt, 8> Notes;
14590 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14591 // Prior to C++11, in contexts where a constant initializer is required,
14592 // the set of valid constant initializers is described by syntactic rules
14593 // in [expr.const]p2-6.
14594 // FIXME: Stricter checking for these rules would be useful for constinit /
14595 // -Wglobal-constructors.
14596 HasConstInit = checkConstInit();
14597
14598 // Compute and cache the constant value, and remember that we have a
14599 // constant initializer.
14600 if (HasConstInit) {
14601 (void)var->checkForConstantInitialization(Notes);
14602 Notes.clear();
14603 } else if (CacheCulprit) {
14604 Notes.emplace_back(CacheCulprit->getExprLoc(),
14605 PDiag(diag::note_invalid_subexpr_in_const_expr));
14606 Notes.back().second << CacheCulprit->getSourceRange();
14607 }
14608 } else {
14609 // Evaluate the initializer to see if it's a constant initializer.
14610 HasConstInit = var->checkForConstantInitialization(Notes);
14611 }
14612
14613 if (HasConstInit) {
14614 // FIXME: Consider replacing the initializer with a ConstantExpr.
14615 } else if (var->isConstexpr()) {
14616 SourceLocation DiagLoc = var->getLocation();
14617 // If the note doesn't add any useful information other than a source
14618 // location, fold it into the primary diagnostic.
14619 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14620 diag::note_invalid_subexpr_in_const_expr) {
14621 DiagLoc = Notes[0].first;
14622 Notes.clear();
14623 }
14624 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14625 << var << Init->getSourceRange();
14626 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14627 Diag(Notes[I].first, Notes[I].second);
14628 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14629 auto *Attr = var->getAttr<ConstInitAttr>();
14630 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14631 << Init->getSourceRange();
14632 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14633 << Attr->getRange() << Attr->isConstinit();
14634 for (auto &it : Notes)
14635 Diag(it.first, it.second);
14636 } else if (IsGlobal &&
14637 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14638 var->getLocation())) {
14639 // Warn about globals which don't have a constant initializer. Don't
14640 // warn about globals with a non-trivial destructor because we already
14641 // warned about them.
14642 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14643 if (!(RD && !RD->hasTrivialDestructor())) {
14644 // checkConstInit() here permits trivial default initialization even in
14645 // C++11 onwards, where such an initializer is not a constant initializer
14646 // but nonetheless doesn't require a global constructor.
14647 if (!checkConstInit())
14648 Diag(var->getLocation(), diag::warn_global_constructor)
14649 << Init->getSourceRange();
14650 }
14651 }
14652 }
14653
14654 // Apply section attributes and pragmas to global variables.
14655 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14656 !inTemplateInstantiation()) {
14657 PragmaStack<StringLiteral *> *Stack = nullptr;
14658 int SectionFlags = ASTContext::PSF_Read;
14659 bool MSVCEnv =
14660 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14661 std::optional<QualType::NonConstantStorageReason> Reason;
14662 if (HasConstInit &&
14663 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14664 Stack = &ConstSegStack;
14665 } else {
14666 SectionFlags |= ASTContext::PSF_Write;
14667 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14668 }
14669 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14670 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14671 SectionFlags |= ASTContext::PSF_Implicit;
14672 UnifySection(SA->getName(), SectionFlags, var);
14673 } else if (Stack->CurrentValue) {
14674 if (Stack != &ConstSegStack && MSVCEnv &&
14675 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14676 var->getType().isConstQualified()) {
14677 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14678 NonConstNonReferenceType) &&
14679 "This case should've already been handled elsewhere");
14680 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14681 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14682 ? QualType::NonConstantStorageReason::NonTrivialCtor
14683 : *Reason);
14684 }
14685 SectionFlags |= ASTContext::PSF_Implicit;
14686 auto SectionName = Stack->CurrentValue->getString();
14687 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14688 Stack->CurrentPragmaLocation,
14689 SectionAttr::Declspec_allocate));
14690 if (UnifySection(SectionName, SectionFlags, var))
14691 var->dropAttr<SectionAttr>();
14692 }
14693
14694 // Apply the init_seg attribute if this has an initializer. If the
14695 // initializer turns out to not be dynamic, we'll end up ignoring this
14696 // attribute.
14697 if (CurInitSeg && var->getInit())
14698 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14699 CurInitSegLoc));
14700 }
14701
14702 // All the following checks are C++ only.
14703 if (!getLangOpts().CPlusPlus) {
14704 // If this variable must be emitted, add it as an initializer for the
14705 // current module.
14706 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14707 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14708 return;
14709 }
14710
14711 // Require the destructor.
14712 if (!type->isDependentType())
14713 if (const RecordType *recordType = baseType->getAs<RecordType>())
14714 FinalizeVarWithDestructor(VD: var, DeclInitType: recordType);
14715
14716 // If this variable must be emitted, add it as an initializer for the current
14717 // module.
14718 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14719 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14720
14721 // Build the bindings if this is a structured binding declaration.
14722 if (auto *DD = dyn_cast<DecompositionDecl>(Val: var))
14723 CheckCompleteDecompositionDeclaration(DD);
14724}
14725
14726/// Check if VD needs to be dllexport/dllimport due to being in a
14727/// dllexport/import function.
14728void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
14729 assert(VD->isStaticLocal());
14730
14731 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14732
14733 // Find outermost function when VD is in lambda function.
14734 while (FD && !getDLLAttr(FD) &&
14735 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14736 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14737 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14738 }
14739
14740 if (!FD)
14741 return;
14742
14743 // Static locals inherit dll attributes from their function.
14744 if (Attr *A = getDLLAttr(FD)) {
14745 auto *NewAttr = cast<InheritableAttr>(Val: A->clone(C&: getASTContext()));
14746 NewAttr->setInherited(true);
14747 VD->addAttr(A: NewAttr);
14748 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14749 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14750 NewAttr->setInherited(true);
14751 VD->addAttr(A: NewAttr);
14752
14753 // Export this function to enforce exporting this static variable even
14754 // if it is not used in this compilation unit.
14755 if (!FD->hasAttr<DLLExportAttr>())
14756 FD->addAttr(NewAttr);
14757
14758 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14759 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14760 NewAttr->setInherited(true);
14761 VD->addAttr(A: NewAttr);
14762 }
14763}
14764
14765void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
14766 assert(VD->getTLSKind());
14767
14768 // Perform TLS alignment check here after attributes attached to the variable
14769 // which may affect the alignment have been processed. Only perform the check
14770 // if the target has a maximum TLS alignment (zero means no constraints).
14771 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14772 // Protect the check so that it's not performed on dependent types and
14773 // dependent alignments (we can't determine the alignment in that case).
14774 if (!VD->hasDependentAlignment()) {
14775 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(BitSize: MaxAlign);
14776 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14777 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14778 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
14779 << (unsigned)MaxAlignChars.getQuantity();
14780 }
14781 }
14782 }
14783}
14784
14785/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
14786/// any semantic actions necessary after any initializer has been attached.
14787void Sema::FinalizeDeclaration(Decl *ThisDecl) {
14788 // Note that we are no longer parsing the initializer for this declaration.
14789 ParsingInitForAutoVars.erase(Ptr: ThisDecl);
14790
14791 VarDecl *VD = dyn_cast_or_null<VarDecl>(Val: ThisDecl);
14792 if (!VD)
14793 return;
14794
14795 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14796 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
14797 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14798 if (PragmaClangBSSSection.Valid)
14799 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14800 Context, PragmaClangBSSSection.SectionName,
14801 PragmaClangBSSSection.PragmaLocation));
14802 if (PragmaClangDataSection.Valid)
14803 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14804 Context, PragmaClangDataSection.SectionName,
14805 PragmaClangDataSection.PragmaLocation));
14806 if (PragmaClangRodataSection.Valid)
14807 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14808 Context, PragmaClangRodataSection.SectionName,
14809 PragmaClangRodataSection.PragmaLocation));
14810 if (PragmaClangRelroSection.Valid)
14811 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14812 Context, PragmaClangRelroSection.SectionName,
14813 PragmaClangRelroSection.PragmaLocation));
14814 }
14815
14816 if (auto *DD = dyn_cast<DecompositionDecl>(Val: ThisDecl)) {
14817 for (auto *BD : DD->bindings()) {
14818 FinalizeDeclaration(BD);
14819 }
14820 }
14821
14822 checkAttributesAfterMerging(*this, *VD);
14823
14824 if (VD->isStaticLocal())
14825 CheckStaticLocalForDllExport(VD);
14826
14827 if (VD->getTLSKind())
14828 CheckThreadLocalForLargeAlignment(VD);
14829
14830 // Perform check for initializers of device-side global variables.
14831 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14832 // 7.5). We must also apply the same checks to all __shared__
14833 // variables whether they are local or not. CUDA also allows
14834 // constant initializers for __constant__ and __device__ variables.
14835 if (getLangOpts().CUDA)
14836 CUDA().checkAllowedInitializer(VD);
14837
14838 // Grab the dllimport or dllexport attribute off of the VarDecl.
14839 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14840
14841 // Imported static data members cannot be defined out-of-line.
14842 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14843 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14844 VD->isThisDeclarationADefinition()) {
14845 // We allow definitions of dllimport class template static data members
14846 // with a warning.
14847 CXXRecordDecl *Context =
14848 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14849 bool IsClassTemplateMember =
14850 isa<ClassTemplatePartialSpecializationDecl>(Val: Context) ||
14851 Context->getDescribedClassTemplate();
14852
14853 Diag(VD->getLocation(),
14854 IsClassTemplateMember
14855 ? diag::warn_attribute_dllimport_static_field_definition
14856 : diag::err_attribute_dllimport_static_field_definition);
14857 Diag(IA->getLocation(), diag::note_attribute);
14858 if (!IsClassTemplateMember)
14859 VD->setInvalidDecl();
14860 }
14861 }
14862
14863 // dllimport/dllexport variables cannot be thread local, their TLS index
14864 // isn't exported with the variable.
14865 if (DLLAttr && VD->getTLSKind()) {
14866 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14867 if (F && getDLLAttr(F)) {
14868 assert(VD->isStaticLocal());
14869 // But if this is a static local in a dlimport/dllexport function, the
14870 // function will never be inlined, which means the var would never be
14871 // imported, so having it marked import/export is safe.
14872 } else {
14873 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14874 << DLLAttr;
14875 VD->setInvalidDecl();
14876 }
14877 }
14878
14879 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14880 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14881 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14882 << Attr;
14883 VD->dropAttr<UsedAttr>();
14884 }
14885 }
14886 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14887 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14888 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14889 << Attr;
14890 VD->dropAttr<RetainAttr>();
14891 }
14892 }
14893
14894 const DeclContext *DC = VD->getDeclContext();
14895 // If there's a #pragma GCC visibility in scope, and this isn't a class
14896 // member, set the visibility of this variable.
14897 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
14898 AddPushedVisibilityAttribute(VD);
14899
14900 // FIXME: Warn on unused var template partial specializations.
14901 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(Val: VD))
14902 MarkUnusedFileScopedDecl(VD);
14903
14904 // Now we have parsed the initializer and can update the table of magic
14905 // tag values.
14906 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14907 !VD->getType()->isIntegralOrEnumerationType())
14908 return;
14909
14910 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14911 const Expr *MagicValueExpr = VD->getInit();
14912 if (!MagicValueExpr) {
14913 continue;
14914 }
14915 std::optional<llvm::APSInt> MagicValueInt;
14916 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14917 Diag(I->getRange().getBegin(),
14918 diag::err_type_tag_for_datatype_not_ice)
14919 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14920 continue;
14921 }
14922 if (MagicValueInt->getActiveBits() > 64) {
14923 Diag(I->getRange().getBegin(),
14924 diag::err_type_tag_for_datatype_too_large)
14925 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14926 continue;
14927 }
14928 uint64_t MagicValue = MagicValueInt->getZExtValue();
14929 RegisterTypeTagForDatatype(I->getArgumentKind(),
14930 MagicValue,
14931 I->getMatchingCType(),
14932 I->getLayoutCompatible(),
14933 I->getMustBeNull());
14934 }
14935}
14936
14937static bool hasDeducedAuto(DeclaratorDecl *DD) {
14938 auto *VD = dyn_cast<VarDecl>(Val: DD);
14939 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14940}
14941
14942Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
14943 ArrayRef<Decl *> Group) {
14944 SmallVector<Decl*, 8> Decls;
14945
14946 if (DS.isTypeSpecOwned())
14947 Decls.push_back(Elt: DS.getRepAsDecl());
14948
14949 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14950 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14951 bool DiagnosedMultipleDecomps = false;
14952 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14953 bool DiagnosedNonDeducedAuto = false;
14954
14955 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14956 if (Decl *D = Group[i]) {
14957 // Check if the Decl has been declared in '#pragma omp declare target'
14958 // directive and has static storage duration.
14959 if (auto *VD = dyn_cast<VarDecl>(Val: D);
14960 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14961 VD->hasGlobalStorage())
14962 OpenMP().ActOnOpenMPDeclareTargetInitializer(D);
14963 // For declarators, there are some additional syntactic-ish checks we need
14964 // to perform.
14965 if (auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
14966 if (!FirstDeclaratorInGroup)
14967 FirstDeclaratorInGroup = DD;
14968 if (!FirstDecompDeclaratorInGroup)
14969 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(Val: D);
14970 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14971 !hasDeducedAuto(DD))
14972 FirstNonDeducedAutoInGroup = DD;
14973
14974 if (FirstDeclaratorInGroup != DD) {
14975 // A decomposition declaration cannot be combined with any other
14976 // declaration in the same group.
14977 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14978 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14979 diag::err_decomp_decl_not_alone)
14980 << FirstDeclaratorInGroup->getSourceRange()
14981 << DD->getSourceRange();
14982 DiagnosedMultipleDecomps = true;
14983 }
14984
14985 // A declarator that uses 'auto' in any way other than to declare a
14986 // variable with a deduced type cannot be combined with any other
14987 // declarator in the same group.
14988 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14989 Diag(FirstNonDeducedAutoInGroup->getLocation(),
14990 diag::err_auto_non_deduced_not_alone)
14991 << FirstNonDeducedAutoInGroup->getType()
14992 ->hasAutoForTrailingReturnType()
14993 << FirstDeclaratorInGroup->getSourceRange()
14994 << DD->getSourceRange();
14995 DiagnosedNonDeducedAuto = true;
14996 }
14997 }
14998 }
14999
15000 Decls.push_back(Elt: D);
15001 }
15002 }
15003
15004 if (DeclSpec::isDeclRep(T: DS.getTypeSpecType())) {
15005 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl())) {
15006 handleTagNumbering(Tag, TagScope: S);
15007 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15008 getLangOpts().CPlusPlus)
15009 Context.addDeclaratorForUnnamedTagDecl(TD: Tag, DD: FirstDeclaratorInGroup);
15010 }
15011 }
15012
15013 return BuildDeclaratorGroup(Group: Decls);
15014}
15015
15016/// BuildDeclaratorGroup - convert a list of declarations into a declaration
15017/// group, performing any necessary semantic checking.
15018Sema::DeclGroupPtrTy
15019Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
15020 // C++14 [dcl.spec.auto]p7: (DR1347)
15021 // If the type that replaces the placeholder type is not the same in each
15022 // deduction, the program is ill-formed.
15023 if (Group.size() > 1) {
15024 QualType Deduced;
15025 VarDecl *DeducedDecl = nullptr;
15026 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15027 VarDecl *D = dyn_cast<VarDecl>(Val: Group[i]);
15028 if (!D || D->isInvalidDecl())
15029 break;
15030 DeducedType *DT = D->getType()->getContainedDeducedType();
15031 if (!DT || DT->getDeducedType().isNull())
15032 continue;
15033 if (Deduced.isNull()) {
15034 Deduced = DT->getDeducedType();
15035 DeducedDecl = D;
15036 } else if (!Context.hasSameType(T1: DT->getDeducedType(), T2: Deduced)) {
15037 auto *AT = dyn_cast<AutoType>(Val: DT);
15038 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15039 diag::err_auto_different_deductions)
15040 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15041 << DeducedDecl->getDeclName() << DT->getDeducedType()
15042 << D->getDeclName();
15043 if (DeducedDecl->hasInit())
15044 Dia << DeducedDecl->getInit()->getSourceRange();
15045 if (D->getInit())
15046 Dia << D->getInit()->getSourceRange();
15047 D->setInvalidDecl();
15048 break;
15049 }
15050 }
15051 }
15052
15053 ActOnDocumentableDecls(Group);
15054
15055 return DeclGroupPtrTy::make(
15056 P: DeclGroupRef::Create(C&: Context, Decls: Group.data(), NumDecls: Group.size()));
15057}
15058
15059void Sema::ActOnDocumentableDecl(Decl *D) {
15060 ActOnDocumentableDecls(Group: D);
15061}
15062
15063void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
15064 // Don't parse the comment if Doxygen diagnostics are ignored.
15065 if (Group.empty() || !Group[0])
15066 return;
15067
15068 if (Diags.isIgnored(diag::warn_doc_param_not_found,
15069 Group[0]->getLocation()) &&
15070 Diags.isIgnored(diag::warn_unknown_comment_command_name,
15071 Group[0]->getLocation()))
15072 return;
15073
15074 if (Group.size() >= 2) {
15075 // This is a decl group. Normally it will contain only declarations
15076 // produced from declarator list. But in case we have any definitions or
15077 // additional declaration references:
15078 // 'typedef struct S {} S;'
15079 // 'typedef struct S *S;'
15080 // 'struct S *pS;'
15081 // FinalizeDeclaratorGroup adds these as separate declarations.
15082 Decl *MaybeTagDecl = Group[0];
15083 if (MaybeTagDecl && isa<TagDecl>(Val: MaybeTagDecl)) {
15084 Group = Group.slice(N: 1);
15085 }
15086 }
15087
15088 // FIMXE: We assume every Decl in the group is in the same file.
15089 // This is false when preprocessor constructs the group from decls in
15090 // different files (e. g. macros or #include).
15091 Context.attachCommentsToJustParsedDecls(Decls: Group, PP: &getPreprocessor());
15092}
15093
15094/// Common checks for a parameter-declaration that should apply to both function
15095/// parameters and non-type template parameters.
15096void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
15097 // Check that there are no default arguments inside the type of this
15098 // parameter.
15099 if (getLangOpts().CPlusPlus)
15100 CheckExtraCXXDefaultArguments(D);
15101
15102 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15103 if (D.getCXXScopeSpec().isSet()) {
15104 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15105 << D.getCXXScopeSpec().getRange();
15106 }
15107
15108 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15109 // simple identifier except [...irrelevant cases...].
15110 switch (D.getName().getKind()) {
15111 case UnqualifiedIdKind::IK_Identifier:
15112 break;
15113
15114 case UnqualifiedIdKind::IK_OperatorFunctionId:
15115 case UnqualifiedIdKind::IK_ConversionFunctionId:
15116 case UnqualifiedIdKind::IK_LiteralOperatorId:
15117 case UnqualifiedIdKind::IK_ConstructorName:
15118 case UnqualifiedIdKind::IK_DestructorName:
15119 case UnqualifiedIdKind::IK_ImplicitSelfParam:
15120 case UnqualifiedIdKind::IK_DeductionGuideName:
15121 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15122 << GetNameForDeclarator(D).getName();
15123 break;
15124
15125 case UnqualifiedIdKind::IK_TemplateId:
15126 case UnqualifiedIdKind::IK_ConstructorTemplateId:
15127 // GetNameForDeclarator would not produce a useful name in this case.
15128 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15129 break;
15130 }
15131}
15132
15133static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
15134 SourceLocation ExplicitThisLoc) {
15135 if (!ExplicitThisLoc.isValid())
15136 return;
15137 assert(S.getLangOpts().CPlusPlus &&
15138 "explicit parameter in non-cplusplus mode");
15139 if (!S.getLangOpts().CPlusPlus23)
15140 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15141 << P->getSourceRange();
15142
15143 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15144 // parameter pack.
15145 if (P->isParameterPack()) {
15146 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15147 << P->getSourceRange();
15148 return;
15149 }
15150 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15151 if (LambdaScopeInfo *LSI = S.getCurLambda())
15152 LSI->ExplicitObjectParameter = P;
15153}
15154
15155/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
15156/// to introduce parameters into function prototype scope.
15157Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15158 SourceLocation ExplicitThisLoc) {
15159 const DeclSpec &DS = D.getDeclSpec();
15160
15161 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15162
15163 // C++03 [dcl.stc]p2 also permits 'auto'.
15164 StorageClass SC = SC_None;
15165 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15166 SC = SC_Register;
15167 // In C++11, the 'register' storage class specifier is deprecated.
15168 // In C++17, it is not allowed, but we tolerate it as an extension.
15169 if (getLangOpts().CPlusPlus11) {
15170 Diag(DS.getStorageClassSpecLoc(),
15171 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
15172 : diag::warn_deprecated_register)
15173 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
15174 }
15175 } else if (getLangOpts().CPlusPlus &&
15176 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
15177 SC = SC_Auto;
15178 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15179 Diag(DS.getStorageClassSpecLoc(),
15180 diag::err_invalid_storage_class_in_func_decl);
15181 D.getMutableDeclSpec().ClearStorageClassSpecs();
15182 }
15183
15184 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15185 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15186 << DeclSpec::getSpecifierName(TSCS);
15187 if (DS.isInlineSpecified())
15188 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15189 << getLangOpts().CPlusPlus17;
15190 if (DS.hasConstexprSpecifier())
15191 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15192 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15193
15194 DiagnoseFunctionSpecifiers(DS);
15195
15196 CheckFunctionOrTemplateParamDeclarator(S, D);
15197
15198 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
15199 QualType parmDeclType = TInfo->getType();
15200
15201 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15202 const IdentifierInfo *II = D.getIdentifier();
15203 if (II) {
15204 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15205 RedeclarationKind::ForVisibleRedeclaration);
15206 LookupName(R, S);
15207 if (!R.empty()) {
15208 NamedDecl *PrevDecl = *R.begin();
15209 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15210 // Maybe we will complain about the shadowed template parameter.
15211 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15212 // Just pretend that we didn't see the previous declaration.
15213 PrevDecl = nullptr;
15214 }
15215 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15216 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15217 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15218 // Recover by removing the name
15219 II = nullptr;
15220 D.SetIdentifier(Id: nullptr, IdLoc: D.getIdentifierLoc());
15221 D.setInvalidType(true);
15222 }
15223 }
15224 }
15225
15226 // Temporarily put parameter variables in the translation unit, not
15227 // the enclosing context. This prevents them from accidentally
15228 // looking like class members in C++.
15229 ParmVarDecl *New =
15230 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15231 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15232
15233 if (D.isInvalidType())
15234 New->setInvalidDecl();
15235
15236 CheckExplicitObjectParameter(S&: *this, P: New, ExplicitThisLoc);
15237
15238 assert(S->isFunctionPrototypeScope());
15239 assert(S->getFunctionPrototypeDepth() >= 1);
15240 New->setScopeInfo(scopeDepth: S->getFunctionPrototypeDepth() - 1,
15241 parameterIndex: S->getNextFunctionPrototypeIndex());
15242
15243 // Add the parameter declaration into this scope.
15244 S->AddDecl(New);
15245 if (II)
15246 IdResolver.AddDecl(New);
15247
15248 ProcessDeclAttributes(S, New, D);
15249
15250 if (D.getDeclSpec().isModulePrivateSpecified())
15251 Diag(New->getLocation(), diag::err_module_private_local)
15252 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15253 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
15254
15255 if (New->hasAttr<BlocksAttr>()) {
15256 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15257 }
15258
15259 if (getLangOpts().OpenCL)
15260 deduceOpenCLAddressSpace(New);
15261
15262 return New;
15263}
15264
15265/// Synthesizes a variable for a parameter arising from a
15266/// typedef.
15267ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
15268 SourceLocation Loc,
15269 QualType T) {
15270 /* FIXME: setting StartLoc == Loc.
15271 Would it be worth to modify callers so as to provide proper source
15272 location for the unnamed parameters, embedding the parameter's type? */
15273 ParmVarDecl *Param = ParmVarDecl::Create(C&: Context, DC, StartLoc: Loc, IdLoc: Loc, Id: nullptr,
15274 T, TInfo: Context.getTrivialTypeSourceInfo(T, Loc),
15275 S: SC_None, DefArg: nullptr);
15276 Param->setImplicit();
15277 return Param;
15278}
15279
15280void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
15281 // Don't diagnose unused-parameter errors in template instantiations; we
15282 // will already have done so in the template itself.
15283 if (inTemplateInstantiation())
15284 return;
15285
15286 for (const ParmVarDecl *Parameter : Parameters) {
15287 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15288 !Parameter->hasAttr<UnusedAttr>() &&
15289 !Parameter->getIdentifier()->isPlaceholder()) {
15290 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15291 << Parameter->getDeclName();
15292 }
15293 }
15294}
15295
15296void Sema::DiagnoseSizeOfParametersAndReturnValue(
15297 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15298 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15299 return;
15300
15301 // Warn if the return value is pass-by-value and larger than the specified
15302 // threshold.
15303 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15304 unsigned Size = Context.getTypeSizeInChars(T: ReturnTy).getQuantity();
15305 if (Size > LangOpts.NumLargeByValueCopy)
15306 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15307 }
15308
15309 // Warn if any parameter is pass-by-value and larger than the specified
15310 // threshold.
15311 for (const ParmVarDecl *Parameter : Parameters) {
15312 QualType T = Parameter->getType();
15313 if (T->isDependentType() || !T.isPODType(Context))
15314 continue;
15315 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15316 if (Size > LangOpts.NumLargeByValueCopy)
15317 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15318 << Parameter << Size;
15319 }
15320}
15321
15322QualType Sema::AdjustParameterTypeForObjCAutoRefCount(QualType T,
15323 SourceLocation NameLoc,
15324 TypeSourceInfo *TSInfo) {
15325 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15326 if (!getLangOpts().ObjCAutoRefCount ||
15327 T.getObjCLifetime() != Qualifiers::OCL_None || !T->isObjCLifetimeType())
15328 return T;
15329
15330 Qualifiers::ObjCLifetime Lifetime;
15331
15332 // Special cases for arrays:
15333 // - if it's const, use __unsafe_unretained
15334 // - otherwise, it's an error
15335 if (T->isArrayType()) {
15336 if (!T.isConstQualified()) {
15337 if (DelayedDiagnostics.shouldDelayDiagnostics())
15338 DelayedDiagnostics.add(sema::DelayedDiagnostic::makeForbiddenType(
15339 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15340 else
15341 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15342 << TSInfo->getTypeLoc().getSourceRange();
15343 }
15344 Lifetime = Qualifiers::OCL_ExplicitNone;
15345 } else {
15346 Lifetime = T->getObjCARCImplicitLifetime();
15347 }
15348 T = Context.getLifetimeQualifiedType(type: T, lifetime: Lifetime);
15349
15350 return T;
15351}
15352
15353ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
15354 SourceLocation NameLoc,
15355 const IdentifierInfo *Name, QualType T,
15356 TypeSourceInfo *TSInfo, StorageClass SC) {
15357 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15358 if (getLangOpts().ObjCAutoRefCount &&
15359 T.getObjCLifetime() == Qualifiers::OCL_None &&
15360 T->isObjCLifetimeType()) {
15361
15362 Qualifiers::ObjCLifetime lifetime;
15363
15364 // Special cases for arrays:
15365 // - if it's const, use __unsafe_unretained
15366 // - otherwise, it's an error
15367 if (T->isArrayType()) {
15368 if (!T.isConstQualified()) {
15369 if (DelayedDiagnostics.shouldDelayDiagnostics())
15370 DelayedDiagnostics.add(
15371 sema::DelayedDiagnostic::makeForbiddenType(
15372 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15373 else
15374 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15375 << TSInfo->getTypeLoc().getSourceRange();
15376 }
15377 lifetime = Qualifiers::OCL_ExplicitNone;
15378 } else {
15379 lifetime = T->getObjCARCImplicitLifetime();
15380 }
15381 T = Context.getLifetimeQualifiedType(type: T, lifetime);
15382 }
15383
15384 ParmVarDecl *New = ParmVarDecl::Create(C&: Context, DC, StartLoc, IdLoc: NameLoc, Id: Name,
15385 T: Context.getAdjustedParameterType(T),
15386 TInfo: TSInfo, S: SC, DefArg: nullptr);
15387
15388 // Make a note if we created a new pack in the scope of a lambda, so that
15389 // we know that references to that pack must also be expanded within the
15390 // lambda scope.
15391 if (New->isParameterPack())
15392 if (auto *LSI = getEnclosingLambda())
15393 LSI->LocalPacks.push_back(New);
15394
15395 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15396 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15397 checkNonTrivialCUnion(QT: New->getType(), Loc: New->getLocation(),
15398 UseContext: NTCUC_FunctionParam, NonTrivialKind: NTCUK_Destruct|NTCUK_Copy);
15399
15400 // Parameter declarators cannot be interface types. All ObjC objects are
15401 // passed by reference.
15402 if (T->isObjCObjectType()) {
15403 SourceLocation TypeEndLoc =
15404 getLocForEndOfToken(Loc: TSInfo->getTypeLoc().getEndLoc());
15405 Diag(NameLoc,
15406 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15407 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15408 T = Context.getObjCObjectPointerType(OIT: T);
15409 New->setType(T);
15410 }
15411
15412 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15413 // duration shall not be qualified by an address-space qualifier."
15414 // Since all parameters have automatic store duration, they can not have
15415 // an address space.
15416 if (T.getAddressSpace() != LangAS::Default &&
15417 // OpenCL allows function arguments declared to be an array of a type
15418 // to be qualified with an address space.
15419 !(getLangOpts().OpenCL &&
15420 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15421 // WebAssembly allows reference types as parameters. Funcref in particular
15422 // lives in a different address space.
15423 !(T->isFunctionPointerType() &&
15424 T.getAddressSpace() == LangAS::wasm_funcref)) {
15425 Diag(NameLoc, diag::err_arg_with_address_space);
15426 New->setInvalidDecl();
15427 }
15428
15429 // PPC MMA non-pointer types are not allowed as function argument types.
15430 if (Context.getTargetInfo().getTriple().isPPC64() &&
15431 CheckPPCMMAType(Type: New->getOriginalType(), TypeLoc: New->getLocation())) {
15432 New->setInvalidDecl();
15433 }
15434
15435 return New;
15436}
15437
15438void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
15439 SourceLocation LocAfterDecls) {
15440 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15441
15442 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15443 // in the declaration list shall have at least one declarator, those
15444 // declarators shall only declare identifiers from the identifier list, and
15445 // every identifier in the identifier list shall be declared.
15446 //
15447 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15448 // identifiers it names shall be declared in the declaration list."
15449 //
15450 // This is why we only diagnose in C99 and later. Note, the other conditions
15451 // listed are checked elsewhere.
15452 if (!FTI.hasPrototype) {
15453 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15454 --i;
15455 if (FTI.Params[i].Param == nullptr) {
15456 if (getLangOpts().C99) {
15457 SmallString<256> Code;
15458 llvm::raw_svector_ostream(Code)
15459 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15460 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15461 << FTI.Params[i].Ident
15462 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15463 }
15464
15465 // Implicitly declare the argument as type 'int' for lack of a better
15466 // type.
15467 AttributeFactory attrs;
15468 DeclSpec DS(attrs);
15469 const char* PrevSpec; // unused
15470 unsigned DiagID; // unused
15471 DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc: FTI.Params[i].IdentLoc, PrevSpec,
15472 DiagID, Policy: Context.getPrintingPolicy());
15473 // Use the identifier location for the type source range.
15474 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15475 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15476 Declarator ParamD(DS, ParsedAttributesView::none(),
15477 DeclaratorContext::KNRTypeList);
15478 ParamD.SetIdentifier(Id: FTI.Params[i].Ident, IdLoc: FTI.Params[i].IdentLoc);
15479 FTI.Params[i].Param = ActOnParamDeclarator(S, D&: ParamD);
15480 }
15481 }
15482 }
15483}
15484
15485Decl *
15486Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
15487 MultiTemplateParamsArg TemplateParameterLists,
15488 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15489 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15490 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15491 Scope *ParentScope = FnBodyScope->getParent();
15492
15493 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15494 // we define a non-templated function definition, we will create a declaration
15495 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15496 // The base function declaration will have the equivalent of an `omp declare
15497 // variant` annotation which specifies the mangled definition as a
15498 // specialization function under the OpenMP context defined as part of the
15499 // `omp begin declare variant`.
15500 SmallVector<FunctionDecl *, 4> Bases;
15501 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15502 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15503 S: ParentScope, D, TemplateParameterLists, Bases);
15504
15505 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15506 Decl *DP = HandleDeclarator(S: ParentScope, D, TemplateParamLists: TemplateParameterLists);
15507 Decl *Dcl = ActOnStartOfFunctionDef(S: FnBodyScope, D: DP, SkipBody, BodyKind);
15508
15509 if (!Bases.empty())
15510 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
15511 Bases);
15512
15513 return Dcl;
15514}
15515
15516void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
15517 Consumer.HandleInlineFunctionDefinition(D);
15518}
15519
15520static bool FindPossiblePrototype(const FunctionDecl *FD,
15521 const FunctionDecl *&PossiblePrototype) {
15522 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15523 Prev = Prev->getPreviousDecl()) {
15524 // Ignore any declarations that occur in function or method
15525 // scope, because they aren't visible from the header.
15526 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15527 continue;
15528
15529 PossiblePrototype = Prev;
15530 return Prev->getType()->isFunctionProtoType();
15531 }
15532 return false;
15533}
15534
15535static bool
15536ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
15537 const FunctionDecl *&PossiblePrototype) {
15538 // Don't warn about invalid declarations.
15539 if (FD->isInvalidDecl())
15540 return false;
15541
15542 // Or declarations that aren't global.
15543 if (!FD->isGlobal())
15544 return false;
15545
15546 // Don't warn about C++ member functions.
15547 if (isa<CXXMethodDecl>(Val: FD))
15548 return false;
15549
15550 // Don't warn about 'main'.
15551 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15552 if (IdentifierInfo *II = FD->getIdentifier())
15553 if (II->isStr(Str: "main") || II->isStr(Str: "efi_main"))
15554 return false;
15555
15556 // Don't warn about inline functions.
15557 if (FD->isInlined())
15558 return false;
15559
15560 // Don't warn about function templates.
15561 if (FD->getDescribedFunctionTemplate())
15562 return false;
15563
15564 // Don't warn about function template specializations.
15565 if (FD->isFunctionTemplateSpecialization())
15566 return false;
15567
15568 // Don't warn for OpenCL kernels.
15569 if (FD->hasAttr<OpenCLKernelAttr>())
15570 return false;
15571
15572 // Don't warn on explicitly deleted functions.
15573 if (FD->isDeleted())
15574 return false;
15575
15576 // Don't warn on implicitly local functions (such as having local-typed
15577 // parameters).
15578 if (!FD->isExternallyVisible())
15579 return false;
15580
15581 // If we were able to find a potential prototype, don't warn.
15582 if (FindPossiblePrototype(FD, PossiblePrototype))
15583 return false;
15584
15585 return true;
15586}
15587
15588void
15589Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
15590 const FunctionDecl *EffectiveDefinition,
15591 SkipBodyInfo *SkipBody) {
15592 const FunctionDecl *Definition = EffectiveDefinition;
15593 if (!Definition &&
15594 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15595 return;
15596
15597 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15598 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15599 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15600 // A merged copy of the same function, instantiated as a member of
15601 // the same class, is OK.
15602 if (declaresSameEntity(OrigFD, OrigDef) &&
15603 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15604 cast<Decl>(FD->getLexicalDeclContext())))
15605 return;
15606 }
15607 }
15608 }
15609
15610 if (canRedefineFunction(FD: Definition, LangOpts: getLangOpts()))
15611 return;
15612
15613 // Don't emit an error when this is redefinition of a typo-corrected
15614 // definition.
15615 if (TypoCorrectedFunctionDefinitions.count(Definition))
15616 return;
15617
15618 // If we don't have a visible definition of the function, and it's inline or
15619 // a template, skip the new definition.
15620 if (SkipBody && !hasVisibleDefinition(Definition) &&
15621 (Definition->getFormalLinkage() == Linkage::Internal ||
15622 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15623 Definition->getNumTemplateParameterLists())) {
15624 SkipBody->ShouldSkip = true;
15625 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15626 if (auto *TD = Definition->getDescribedFunctionTemplate())
15627 makeMergedDefinitionVisible(TD);
15628 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
15629 return;
15630 }
15631
15632 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15633 Definition->getStorageClass() == SC_Extern)
15634 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15635 << FD << getLangOpts().CPlusPlus;
15636 else
15637 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15638
15639 Diag(Definition->getLocation(), diag::note_previous_definition);
15640 FD->setInvalidDecl();
15641}
15642
15643LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
15644 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15645
15646 LambdaScopeInfo *LSI = PushLambdaScope();
15647 LSI->CallOperator = CallOperator;
15648 LSI->Lambda = LambdaClass;
15649 LSI->ReturnType = CallOperator->getReturnType();
15650 // This function in calls in situation where the context of the call operator
15651 // is not entered, so we set AfterParameterList to false, so that
15652 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15653 LSI->AfterParameterList = false;
15654 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15655
15656 if (LCD == LCD_None)
15657 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
15658 else if (LCD == LCD_ByCopy)
15659 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
15660 else if (LCD == LCD_ByRef)
15661 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
15662 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15663
15664 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
15665 LSI->Mutable = !CallOperator->isConst();
15666 if (CallOperator->isExplicitObjectMemberFunction())
15667 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15668
15669 // Add the captures to the LSI so they can be noted as already
15670 // captured within tryCaptureVar.
15671 auto I = LambdaClass->field_begin();
15672 for (const auto &C : LambdaClass->captures()) {
15673 if (C.capturesVariable()) {
15674 ValueDecl *VD = C.getCapturedVar();
15675 if (VD->isInitCapture())
15676 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
15677 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15678 LSI->addCapture(Var: VD, /*IsBlock*/isBlock: false, isByref: ByRef,
15679 /*RefersToEnclosingVariableOrCapture*/isNested: true, Loc: C.getLocation(),
15680 /*EllipsisLoc*/C.isPackExpansion()
15681 ? C.getEllipsisLoc() : SourceLocation(),
15682 CaptureType: I->getType(), /*Invalid*/false);
15683
15684 } else if (C.capturesThis()) {
15685 LSI->addThisCapture(/*Nested*/ isNested: false, Loc: C.getLocation(), CaptureType: I->getType(),
15686 ByCopy: C.getCaptureKind() == LCK_StarThis);
15687 } else {
15688 LSI->addVLATypeCapture(Loc: C.getLocation(), VLAType: I->getCapturedVLAType(),
15689 CaptureType: I->getType());
15690 }
15691 ++I;
15692 }
15693 return LSI;
15694}
15695
15696Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
15697 SkipBodyInfo *SkipBody,
15698 FnBodyKind BodyKind) {
15699 if (!D) {
15700 // Parsing the function declaration failed in some way. Push on a fake scope
15701 // anyway so we can try to parse the function body.
15702 PushFunctionScope();
15703 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
15704 return D;
15705 }
15706
15707 FunctionDecl *FD = nullptr;
15708
15709 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D))
15710 FD = FunTmpl->getTemplatedDecl();
15711 else
15712 FD = cast<FunctionDecl>(Val: D);
15713
15714 // Do not push if it is a lambda because one is already pushed when building
15715 // the lambda in ActOnStartOfLambdaDefinition().
15716 if (!isLambdaCallOperator(FD))
15717 // [expr.const]/p14.1
15718 // An expression or conversion is in an immediate function context if it is
15719 // potentially evaluated and either: its innermost enclosing non-block scope
15720 // is a function parameter scope of an immediate function.
15721 PushExpressionEvaluationContext(
15722 NewContext: FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
15723 : ExprEvalContexts.back().Context);
15724
15725 // Each ExpressionEvaluationContextRecord also keeps track of whether the
15726 // context is nested in an immediate function context, so smaller contexts
15727 // that appear inside immediate functions (like variable initializers) are
15728 // considered to be inside an immediate function context even though by
15729 // themselves they are not immediate function contexts. But when a new
15730 // function is entered, we need to reset this tracking, since the entered
15731 // function might be not an immediate function.
15732 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15733 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15734 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15735
15736 // Check for defining attributes before the check for redefinition.
15737 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15738 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15739 FD->dropAttr<AliasAttr>();
15740 FD->setInvalidDecl();
15741 }
15742 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15743 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15744 FD->dropAttr<IFuncAttr>();
15745 FD->setInvalidDecl();
15746 }
15747 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15748 if (!Context.getTargetInfo().hasFeature(Feature: "fmv") &&
15749 !Attr->isDefaultVersion()) {
15750 // If function multi versioning disabled skip parsing function body
15751 // defined with non-default target_version attribute
15752 if (SkipBody)
15753 SkipBody->ShouldSkip = true;
15754 return nullptr;
15755 }
15756 }
15757
15758 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
15759 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15760 Ctor->isDefaultConstructor() &&
15761 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15762 // If this is an MS ABI dllexport default constructor, instantiate any
15763 // default arguments.
15764 InstantiateDefaultCtorDefaultArgs(Ctor);
15765 }
15766 }
15767
15768 // See if this is a redefinition. If 'will have body' (or similar) is already
15769 // set, then these checks were already performed when it was set.
15770 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15771 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
15772 CheckForFunctionRedefinition(FD, EffectiveDefinition: nullptr, SkipBody);
15773
15774 // If we're skipping the body, we're done. Don't enter the scope.
15775 if (SkipBody && SkipBody->ShouldSkip)
15776 return D;
15777 }
15778
15779 // Mark this function as "will have a body eventually". This lets users to
15780 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15781 // this function.
15782 FD->setWillHaveBody();
15783
15784 // If we are instantiating a generic lambda call operator, push
15785 // a LambdaScopeInfo onto the function stack. But use the information
15786 // that's already been calculated (ActOnLambdaExpr) to prime the current
15787 // LambdaScopeInfo.
15788 // When the template operator is being specialized, the LambdaScopeInfo,
15789 // has to be properly restored so that tryCaptureVariable doesn't try
15790 // and capture any new variables. In addition when calculating potential
15791 // captures during transformation of nested lambdas, it is necessary to
15792 // have the LSI properly restored.
15793 if (isGenericLambdaCallOperatorSpecialization(FD)) {
15794 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
15795 // instantiated, explicitly specialized.
15796 if (FD->getTemplateSpecializationInfo()
15797 ->isExplicitInstantiationOrSpecialization()) {
15798 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
15799 FD->setInvalidDecl();
15800 PushFunctionScope();
15801 } else {
15802 assert(inTemplateInstantiation() &&
15803 "There should be an active template instantiation on the stack "
15804 "when instantiating a generic lambda!");
15805 RebuildLambdaScopeInfo(CallOperator: cast<CXXMethodDecl>(Val: D));
15806 }
15807 } else {
15808 // Enter a new function scope
15809 PushFunctionScope();
15810 }
15811
15812 // Builtin functions cannot be defined.
15813 if (unsigned BuiltinID = FD->getBuiltinID()) {
15814 if (!Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID) &&
15815 !Context.BuiltinInfo.isPredefinedRuntimeFunction(ID: BuiltinID)) {
15816 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15817 FD->setInvalidDecl();
15818 }
15819 }
15820
15821 // The return type of a function definition must be complete (C99 6.9.1p3).
15822 // C++23 [dcl.fct.def.general]/p2
15823 // The type of [...] the return for a function definition
15824 // shall not be a (possibly cv-qualified) class type that is incomplete
15825 // or abstract within the function body unless the function is deleted.
15826 QualType ResultType = FD->getReturnType();
15827 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15828 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15829 (RequireCompleteType(FD->getLocation(), ResultType,
15830 diag::err_func_def_incomplete_result) ||
15831 RequireNonAbstractType(FD->getLocation(), FD->getReturnType(),
15832 diag::err_abstract_type_in_decl,
15833 AbstractReturnType)))
15834 FD->setInvalidDecl();
15835
15836 if (FnBodyScope)
15837 PushDeclContext(FnBodyScope, FD);
15838
15839 // Check the validity of our function parameters
15840 if (BodyKind != FnBodyKind::Delete)
15841 CheckParmsForFunctionDef(Parameters: FD->parameters(),
15842 /*CheckParameterNames=*/true);
15843
15844 // Add non-parameter declarations already in the function to the current
15845 // scope.
15846 if (FnBodyScope) {
15847 for (Decl *NPD : FD->decls()) {
15848 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15849 if (!NonParmDecl)
15850 continue;
15851 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15852 "parameters should not be in newly created FD yet");
15853
15854 // If the decl has a name, make it accessible in the current scope.
15855 if (NonParmDecl->getDeclName())
15856 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15857
15858 // Similarly, dive into enums and fish their constants out, making them
15859 // accessible in this scope.
15860 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15861 for (auto *EI : ED->enumerators())
15862 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15863 }
15864 }
15865 }
15866
15867 // Introduce our parameters into the function scope
15868 for (auto *Param : FD->parameters()) {
15869 Param->setOwningFunction(FD);
15870
15871 // If this has an identifier, add it to the scope stack.
15872 if (Param->getIdentifier() && FnBodyScope) {
15873 CheckShadow(FnBodyScope, Param);
15874
15875 PushOnScopeChains(Param, FnBodyScope);
15876 }
15877 }
15878
15879 // C++ [module.import/6] external definitions are not permitted in header
15880 // units. Deleted and Defaulted functions are implicitly inline (but the
15881 // inline state is not set at this point, so check the BodyKind explicitly).
15882 // FIXME: Consider an alternate location for the test where the inlined()
15883 // state is complete.
15884 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15885 !FD->isInvalidDecl() && !FD->isInlined() &&
15886 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15887 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
15888 !FD->isTemplateInstantiation()) {
15889 assert(FD->isThisDeclarationADefinition());
15890 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15891 FD->setInvalidDecl();
15892 }
15893
15894 // Ensure that the function's exception specification is instantiated.
15895 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15896 ResolveExceptionSpec(Loc: D->getLocation(), FPT);
15897
15898 // dllimport cannot be applied to non-inline function definitions.
15899 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15900 !FD->isTemplateInstantiation()) {
15901 assert(!FD->hasAttr<DLLExportAttr>());
15902 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15903 FD->setInvalidDecl();
15904 return D;
15905 }
15906
15907 // Some function attributes (like OptimizeNoneAttr) need actions before
15908 // parsing body started.
15909 applyFunctionAttributesBeforeParsingBody(FD: D);
15910
15911 // We want to attach documentation to original Decl (which might be
15912 // a function template).
15913 ActOnDocumentableDecl(D);
15914 if (getCurLexicalContext()->isObjCContainer() &&
15915 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15916 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15917 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15918
15919 return D;
15920}
15921
15922void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {
15923 if (!FD || FD->isInvalidDecl())
15924 return;
15925 if (auto *TD = dyn_cast<FunctionTemplateDecl>(Val: FD))
15926 FD = TD->getTemplatedDecl();
15927 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
15928 FPOptionsOverride FPO;
15929 FPO.setDisallowOptimizations();
15930 CurFPFeatures.applyChanges(FPO);
15931 FpPragmaStack.CurrentValue =
15932 CurFPFeatures.getChangesFrom(Base: FPOptions(LangOpts));
15933 }
15934}
15935
15936/// Given the set of return statements within a function body,
15937/// compute the variables that are subject to the named return value
15938/// optimization.
15939///
15940/// Each of the variables that is subject to the named return value
15941/// optimization will be marked as NRVO variables in the AST, and any
15942/// return statement that has a marked NRVO variable as its NRVO candidate can
15943/// use the named return value optimization.
15944///
15945/// This function applies a very simplistic algorithm for NRVO: if every return
15946/// statement in the scope of a variable has the same NRVO candidate, that
15947/// candidate is an NRVO variable.
15948void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
15949 ReturnStmt **Returns = Scope->Returns.data();
15950
15951 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15952 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15953 if (!NRVOCandidate->isNRVOVariable())
15954 Returns[I]->setNRVOCandidate(nullptr);
15955 }
15956 }
15957}
15958
15959bool Sema::canDelayFunctionBody(const Declarator &D) {
15960 // We can't delay parsing the body of a constexpr function template (yet).
15961 if (D.getDeclSpec().hasConstexprSpecifier())
15962 return false;
15963
15964 // We can't delay parsing the body of a function template with a deduced
15965 // return type (yet).
15966 if (D.getDeclSpec().hasAutoTypeSpec()) {
15967 // If the placeholder introduces a non-deduced trailing return type,
15968 // we can still delay parsing it.
15969 if (D.getNumTypeObjects()) {
15970 const auto &Outer = D.getTypeObject(i: D.getNumTypeObjects() - 1);
15971 if (Outer.Kind == DeclaratorChunk::Function &&
15972 Outer.Fun.hasTrailingReturnType()) {
15973 QualType Ty = GetTypeFromParser(Ty: Outer.Fun.getTrailingReturnType());
15974 return Ty.isNull() || !Ty->isUndeducedType();
15975 }
15976 }
15977 return false;
15978 }
15979
15980 return true;
15981}
15982
15983bool Sema::canSkipFunctionBody(Decl *D) {
15984 // We cannot skip the body of a function (or function template) which is
15985 // constexpr, since we may need to evaluate its body in order to parse the
15986 // rest of the file.
15987 // We cannot skip the body of a function with an undeduced return type,
15988 // because any callers of that function need to know the type.
15989 if (const FunctionDecl *FD = D->getAsFunction()) {
15990 if (FD->isConstexpr())
15991 return false;
15992 // We can't simply call Type::isUndeducedType here, because inside template
15993 // auto can be deduced to a dependent type, which is not considered
15994 // "undeduced".
15995 if (FD->getReturnType()->getContainedDeducedType())
15996 return false;
15997 }
15998 return Consumer.shouldSkipFunctionBody(D);
15999}
16000
16001Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
16002 if (!Decl)
16003 return nullptr;
16004 if (FunctionDecl *FD = Decl->getAsFunction())
16005 FD->setHasSkippedBody();
16006 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: Decl))
16007 MD->setHasSkippedBody();
16008 return Decl;
16009}
16010
16011Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
16012 return ActOnFinishFunctionBody(Decl: D, Body: BodyArg, /*IsInstantiation=*/false);
16013}
16014
16015/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16016/// body.
16017class ExitFunctionBodyRAII {
16018public:
16019 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16020 ~ExitFunctionBodyRAII() {
16021 if (!IsLambda)
16022 S.PopExpressionEvaluationContext();
16023 }
16024
16025private:
16026 Sema &S;
16027 bool IsLambda = false;
16028};
16029
16030static void diagnoseImplicitlyRetainedSelf(Sema &S) {
16031 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16032
16033 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16034 if (EscapeInfo.count(Val: BD))
16035 return EscapeInfo[BD];
16036
16037 bool R = false;
16038 const BlockDecl *CurBD = BD;
16039
16040 do {
16041 R = !CurBD->doesNotEscape();
16042 if (R)
16043 break;
16044 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16045 } while (CurBD);
16046
16047 return EscapeInfo[BD] = R;
16048 };
16049
16050 // If the location where 'self' is implicitly retained is inside a escaping
16051 // block, emit a diagnostic.
16052 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16053 S.ImplicitlyRetainedSelfLocs)
16054 if (IsOrNestedInEscapingBlock(P.second))
16055 S.Diag(P.first, diag::warn_implicitly_retains_self)
16056 << FixItHint::CreateInsertion(P.first, "self->");
16057}
16058
16059static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16060 return isa<CXXMethodDecl>(Val: FD) && FD->param_empty() &&
16061 FD->getDeclName().isIdentifier() && FD->getName().equals(Name);
16062}
16063
16064bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {
16065 return methodHasName(FD, Name: "get_return_object");
16066}
16067
16068bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {
16069 return FD->isStatic() &&
16070 methodHasName(FD, Name: "get_return_object_on_allocation_failure");
16071}
16072
16073void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
16074 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
16075 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16076 return;
16077 // Allow some_promise_type::get_return_object().
16078 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
16079 return;
16080 if (!FD->hasAttr<CoroWrapperAttr>())
16081 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16082}
16083
16084Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
16085 bool IsInstantiation) {
16086 FunctionScopeInfo *FSI = getCurFunction();
16087 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16088
16089 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16090 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16091
16092 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
16093 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16094
16095 // If we skip function body, we can't tell if a function is a coroutine.
16096 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16097 if (FSI->isCoroutine())
16098 CheckCompletedCoroutineBody(FD, Body);
16099 else
16100 CheckCoroutineWrapper(FD);
16101 }
16102
16103 {
16104 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16105 // one is already popped when finishing the lambda in BuildLambdaExpr().
16106 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16107 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16108 if (FD) {
16109 // If this is called by Parser::ParseFunctionDefinition() after marking
16110 // the declaration as deleted, and if the deleted-function-body contains
16111 // a message (C++26), then a DefaultedOrDeletedInfo will have already been
16112 // added to store that message; do not overwrite it in that case.
16113 //
16114 // Since this would always set the body to 'nullptr' in that case anyway,
16115 // which is already done when the function decl is initially created,
16116 // always skipping this irrespective of whether there is a delete message
16117 // should not be a problem.
16118 if (!FD->isDeletedAsWritten())
16119 FD->setBody(Body);
16120 FD->setWillHaveBody(false);
16121 CheckImmediateEscalatingFunctionDefinition(FD, FSI);
16122
16123 if (getLangOpts().CPlusPlus14) {
16124 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16125 FD->getReturnType()->isUndeducedType()) {
16126 // For a function with a deduced result type to return void,
16127 // the result type as written must be 'auto' or 'decltype(auto)',
16128 // possibly cv-qualified or constrained, but not ref-qualified.
16129 if (!FD->getReturnType()->getAs<AutoType>()) {
16130 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16131 << FD->getReturnType();
16132 FD->setInvalidDecl();
16133 } else {
16134 // Falling off the end of the function is the same as 'return;'.
16135 Expr *Dummy = nullptr;
16136 if (DeduceFunctionTypeFromReturnExpr(
16137 FD, ReturnLoc: dcl->getLocation(), RetExpr: Dummy,
16138 AT: FD->getReturnType()->getAs<AutoType>()))
16139 FD->setInvalidDecl();
16140 }
16141 }
16142 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16143 // In C++11, we don't use 'auto' deduction rules for lambda call
16144 // operators because we don't support return type deduction.
16145 auto *LSI = getCurLambda();
16146 if (LSI->HasImplicitReturnType) {
16147 deduceClosureReturnType(*LSI);
16148
16149 // C++11 [expr.prim.lambda]p4:
16150 // [...] if there are no return statements in the compound-statement
16151 // [the deduced type is] the type void
16152 QualType RetType =
16153 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16154
16155 // Update the return type to the deduced type.
16156 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16157 FD->setType(Context.getFunctionType(ResultTy: RetType, Args: Proto->getParamTypes(),
16158 EPI: Proto->getExtProtoInfo()));
16159 }
16160 }
16161
16162 // If the function implicitly returns zero (like 'main') or is naked,
16163 // don't complain about missing return statements.
16164 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
16165 WP.disableCheckFallThrough();
16166
16167 // MSVC permits the use of pure specifier (=0) on function definition,
16168 // defined at class scope, warn about this non-standard construct.
16169 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16170 !FD->isOutOfLine())
16171 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16172
16173 if (!FD->isInvalidDecl()) {
16174 // Don't diagnose unused parameters of defaulted, deleted or naked
16175 // functions.
16176 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16177 !FD->hasAttr<NakedAttr>())
16178 DiagnoseUnusedParameters(Parameters: FD->parameters());
16179 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
16180 FD->getReturnType(), FD);
16181
16182 // If this is a structor, we need a vtable.
16183 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: FD))
16184 MarkVTableUsed(Loc: FD->getLocation(), Class: Constructor->getParent());
16185 else if (CXXDestructorDecl *Destructor =
16186 dyn_cast<CXXDestructorDecl>(Val: FD))
16187 MarkVTableUsed(Loc: FD->getLocation(), Class: Destructor->getParent());
16188
16189 // Try to apply the named return value optimization. We have to check
16190 // if we can do this here because lambdas keep return statements around
16191 // to deduce an implicit return type.
16192 if (FD->getReturnType()->isRecordType() &&
16193 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
16194 computeNRVO(Body, Scope: FSI);
16195 }
16196
16197 // GNU warning -Wmissing-prototypes:
16198 // Warn if a global function is defined without a previous
16199 // prototype declaration. This warning is issued even if the
16200 // definition itself provides a prototype. The aim is to detect
16201 // global functions that fail to be declared in header files.
16202 const FunctionDecl *PossiblePrototype = nullptr;
16203 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16204 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16205
16206 if (PossiblePrototype) {
16207 // We found a declaration that is not a prototype,
16208 // but that could be a zero-parameter prototype
16209 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16210 TypeLoc TL = TI->getTypeLoc();
16211 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
16212 Diag(PossiblePrototype->getLocation(),
16213 diag::note_declaration_not_a_prototype)
16214 << (FD->getNumParams() != 0)
16215 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
16216 FTL.getRParenLoc(), "void")
16217 : FixItHint{});
16218 }
16219 } else {
16220 // Returns true if the token beginning at this Loc is `const`.
16221 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16222 const LangOptions &LangOpts) {
16223 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
16224 if (LocInfo.first.isInvalid())
16225 return false;
16226
16227 bool Invalid = false;
16228 StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid);
16229 if (Invalid)
16230 return false;
16231
16232 if (LocInfo.second > Buffer.size())
16233 return false;
16234
16235 const char *LexStart = Buffer.data() + LocInfo.second;
16236 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16237
16238 return StartTok.consume_front(Prefix: "const") &&
16239 (StartTok.empty() || isWhitespace(c: StartTok[0]) ||
16240 StartTok.starts_with(Prefix: "/*") || StartTok.starts_with(Prefix: "//"));
16241 };
16242
16243 auto findBeginLoc = [&]() {
16244 // If the return type has `const` qualifier, we want to insert
16245 // `static` before `const` (and not before the typename).
16246 if ((FD->getReturnType()->isAnyPointerType() &&
16247 FD->getReturnType()->getPointeeType().isConstQualified()) ||
16248 FD->getReturnType().isConstQualified()) {
16249 // But only do this if we can determine where the `const` is.
16250
16251 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16252 getLangOpts()))
16253
16254 return FD->getBeginLoc();
16255 }
16256 return FD->getTypeSpecStartLoc();
16257 };
16258 Diag(FD->getTypeSpecStartLoc(),
16259 diag::note_static_for_internal_linkage)
16260 << /* function */ 1
16261 << (FD->getStorageClass() == SC_None
16262 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16263 : FixItHint{});
16264 }
16265 }
16266
16267 // We might not have found a prototype because we didn't wish to warn on
16268 // the lack of a missing prototype. Try again without the checks for
16269 // whether we want to warn on the missing prototype.
16270 if (!PossiblePrototype)
16271 (void)FindPossiblePrototype(FD, PossiblePrototype);
16272
16273 // If the function being defined does not have a prototype, then we may
16274 // need to diagnose it as changing behavior in C23 because we now know
16275 // whether the function accepts arguments or not. This only handles the
16276 // case where the definition has no prototype but does have parameters
16277 // and either there is no previous potential prototype, or the previous
16278 // potential prototype also has no actual prototype. This handles cases
16279 // like:
16280 // void f(); void f(a) int a; {}
16281 // void g(a) int a; {}
16282 // See MergeFunctionDecl() for other cases of the behavior change
16283 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16284 // type without a prototype.
16285 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16286 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16287 !PossiblePrototype->isImplicit()))) {
16288 // The function definition has parameters, so this will change behavior
16289 // in C23. If there is a possible prototype, it comes before the
16290 // function definition.
16291 // FIXME: The declaration may have already been diagnosed as being
16292 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16293 // there's no way to test for the "changes behavior" condition in
16294 // SemaType.cpp when forming the declaration's function type. So, we do
16295 // this awkward dance instead.
16296 //
16297 // If we have a possible prototype and it declares a function with a
16298 // prototype, we don't want to diagnose it; if we have a possible
16299 // prototype and it has no prototype, it may have already been
16300 // diagnosed in SemaType.cpp as deprecated depending on whether
16301 // -Wstrict-prototypes is enabled. If we already warned about it being
16302 // deprecated, add a note that it also changes behavior. If we didn't
16303 // warn about it being deprecated (because the diagnostic is not
16304 // enabled), warn now that it is deprecated and changes behavior.
16305
16306 // This K&R C function definition definitely changes behavior in C23,
16307 // so diagnose it.
16308 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16309 << /*definition*/ 1 << /* not supported in C23 */ 0;
16310
16311 // If we have a possible prototype for the function which is a user-
16312 // visible declaration, we already tested that it has no prototype.
16313 // This will change behavior in C23. This gets a warning rather than a
16314 // note because it's the same behavior-changing problem as with the
16315 // definition.
16316 if (PossiblePrototype)
16317 Diag(PossiblePrototype->getLocation(),
16318 diag::warn_non_prototype_changes_behavior)
16319 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16320 << /*definition*/ 1;
16321 }
16322
16323 // Warn on CPUDispatch with an actual body.
16324 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16325 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16326 if (!CmpndBody->body_empty())
16327 Diag(CmpndBody->body_front()->getBeginLoc(),
16328 diag::warn_dispatch_body_ignored);
16329
16330 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
16331 const CXXMethodDecl *KeyFunction;
16332 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16333 MD->isVirtual() &&
16334 (KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent())) &&
16335 MD == KeyFunction->getCanonicalDecl()) {
16336 // Update the key-function state if necessary for this ABI.
16337 if (FD->isInlined() &&
16338 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16339 Context.setNonKeyFunction(MD);
16340
16341 // If the newly-chosen key function is already defined, then we
16342 // need to mark the vtable as used retroactively.
16343 KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent());
16344 const FunctionDecl *Definition;
16345 if (KeyFunction && KeyFunction->isDefined(Definition))
16346 MarkVTableUsed(Loc: Definition->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16347 } else {
16348 // We just defined they key function; mark the vtable as used.
16349 MarkVTableUsed(Loc: FD->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16350 }
16351 }
16352 }
16353
16354 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16355 "Function parsing confused");
16356 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Val: dcl)) {
16357 assert(MD == getCurMethodDecl() && "Method parsing confused");
16358 MD->setBody(Body);
16359 if (!MD->isInvalidDecl()) {
16360 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
16361 MD->getReturnType(), MD);
16362
16363 if (Body)
16364 computeNRVO(Body, Scope: FSI);
16365 }
16366 if (FSI->ObjCShouldCallSuper) {
16367 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16368 << MD->getSelector().getAsString();
16369 FSI->ObjCShouldCallSuper = false;
16370 }
16371 if (FSI->ObjCWarnForNoDesignatedInitChain) {
16372 const ObjCMethodDecl *InitMethod = nullptr;
16373 bool isDesignated =
16374 MD->isDesignatedInitializerForTheInterface(InitMethod: &InitMethod);
16375 assert(isDesignated && InitMethod);
16376 (void)isDesignated;
16377
16378 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16379 auto IFace = MD->getClassInterface();
16380 if (!IFace)
16381 return false;
16382 auto SuperD = IFace->getSuperClass();
16383 if (!SuperD)
16384 return false;
16385 return SuperD->getIdentifier() ==
16386 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16387 };
16388 // Don't issue this warning for unavailable inits or direct subclasses
16389 // of NSObject.
16390 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16391 Diag(MD->getLocation(),
16392 diag::warn_objc_designated_init_missing_super_call);
16393 Diag(InitMethod->getLocation(),
16394 diag::note_objc_designated_init_marked_here);
16395 }
16396 FSI->ObjCWarnForNoDesignatedInitChain = false;
16397 }
16398 if (FSI->ObjCWarnForNoInitDelegation) {
16399 // Don't issue this warning for unavaialable inits.
16400 if (!MD->isUnavailable())
16401 Diag(MD->getLocation(),
16402 diag::warn_objc_secondary_init_missing_init_call);
16403 FSI->ObjCWarnForNoInitDelegation = false;
16404 }
16405
16406 diagnoseImplicitlyRetainedSelf(S&: *this);
16407 } else {
16408 // Parsing the function declaration failed in some way. Pop the fake scope
16409 // we pushed on.
16410 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
16411 return nullptr;
16412 }
16413
16414 if (Body && FSI->HasPotentialAvailabilityViolations)
16415 DiagnoseUnguardedAvailabilityViolations(FD: dcl);
16416
16417 assert(!FSI->ObjCShouldCallSuper &&
16418 "This should only be set for ObjC methods, which should have been "
16419 "handled in the block above.");
16420
16421 // Verify and clean out per-function state.
16422 if (Body && (!FD || !FD->isDefaulted())) {
16423 // C++ constructors that have function-try-blocks can't have return
16424 // statements in the handlers of that block. (C++ [except.handle]p14)
16425 // Verify this.
16426 if (FD && isa<CXXConstructorDecl>(Val: FD) && isa<CXXTryStmt>(Val: Body))
16427 DiagnoseReturnInConstructorExceptionHandler(TryBlock: cast<CXXTryStmt>(Val: Body));
16428
16429 // Verify that gotos and switch cases don't jump into scopes illegally.
16430 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16431 DiagnoseInvalidJumps(Body);
16432
16433 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: dcl)) {
16434 if (!Destructor->getParent()->isDependentType())
16435 CheckDestructor(Destructor);
16436
16437 MarkBaseAndMemberDestructorsReferenced(Loc: Destructor->getLocation(),
16438 Record: Destructor->getParent());
16439 }
16440
16441 // If any errors have occurred, clear out any temporaries that may have
16442 // been leftover. This ensures that these temporaries won't be picked up
16443 // for deletion in some later function.
16444 if (hasUncompilableErrorOccurred() ||
16445 hasAnyUnrecoverableErrorsInThisFunction() ||
16446 getDiagnostics().getSuppressAllDiagnostics()) {
16447 DiscardCleanupsInEvaluationContext();
16448 }
16449 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(Val: dcl)) {
16450 // Since the body is valid, issue any analysis-based warnings that are
16451 // enabled.
16452 ActivePolicy = &WP;
16453 }
16454
16455 if (!IsInstantiation && FD &&
16456 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16457 !FD->isInvalidDecl() &&
16458 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
16459 FD->setInvalidDecl();
16460
16461 if (FD && FD->hasAttr<NakedAttr>()) {
16462 for (const Stmt *S : Body->children()) {
16463 // Allow local register variables without initializer as they don't
16464 // require prologue.
16465 bool RegisterVariables = false;
16466 if (auto *DS = dyn_cast<DeclStmt>(Val: S)) {
16467 for (const auto *Decl : DS->decls()) {
16468 if (const auto *Var = dyn_cast<VarDecl>(Val: Decl)) {
16469 RegisterVariables =
16470 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16471 if (!RegisterVariables)
16472 break;
16473 }
16474 }
16475 }
16476 if (RegisterVariables)
16477 continue;
16478 if (!isa<AsmStmt>(Val: S) && !isa<NullStmt>(Val: S)) {
16479 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16480 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16481 FD->setInvalidDecl();
16482 break;
16483 }
16484 }
16485 }
16486
16487 assert(ExprCleanupObjects.size() ==
16488 ExprEvalContexts.back().NumCleanupObjects &&
16489 "Leftover temporaries in function");
16490 assert(!Cleanup.exprNeedsCleanups() &&
16491 "Unaccounted cleanups in function");
16492 assert(MaybeODRUseExprs.empty() &&
16493 "Leftover expressions for odr-use checking");
16494 }
16495 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16496 // the declaration context below. Otherwise, we're unable to transform
16497 // 'this' expressions when transforming immediate context functions.
16498
16499 if (!IsInstantiation)
16500 PopDeclContext();
16501
16502 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
16503 // If any errors have occurred, clear out any temporaries that may have
16504 // been leftover. This ensures that these temporaries won't be picked up for
16505 // deletion in some later function.
16506 if (hasUncompilableErrorOccurred()) {
16507 DiscardCleanupsInEvaluationContext();
16508 }
16509
16510 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
16511 !LangOpts.OMPTargetTriples.empty())) ||
16512 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
16513 auto ES = getEmissionStatus(Decl: FD);
16514 if (ES == Sema::FunctionEmissionStatus::Emitted ||
16515 ES == Sema::FunctionEmissionStatus::Unknown)
16516 DeclsToCheckForDeferredDiags.insert(FD);
16517 }
16518
16519 if (FD && !FD->isDeleted())
16520 checkTypeSupport(Ty: FD->getType(), Loc: FD->getLocation(), D: FD);
16521
16522 return dcl;
16523}
16524
16525/// When we finish delayed parsing of an attribute, we must attach it to the
16526/// relevant Decl.
16527void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
16528 ParsedAttributes &Attrs) {
16529 // Always attach attributes to the underlying decl.
16530 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D))
16531 D = TD->getTemplatedDecl();
16532 ProcessDeclAttributeList(S, D, AttrList: Attrs);
16533 ProcessAPINotes(D);
16534
16535 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: D))
16536 if (Method->isStatic())
16537 checkThisInStaticMemberFunctionAttributes(Method);
16538}
16539
16540/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
16541/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
16542NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
16543 IdentifierInfo &II, Scope *S) {
16544 // It is not valid to implicitly define a function in C23.
16545 assert(LangOpts.implicitFunctionsAllowed() &&
16546 "Implicit function declarations aren't allowed in this language mode");
16547
16548 // Find the scope in which the identifier is injected and the corresponding
16549 // DeclContext.
16550 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16551 // In that case, we inject the declaration into the translation unit scope
16552 // instead.
16553 Scope *BlockScope = S;
16554 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16555 BlockScope = BlockScope->getParent();
16556
16557 // Loop until we find a DeclContext that is either a function/method or the
16558 // translation unit, which are the only two valid places to implicitly define
16559 // a function. This avoids accidentally defining the function within a tag
16560 // declaration, for example.
16561 Scope *ContextScope = BlockScope;
16562 while (!ContextScope->getEntity() ||
16563 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16564 !ContextScope->getEntity()->isTranslationUnit()))
16565 ContextScope = ContextScope->getParent();
16566 ContextRAII SavedContext(*this, ContextScope->getEntity());
16567
16568 // Before we produce a declaration for an implicitly defined
16569 // function, see whether there was a locally-scoped declaration of
16570 // this name as a function or variable. If so, use that
16571 // (non-visible) declaration, and complain about it.
16572 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(Name: &II);
16573 if (ExternCPrev) {
16574 // We still need to inject the function into the enclosing block scope so
16575 // that later (non-call) uses can see it.
16576 PushOnScopeChains(D: ExternCPrev, S: BlockScope, /*AddToContext*/false);
16577
16578 // C89 footnote 38:
16579 // If in fact it is not defined as having type "function returning int",
16580 // the behavior is undefined.
16581 if (!isa<FunctionDecl>(Val: ExternCPrev) ||
16582 !Context.typesAreCompatible(
16583 T1: cast<FunctionDecl>(Val: ExternCPrev)->getType(),
16584 T2: Context.getFunctionNoProtoType(Context.IntTy))) {
16585 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16586 << ExternCPrev << !getLangOpts().C99;
16587 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16588 return ExternCPrev;
16589 }
16590 }
16591
16592 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16593 unsigned diag_id;
16594 if (II.getName().starts_with("__builtin_"))
16595 diag_id = diag::warn_builtin_unknown;
16596 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16597 else if (getLangOpts().C99)
16598 diag_id = diag::ext_implicit_function_decl_c99;
16599 else
16600 diag_id = diag::warn_implicit_function_decl;
16601
16602 TypoCorrection Corrected;
16603 // Because typo correction is expensive, only do it if the implicit
16604 // function declaration is going to be treated as an error.
16605 //
16606 // Perform the correction before issuing the main diagnostic, as some
16607 // consumers use typo-correction callbacks to enhance the main diagnostic.
16608 if (S && !ExternCPrev &&
16609 (Diags.getDiagnosticLevel(DiagID: diag_id, Loc) >= DiagnosticsEngine::Error)) {
16610 DeclFilterCCC<FunctionDecl> CCC{};
16611 Corrected = CorrectTypo(Typo: DeclarationNameInfo(&II, Loc), LookupKind: LookupOrdinaryName,
16612 S, SS: nullptr, CCC, Mode: CTK_NonError);
16613 }
16614
16615 Diag(Loc, diag_id) << &II;
16616 if (Corrected) {
16617 // If the correction is going to suggest an implicitly defined function,
16618 // skip the correction as not being a particularly good idea.
16619 bool Diagnose = true;
16620 if (const auto *D = Corrected.getCorrectionDecl())
16621 Diagnose = !D->isImplicit();
16622 if (Diagnose)
16623 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16624 /*ErrorRecovery*/ false);
16625 }
16626
16627 // If we found a prior declaration of this function, don't bother building
16628 // another one. We've already pushed that one into scope, so there's nothing
16629 // more to do.
16630 if (ExternCPrev)
16631 return ExternCPrev;
16632
16633 // Set a Declarator for the implicit definition: int foo();
16634 const char *Dummy;
16635 AttributeFactory attrFactory;
16636 DeclSpec DS(attrFactory);
16637 unsigned DiagID;
16638 bool Error = DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc, PrevSpec&: Dummy, DiagID,
16639 Policy: Context.getPrintingPolicy());
16640 (void)Error; // Silence warning.
16641 assert(!Error && "Error setting up implicit decl!");
16642 SourceLocation NoLoc;
16643 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
16644 D.AddTypeInfo(TI: DeclaratorChunk::getFunction(/*HasProto=*/false,
16645 /*IsAmbiguous=*/false,
16646 /*LParenLoc=*/NoLoc,
16647 /*Params=*/nullptr,
16648 /*NumParams=*/0,
16649 /*EllipsisLoc=*/NoLoc,
16650 /*RParenLoc=*/NoLoc,
16651 /*RefQualifierIsLvalueRef=*/true,
16652 /*RefQualifierLoc=*/NoLoc,
16653 /*MutableLoc=*/NoLoc, ESpecType: EST_None,
16654 /*ESpecRange=*/SourceRange(),
16655 /*Exceptions=*/nullptr,
16656 /*ExceptionRanges=*/nullptr,
16657 /*NumExceptions=*/0,
16658 /*NoexceptExpr=*/nullptr,
16659 /*ExceptionSpecTokens=*/nullptr,
16660 /*DeclsInPrototype=*/std::nullopt,
16661 LocalRangeBegin: Loc, LocalRangeEnd: Loc, TheDeclarator&: D),
16662 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
16663 D.SetIdentifier(Id: &II, IdLoc: Loc);
16664
16665 // Insert this function into the enclosing block scope.
16666 FunctionDecl *FD = cast<FunctionDecl>(Val: ActOnDeclarator(S: BlockScope, D));
16667 FD->setImplicit();
16668
16669 AddKnownFunctionAttributes(FD);
16670
16671 return FD;
16672}
16673
16674/// If this function is a C++ replaceable global allocation function
16675/// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
16676/// adds any function attributes that we know a priori based on the standard.
16677///
16678/// We need to check for duplicate attributes both here and where user-written
16679/// attributes are applied to declarations.
16680void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
16681 FunctionDecl *FD) {
16682 if (FD->isInvalidDecl())
16683 return;
16684
16685 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16686 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16687 return;
16688
16689 std::optional<unsigned> AlignmentParam;
16690 bool IsNothrow = false;
16691 if (!FD->isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam, IsNothrow: &IsNothrow))
16692 return;
16693
16694 // C++2a [basic.stc.dynamic.allocation]p4:
16695 // An allocation function that has a non-throwing exception specification
16696 // indicates failure by returning a null pointer value. Any other allocation
16697 // function never returns a null pointer value and indicates failure only by
16698 // throwing an exception [...]
16699 //
16700 // However, -fcheck-new invalidates this possible assumption, so don't add
16701 // NonNull when that is enabled.
16702 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16703 !getLangOpts().CheckNew)
16704 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16705
16706 // C++2a [basic.stc.dynamic.allocation]p2:
16707 // An allocation function attempts to allocate the requested amount of
16708 // storage. [...] If the request succeeds, the value returned by a
16709 // replaceable allocation function is a [...] pointer value p0 different
16710 // from any previously returned value p1 [...]
16711 //
16712 // However, this particular information is being added in codegen,
16713 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16714
16715 // C++2a [basic.stc.dynamic.allocation]p2:
16716 // An allocation function attempts to allocate the requested amount of
16717 // storage. If it is successful, it returns the address of the start of a
16718 // block of storage whose length in bytes is at least as large as the
16719 // requested size.
16720 if (!FD->hasAttr<AllocSizeAttr>()) {
16721 FD->addAttr(AllocSizeAttr::CreateImplicit(
16722 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16723 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16724 }
16725
16726 // C++2a [basic.stc.dynamic.allocation]p3:
16727 // For an allocation function [...], the pointer returned on a successful
16728 // call shall represent the address of storage that is aligned as follows:
16729 // (3.1) If the allocation function takes an argument of type
16730 // std​::​align_­val_­t, the storage will have the alignment
16731 // specified by the value of this argument.
16732 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16733 FD->addAttr(AllocAlignAttr::CreateImplicit(
16734 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16735 }
16736
16737 // FIXME:
16738 // C++2a [basic.stc.dynamic.allocation]p3:
16739 // For an allocation function [...], the pointer returned on a successful
16740 // call shall represent the address of storage that is aligned as follows:
16741 // (3.2) Otherwise, if the allocation function is named operator new[],
16742 // the storage is aligned for any object that does not have
16743 // new-extended alignment ([basic.align]) and is no larger than the
16744 // requested size.
16745 // (3.3) Otherwise, the storage is aligned for any object that does not
16746 // have new-extended alignment and is of the requested size.
16747}
16748
16749/// Adds any function attributes that we know a priori based on
16750/// the declaration of this function.
16751///
16752/// These attributes can apply both to implicitly-declared builtins
16753/// (like __builtin___printf_chk) or to library-declared functions
16754/// like NSLog or printf.
16755///
16756/// We need to check for duplicate attributes both here and where user-written
16757/// attributes are applied to declarations.
16758void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
16759 if (FD->isInvalidDecl())
16760 return;
16761
16762 // If this is a built-in function, map its builtin attributes to
16763 // actual attributes.
16764 if (unsigned BuiltinID = FD->getBuiltinID()) {
16765 // Handle printf-formatting attributes.
16766 unsigned FormatIdx;
16767 bool HasVAListArg;
16768 if (Context.BuiltinInfo.isPrintfLike(ID: BuiltinID, FormatIdx, HasVAListArg)) {
16769 if (!FD->hasAttr<FormatAttr>()) {
16770 const char *fmt = "printf";
16771 unsigned int NumParams = FD->getNumParams();
16772 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16773 FD->getParamDecl(i: FormatIdx)->getType()->isObjCObjectPointerType())
16774 fmt = "NSString";
16775 FD->addAttr(FormatAttr::CreateImplicit(Context,
16776 &Context.Idents.get(fmt),
16777 FormatIdx+1,
16778 HasVAListArg ? 0 : FormatIdx+2,
16779 FD->getLocation()));
16780 }
16781 }
16782 if (Context.BuiltinInfo.isScanfLike(ID: BuiltinID, FormatIdx,
16783 HasVAListArg)) {
16784 if (!FD->hasAttr<FormatAttr>())
16785 FD->addAttr(FormatAttr::CreateImplicit(Context,
16786 &Context.Idents.get("scanf"),
16787 FormatIdx+1,
16788 HasVAListArg ? 0 : FormatIdx+2,
16789 FD->getLocation()));
16790 }
16791
16792 // Handle automatically recognized callbacks.
16793 SmallVector<int, 4> Encoding;
16794 if (!FD->hasAttr<CallbackAttr>() &&
16795 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16796 FD->addAttr(CallbackAttr::CreateImplicit(
16797 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16798
16799 // Mark const if we don't care about errno and/or floating point exceptions
16800 // that are the only thing preventing the function from being const. This
16801 // allows IRgen to use LLVM intrinsics for such functions.
16802 bool NoExceptions =
16803 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
16804 bool ConstWithoutErrnoAndExceptions =
16805 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(ID: BuiltinID);
16806 bool ConstWithoutExceptions =
16807 Context.BuiltinInfo.isConstWithoutExceptions(ID: BuiltinID);
16808 if (!FD->hasAttr<ConstAttr>() &&
16809 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16810 (!ConstWithoutErrnoAndExceptions ||
16811 (!getLangOpts().MathErrno && NoExceptions)) &&
16812 (!ConstWithoutExceptions || NoExceptions))
16813 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16814
16815 // We make "fma" on GNU or Windows const because we know it does not set
16816 // errno in those environments even though it could set errno based on the
16817 // C standard.
16818 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16819 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16820 !FD->hasAttr<ConstAttr>()) {
16821 switch (BuiltinID) {
16822 case Builtin::BI__builtin_fma:
16823 case Builtin::BI__builtin_fmaf:
16824 case Builtin::BI__builtin_fmal:
16825 case Builtin::BIfma:
16826 case Builtin::BIfmaf:
16827 case Builtin::BIfmal:
16828 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16829 break;
16830 default:
16831 break;
16832 }
16833 }
16834
16835 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16836 !FD->hasAttr<ReturnsTwiceAttr>())
16837 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16838 FD->getLocation()));
16839 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16840 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16841 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16842 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16843 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16844 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16845 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16846 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16847 // Add the appropriate attribute, depending on the CUDA compilation mode
16848 // and which target the builtin belongs to. For example, during host
16849 // compilation, aux builtins are __device__, while the rest are __host__.
16850 if (getLangOpts().CUDAIsDevice !=
16851 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
16852 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16853 else
16854 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16855 }
16856
16857 // Add known guaranteed alignment for allocation functions.
16858 switch (BuiltinID) {
16859 case Builtin::BImemalign:
16860 case Builtin::BIaligned_alloc:
16861 if (!FD->hasAttr<AllocAlignAttr>())
16862 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16863 FD->getLocation()));
16864 break;
16865 default:
16866 break;
16867 }
16868
16869 // Add allocsize attribute for allocation functions.
16870 switch (BuiltinID) {
16871 case Builtin::BIcalloc:
16872 FD->addAttr(AllocSizeAttr::CreateImplicit(
16873 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16874 break;
16875 case Builtin::BImemalign:
16876 case Builtin::BIaligned_alloc:
16877 case Builtin::BIrealloc:
16878 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16879 ParamIdx(), FD->getLocation()));
16880 break;
16881 case Builtin::BImalloc:
16882 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16883 ParamIdx(), FD->getLocation()));
16884 break;
16885 default:
16886 break;
16887 }
16888
16889 // Add lifetime attribute to std::move, std::fowrard et al.
16890 switch (BuiltinID) {
16891 case Builtin::BIaddressof:
16892 case Builtin::BI__addressof:
16893 case Builtin::BI__builtin_addressof:
16894 case Builtin::BIas_const:
16895 case Builtin::BIforward:
16896 case Builtin::BIforward_like:
16897 case Builtin::BImove:
16898 case Builtin::BImove_if_noexcept:
16899 if (ParmVarDecl *P = FD->getParamDecl(0u);
16900 !P->hasAttr<LifetimeBoundAttr>())
16901 P->addAttr(
16902 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16903 break;
16904 default:
16905 break;
16906 }
16907 }
16908
16909 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
16910
16911 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16912 // throw, add an implicit nothrow attribute to any extern "C" function we come
16913 // across.
16914 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16915 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16916 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16917 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16918 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16919 }
16920
16921 IdentifierInfo *Name = FD->getIdentifier();
16922 if (!Name)
16923 return;
16924 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
16925 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16926 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16927 LinkageSpecLanguageIDs::C)) {
16928 // Okay: this could be a libc/libm/Objective-C function we know
16929 // about.
16930 } else
16931 return;
16932
16933 if (Name->isStr(Str: "asprintf") || Name->isStr(Str: "vasprintf")) {
16934 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16935 // target-specific builtins, perhaps?
16936 if (!FD->hasAttr<FormatAttr>())
16937 FD->addAttr(FormatAttr::CreateImplicit(Context,
16938 &Context.Idents.get("printf"), 2,
16939 Name->isStr("vasprintf") ? 0 : 3,
16940 FD->getLocation()));
16941 }
16942
16943 if (Name->isStr(Str: "__CFStringMakeConstantString")) {
16944 // We already have a __builtin___CFStringMakeConstantString,
16945 // but builds that use -fno-constant-cfstrings don't go through that.
16946 if (!FD->hasAttr<FormatArgAttr>())
16947 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16948 FD->getLocation()));
16949 }
16950}
16951
16952TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
16953 TypeSourceInfo *TInfo) {
16954 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16955 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16956
16957 if (!TInfo) {
16958 assert(D.isInvalidType() && "no declarator info for valid type");
16959 TInfo = Context.getTrivialTypeSourceInfo(T);
16960 }
16961
16962 // Scope manipulation handled by caller.
16963 TypedefDecl *NewTD =
16964 TypedefDecl::Create(C&: Context, DC: CurContext, StartLoc: D.getBeginLoc(),
16965 IdLoc: D.getIdentifierLoc(), Id: D.getIdentifier(), TInfo);
16966
16967 // Bail out immediately if we have an invalid declaration.
16968 if (D.isInvalidType()) {
16969 NewTD->setInvalidDecl();
16970 return NewTD;
16971 }
16972
16973 if (D.getDeclSpec().isModulePrivateSpecified()) {
16974 if (CurContext->isFunctionOrMethod())
16975 Diag(NewTD->getLocation(), diag::err_module_private_local)
16976 << 2 << NewTD
16977 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16978 << FixItHint::CreateRemoval(
16979 D.getDeclSpec().getModulePrivateSpecLoc());
16980 else
16981 NewTD->setModulePrivate();
16982 }
16983
16984 // C++ [dcl.typedef]p8:
16985 // If the typedef declaration defines an unnamed class (or
16986 // enum), the first typedef-name declared by the declaration
16987 // to be that class type (or enum type) is used to denote the
16988 // class type (or enum type) for linkage purposes only.
16989 // We need to check whether the type was declared in the declaration.
16990 switch (D.getDeclSpec().getTypeSpecType()) {
16991 case TST_enum:
16992 case TST_struct:
16993 case TST_interface:
16994 case TST_union:
16995 case TST_class: {
16996 TagDecl *tagFromDeclSpec = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
16997 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16998 break;
16999 }
17000
17001 default:
17002 break;
17003 }
17004
17005 return NewTD;
17006}
17007
17008/// Check that this is a valid underlying type for an enum declaration.
17009bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
17010 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17011 QualType T = TI->getType();
17012
17013 if (T->isDependentType())
17014 return false;
17015
17016 // This doesn't use 'isIntegralType' despite the error message mentioning
17017 // integral type because isIntegralType would also allow enum types in C.
17018 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17019 if (BT->isInteger())
17020 return false;
17021
17022 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17023 << T << T->isBitIntType();
17024}
17025
17026/// Check whether this is a valid redeclaration of a previous enumeration.
17027/// \return true if the redeclaration was invalid.
17028bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
17029 QualType EnumUnderlyingTy, bool IsFixed,
17030 const EnumDecl *Prev) {
17031 if (IsScoped != Prev->isScoped()) {
17032 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17033 << Prev->isScoped();
17034 Diag(Prev->getLocation(), diag::note_previous_declaration);
17035 return true;
17036 }
17037
17038 if (IsFixed && Prev->isFixed()) {
17039 if (!EnumUnderlyingTy->isDependentType() &&
17040 !Prev->getIntegerType()->isDependentType() &&
17041 !Context.hasSameUnqualifiedType(T1: EnumUnderlyingTy,
17042 T2: Prev->getIntegerType())) {
17043 // TODO: Highlight the underlying type of the redeclaration.
17044 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17045 << EnumUnderlyingTy << Prev->getIntegerType();
17046 Diag(Prev->getLocation(), diag::note_previous_declaration)
17047 << Prev->getIntegerTypeRange();
17048 return true;
17049 }
17050 } else if (IsFixed != Prev->isFixed()) {
17051 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17052 << Prev->isFixed();
17053 Diag(Prev->getLocation(), diag::note_previous_declaration);
17054 return true;
17055 }
17056
17057 return false;
17058}
17059
17060/// Get diagnostic %select index for tag kind for
17061/// redeclaration diagnostic message.
17062/// WARNING: Indexes apply to particular diagnostics only!
17063///
17064/// \returns diagnostic %select index.
17065static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
17066 switch (Tag) {
17067 case TagTypeKind::Struct:
17068 return 0;
17069 case TagTypeKind::Interface:
17070 return 1;
17071 case TagTypeKind::Class:
17072 return 2;
17073 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17074 }
17075}
17076
17077/// Determine if tag kind is a class-key compatible with
17078/// class for redeclaration (class, struct, or __interface).
17079///
17080/// \returns true iff the tag kind is compatible.
17081static bool isClassCompatTagKind(TagTypeKind Tag)
17082{
17083 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17084 Tag == TagTypeKind::Interface;
17085}
17086
17087Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
17088 TagTypeKind TTK) {
17089 if (isa<TypedefDecl>(Val: PrevDecl))
17090 return NTK_Typedef;
17091 else if (isa<TypeAliasDecl>(Val: PrevDecl))
17092 return NTK_TypeAlias;
17093 else if (isa<ClassTemplateDecl>(Val: PrevDecl))
17094 return NTK_Template;
17095 else if (isa<TypeAliasTemplateDecl>(Val: PrevDecl))
17096 return NTK_TypeAliasTemplate;
17097 else if (isa<TemplateTemplateParmDecl>(Val: PrevDecl))
17098 return NTK_TemplateTemplateArgument;
17099 switch (TTK) {
17100 case TagTypeKind::Struct:
17101 case TagTypeKind::Interface:
17102 case TagTypeKind::Class:
17103 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
17104 case TagTypeKind::Union:
17105 return NTK_NonUnion;
17106 case TagTypeKind::Enum:
17107 return NTK_NonEnum;
17108 }
17109 llvm_unreachable("invalid TTK");
17110}
17111
17112/// Determine whether a tag with a given kind is acceptable
17113/// as a redeclaration of the given tag declaration.
17114///
17115/// \returns true if the new tag kind is acceptable, false otherwise.
17116bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
17117 TagTypeKind NewTag, bool isDefinition,
17118 SourceLocation NewTagLoc,
17119 const IdentifierInfo *Name) {
17120 // C++ [dcl.type.elab]p3:
17121 // The class-key or enum keyword present in the
17122 // elaborated-type-specifier shall agree in kind with the
17123 // declaration to which the name in the elaborated-type-specifier
17124 // refers. This rule also applies to the form of
17125 // elaborated-type-specifier that declares a class-name or
17126 // friend class since it can be construed as referring to the
17127 // definition of the class. Thus, in any
17128 // elaborated-type-specifier, the enum keyword shall be used to
17129 // refer to an enumeration (7.2), the union class-key shall be
17130 // used to refer to a union (clause 9), and either the class or
17131 // struct class-key shall be used to refer to a class (clause 9)
17132 // declared using the class or struct class-key.
17133 TagTypeKind OldTag = Previous->getTagKind();
17134 if (OldTag != NewTag &&
17135 !(isClassCompatTagKind(Tag: OldTag) && isClassCompatTagKind(Tag: NewTag)))
17136 return false;
17137
17138 // Tags are compatible, but we might still want to warn on mismatched tags.
17139 // Non-class tags can't be mismatched at this point.
17140 if (!isClassCompatTagKind(Tag: NewTag))
17141 return true;
17142
17143 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17144 // by our warning analysis. We don't want to warn about mismatches with (eg)
17145 // declarations in system headers that are designed to be specialized, but if
17146 // a user asks us to warn, we should warn if their code contains mismatched
17147 // declarations.
17148 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17149 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17150 Loc);
17151 };
17152 if (IsIgnoredLoc(NewTagLoc))
17153 return true;
17154
17155 auto IsIgnored = [&](const TagDecl *Tag) {
17156 return IsIgnoredLoc(Tag->getLocation());
17157 };
17158 while (IsIgnored(Previous)) {
17159 Previous = Previous->getPreviousDecl();
17160 if (!Previous)
17161 return true;
17162 OldTag = Previous->getTagKind();
17163 }
17164
17165 bool isTemplate = false;
17166 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Previous))
17167 isTemplate = Record->getDescribedClassTemplate();
17168
17169 if (inTemplateInstantiation()) {
17170 if (OldTag != NewTag) {
17171 // In a template instantiation, do not offer fix-its for tag mismatches
17172 // since they usually mess up the template instead of fixing the problem.
17173 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17174 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17175 << getRedeclDiagFromTagKind(OldTag);
17176 // FIXME: Note previous location?
17177 }
17178 return true;
17179 }
17180
17181 if (isDefinition) {
17182 // On definitions, check all previous tags and issue a fix-it for each
17183 // one that doesn't match the current tag.
17184 if (Previous->getDefinition()) {
17185 // Don't suggest fix-its for redefinitions.
17186 return true;
17187 }
17188
17189 bool previousMismatch = false;
17190 for (const TagDecl *I : Previous->redecls()) {
17191 if (I->getTagKind() != NewTag) {
17192 // Ignore previous declarations for which the warning was disabled.
17193 if (IsIgnored(I))
17194 continue;
17195
17196 if (!previousMismatch) {
17197 previousMismatch = true;
17198 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17199 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17200 << getRedeclDiagFromTagKind(I->getTagKind());
17201 }
17202 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17203 << getRedeclDiagFromTagKind(NewTag)
17204 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17205 TypeWithKeyword::getTagTypeKindName(NewTag));
17206 }
17207 }
17208 return true;
17209 }
17210
17211 // Identify the prevailing tag kind: this is the kind of the definition (if
17212 // there is a non-ignored definition), or otherwise the kind of the prior
17213 // (non-ignored) declaration.
17214 const TagDecl *PrevDef = Previous->getDefinition();
17215 if (PrevDef && IsIgnored(PrevDef))
17216 PrevDef = nullptr;
17217 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17218 if (Redecl->getTagKind() != NewTag) {
17219 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17220 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17221 << getRedeclDiagFromTagKind(OldTag);
17222 Diag(Redecl->getLocation(), diag::note_previous_use);
17223
17224 // If there is a previous definition, suggest a fix-it.
17225 if (PrevDef) {
17226 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17227 << getRedeclDiagFromTagKind(Redecl->getTagKind())
17228 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
17229 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
17230 }
17231 }
17232
17233 return true;
17234}
17235
17236/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17237/// from an outer enclosing namespace or file scope inside a friend declaration.
17238/// This should provide the commented out code in the following snippet:
17239/// namespace N {
17240/// struct X;
17241/// namespace M {
17242/// struct Y { friend struct /*N::*/ X; };
17243/// }
17244/// }
17245static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
17246 SourceLocation NameLoc) {
17247 // While the decl is in a namespace, do repeated lookup of that name and see
17248 // if we get the same namespace back. If we do not, continue until
17249 // translation unit scope, at which point we have a fully qualified NNS.
17250 SmallVector<IdentifierInfo *, 4> Namespaces;
17251 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17252 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17253 // This tag should be declared in a namespace, which can only be enclosed by
17254 // other namespaces. Bail if there's an anonymous namespace in the chain.
17255 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: DC);
17256 if (!Namespace || Namespace->isAnonymousNamespace())
17257 return FixItHint();
17258 IdentifierInfo *II = Namespace->getIdentifier();
17259 Namespaces.push_back(Elt: II);
17260 NamedDecl *Lookup = SemaRef.LookupSingleName(
17261 S, Name: II, Loc: NameLoc, NameKind: Sema::LookupNestedNameSpecifierName);
17262 if (Lookup == Namespace)
17263 break;
17264 }
17265
17266 // Once we have all the namespaces, reverse them to go outermost first, and
17267 // build an NNS.
17268 SmallString<64> Insertion;
17269 llvm::raw_svector_ostream OS(Insertion);
17270 if (DC->isTranslationUnit())
17271 OS << "::";
17272 std::reverse(first: Namespaces.begin(), last: Namespaces.end());
17273 for (auto *II : Namespaces)
17274 OS << II->getName() << "::";
17275 return FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: Insertion);
17276}
17277
17278/// Determine whether a tag originally declared in context \p OldDC can
17279/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17280/// found a declaration in \p OldDC as a previous decl, perhaps through a
17281/// using-declaration).
17282static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
17283 DeclContext *NewDC) {
17284 OldDC = OldDC->getRedeclContext();
17285 NewDC = NewDC->getRedeclContext();
17286
17287 if (OldDC->Equals(DC: NewDC))
17288 return true;
17289
17290 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17291 // encloses the other).
17292 if (S.getLangOpts().MSVCCompat &&
17293 (OldDC->Encloses(DC: NewDC) || NewDC->Encloses(DC: OldDC)))
17294 return true;
17295
17296 return false;
17297}
17298
17299/// This is invoked when we see 'struct foo' or 'struct {'. In the
17300/// former case, Name will be non-null. In the later case, Name will be null.
17301/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
17302/// reference/declaration/definition of a tag.
17303///
17304/// \param IsTypeSpecifier \c true if this is a type-specifier (or
17305/// trailing-type-specifier) other than one in an alias-declaration.
17306///
17307/// \param SkipBody If non-null, will be set to indicate if the caller should
17308/// skip the definition of this tag and treat it as if it were a declaration.
17309DeclResult
17310Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17311 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17312 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17313 SourceLocation ModulePrivateLoc,
17314 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17315 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17316 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17317 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17318 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17319 // If this is not a definition, it must have a name.
17320 IdentifierInfo *OrigName = Name;
17321 assert((Name != nullptr || TUK == TUK_Definition) &&
17322 "Nameless record must be a definition!");
17323 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
17324
17325 OwnedDecl = false;
17326 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
17327 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17328
17329 // FIXME: Check member specializations more carefully.
17330 bool isMemberSpecialization = false;
17331 bool Invalid = false;
17332
17333 // We only need to do this matching if we have template parameters
17334 // or a scope specifier, which also conveniently avoids this work
17335 // for non-C++ cases.
17336 if (TemplateParameterLists.size() > 0 ||
17337 (SS.isNotEmpty() && TUK != TUK_Reference)) {
17338 TemplateParameterList *TemplateParams =
17339 MatchTemplateParametersToScopeSpecifier(
17340 DeclStartLoc: KWLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TemplateParameterLists,
17341 IsFriend: TUK == TUK_Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
17342
17343 // C++23 [dcl.type.elab] p2:
17344 // If an elaborated-type-specifier is the sole constituent of a
17345 // declaration, the declaration is ill-formed unless it is an explicit
17346 // specialization, an explicit instantiation or it has one of the
17347 // following forms: [...]
17348 // C++23 [dcl.enum] p1:
17349 // If the enum-head-name of an opaque-enum-declaration contains a
17350 // nested-name-specifier, the declaration shall be an explicit
17351 // specialization.
17352 //
17353 // FIXME: Class template partial specializations can be forward declared
17354 // per CWG2213, but the resolution failed to allow qualified forward
17355 // declarations. This is almost certainly unintentional, so we allow them.
17356 if (TUK == TUK_Declaration && SS.isNotEmpty() && !isMemberSpecialization)
17357 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17358 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();
17359
17360 if (TemplateParams) {
17361 if (Kind == TagTypeKind::Enum) {
17362 Diag(KWLoc, diag::err_enum_template);
17363 return true;
17364 }
17365
17366 if (TemplateParams->size() > 0) {
17367 // This is a declaration or definition of a class template (which may
17368 // be a member of another template).
17369
17370 if (Invalid)
17371 return true;
17372
17373 OwnedDecl = false;
17374 DeclResult Result = CheckClassTemplate(
17375 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attr: Attrs, TemplateParams,
17376 AS, ModulePrivateLoc,
17377 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
17378 OuterTemplateParamLists: TemplateParameterLists.data(), SkipBody);
17379 return Result.get();
17380 } else {
17381 // The "template<>" header is extraneous.
17382 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17383 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17384 isMemberSpecialization = true;
17385 }
17386 }
17387
17388 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17389 CheckTemplateDeclScope(S, TemplateParams: TemplateParameterLists.back()))
17390 return true;
17391 }
17392
17393 if (TUK == TUK_Friend && Kind == TagTypeKind::Enum) {
17394 // C++23 [dcl.type.elab]p4:
17395 // If an elaborated-type-specifier appears with the friend specifier as
17396 // an entire member-declaration, the member-declaration shall have one
17397 // of the following forms:
17398 // friend class-key nested-name-specifier(opt) identifier ;
17399 // friend class-key simple-template-id ;
17400 // friend class-key nested-name-specifier template(opt)
17401 // simple-template-id ;
17402 //
17403 // Since enum is not a class-key, so declarations like "friend enum E;"
17404 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17405 // invalid, most implementations accept so we issue a pedantic warning.
17406 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17407 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17408 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17409 Diag(KWLoc, diag::note_enum_friend)
17410 << (ScopedEnum + ScopedEnumUsesClassTag);
17411 }
17412
17413 // Figure out the underlying type if this a enum declaration. We need to do
17414 // this early, because it's needed to detect if this is an incompatible
17415 // redeclaration.
17416 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17417 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17418
17419 if (Kind == TagTypeKind::Enum) {
17420 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17421 // No underlying type explicitly specified, or we failed to parse the
17422 // type, default to int.
17423 EnumUnderlying = Context.IntTy.getTypePtr();
17424 } else if (UnderlyingType.get()) {
17425 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17426 // integral type; any cv-qualification is ignored.
17427 TypeSourceInfo *TI = nullptr;
17428 GetTypeFromParser(Ty: UnderlyingType.get(), TInfo: &TI);
17429 EnumUnderlying = TI;
17430
17431 if (CheckEnumUnderlyingType(TI))
17432 // Recover by falling back to int.
17433 EnumUnderlying = Context.IntTy.getTypePtr();
17434
17435 if (DiagnoseUnexpandedParameterPack(Loc: TI->getTypeLoc().getBeginLoc(), T: TI,
17436 UPPC: UPPC_FixedUnderlyingType))
17437 EnumUnderlying = Context.IntTy.getTypePtr();
17438
17439 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17440 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17441 // of 'int'. However, if this is an unfixed forward declaration, don't set
17442 // the underlying type unless the user enables -fms-compatibility. This
17443 // makes unfixed forward declared enums incomplete and is more conforming.
17444 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
17445 EnumUnderlying = Context.IntTy.getTypePtr();
17446 }
17447 }
17448
17449 DeclContext *SearchDC = CurContext;
17450 DeclContext *DC = CurContext;
17451 bool isStdBadAlloc = false;
17452 bool isStdAlignValT = false;
17453
17454 RedeclarationKind Redecl = forRedeclarationInCurContext();
17455 if (TUK == TUK_Friend || TUK == TUK_Reference)
17456 Redecl = RedeclarationKind::NotForRedeclaration;
17457
17458 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17459 /// implemented asks for structural equivalence checking, the returned decl
17460 /// here is passed back to the parser, allowing the tag body to be parsed.
17461 auto createTagFromNewDecl = [&]() -> TagDecl * {
17462 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17463 // If there is an identifier, use the location of the identifier as the
17464 // location of the decl, otherwise use the location of the struct/union
17465 // keyword.
17466 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17467 TagDecl *New = nullptr;
17468
17469 if (Kind == TagTypeKind::Enum) {
17470 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, PrevDecl: nullptr,
17471 IsScoped: ScopedEnum, IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
17472 // If this is an undefined enum, bail.
17473 if (TUK != TUK_Definition && !Invalid)
17474 return nullptr;
17475 if (EnumUnderlying) {
17476 EnumDecl *ED = cast<EnumDecl>(Val: New);
17477 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
17478 ED->setIntegerTypeSourceInfo(TI);
17479 else
17480 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17481 QualType EnumTy = ED->getIntegerType();
17482 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
17483 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
17484 : EnumTy);
17485 }
17486 } else { // struct/union
17487 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
17488 PrevDecl: nullptr);
17489 }
17490
17491 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
17492 // Add alignment attributes if necessary; these attributes are checked
17493 // when the ASTContext lays out the structure.
17494 //
17495 // It is important for implementing the correct semantics that this
17496 // happen here (in ActOnTag). The #pragma pack stack is
17497 // maintained as a result of parser callbacks which can occur at
17498 // many points during the parsing of a struct declaration (because
17499 // the #pragma tokens are effectively skipped over during the
17500 // parsing of the struct).
17501 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17502 AddAlignmentAttributesForRecord(RD);
17503 AddMsStructLayoutForRecord(RD);
17504 }
17505 }
17506 New->setLexicalDeclContext(CurContext);
17507 return New;
17508 };
17509
17510 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17511 if (Name && SS.isNotEmpty()) {
17512 // We have a nested-name tag ('struct foo::bar').
17513
17514 // Check for invalid 'foo::'.
17515 if (SS.isInvalid()) {
17516 Name = nullptr;
17517 goto CreateNewDecl;
17518 }
17519
17520 // If this is a friend or a reference to a class in a dependent
17521 // context, don't try to make a decl for it.
17522 if (TUK == TUK_Friend || TUK == TUK_Reference) {
17523 DC = computeDeclContext(SS, EnteringContext: false);
17524 if (!DC) {
17525 IsDependent = true;
17526 return true;
17527 }
17528 } else {
17529 DC = computeDeclContext(SS, EnteringContext: true);
17530 if (!DC) {
17531 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17532 << SS.getRange();
17533 return true;
17534 }
17535 }
17536
17537 if (RequireCompleteDeclContext(SS, DC))
17538 return true;
17539
17540 SearchDC = DC;
17541 // Look-up name inside 'foo::'.
17542 LookupQualifiedName(R&: Previous, LookupCtx: DC);
17543
17544 if (Previous.isAmbiguous())
17545 return true;
17546
17547 if (Previous.empty()) {
17548 // Name lookup did not find anything. However, if the
17549 // nested-name-specifier refers to the current instantiation,
17550 // and that current instantiation has any dependent base
17551 // classes, we might find something at instantiation time: treat
17552 // this as a dependent elaborated-type-specifier.
17553 // But this only makes any sense for reference-like lookups.
17554 if (Previous.wasNotFoundInCurrentInstantiation() &&
17555 (TUK == TUK_Reference || TUK == TUK_Friend)) {
17556 IsDependent = true;
17557 return true;
17558 }
17559
17560 // A tag 'foo::bar' must already exist.
17561 Diag(NameLoc, diag::err_not_tag_in_scope)
17562 << llvm::to_underlying(Kind) << Name << DC << SS.getRange();
17563 Name = nullptr;
17564 Invalid = true;
17565 goto CreateNewDecl;
17566 }
17567 } else if (Name) {
17568 // C++14 [class.mem]p14:
17569 // If T is the name of a class, then each of the following shall have a
17570 // name different from T:
17571 // -- every member of class T that is itself a type
17572 if (TUK != TUK_Reference && TUK != TUK_Friend &&
17573 DiagnoseClassNameShadow(DC: SearchDC, NameInfo: DeclarationNameInfo(Name, NameLoc)))
17574 return true;
17575
17576 // If this is a named struct, check to see if there was a previous forward
17577 // declaration or definition.
17578 // FIXME: We're looking into outer scopes here, even when we
17579 // shouldn't be. Doing so can result in ambiguities that we
17580 // shouldn't be diagnosing.
17581 LookupName(R&: Previous, S);
17582
17583 // When declaring or defining a tag, ignore ambiguities introduced
17584 // by types using'ed into this scope.
17585 if (Previous.isAmbiguous() &&
17586 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
17587 LookupResult::Filter F = Previous.makeFilter();
17588 while (F.hasNext()) {
17589 NamedDecl *ND = F.next();
17590 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17591 SearchDC->getRedeclContext()))
17592 F.erase();
17593 }
17594 F.done();
17595 }
17596
17597 // C++11 [namespace.memdef]p3:
17598 // If the name in a friend declaration is neither qualified nor
17599 // a template-id and the declaration is a function or an
17600 // elaborated-type-specifier, the lookup to determine whether
17601 // the entity has been previously declared shall not consider
17602 // any scopes outside the innermost enclosing namespace.
17603 //
17604 // MSVC doesn't implement the above rule for types, so a friend tag
17605 // declaration may be a redeclaration of a type declared in an enclosing
17606 // scope. They do implement this rule for friend functions.
17607 //
17608 // Does it matter that this should be by scope instead of by
17609 // semantic context?
17610 if (!Previous.empty() && TUK == TUK_Friend) {
17611 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17612 LookupResult::Filter F = Previous.makeFilter();
17613 bool FriendSawTagOutsideEnclosingNamespace = false;
17614 while (F.hasNext()) {
17615 NamedDecl *ND = F.next();
17616 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17617 if (DC->isFileContext() &&
17618 !EnclosingNS->Encloses(DC: ND->getDeclContext())) {
17619 if (getLangOpts().MSVCCompat)
17620 FriendSawTagOutsideEnclosingNamespace = true;
17621 else
17622 F.erase();
17623 }
17624 }
17625 F.done();
17626
17627 // Diagnose this MSVC extension in the easy case where lookup would have
17628 // unambiguously found something outside the enclosing namespace.
17629 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17630 NamedDecl *ND = Previous.getFoundDecl();
17631 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17632 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17633 }
17634 }
17635
17636 // Note: there used to be some attempt at recovery here.
17637 if (Previous.isAmbiguous())
17638 return true;
17639
17640 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
17641 // FIXME: This makes sure that we ignore the contexts associated
17642 // with C structs, unions, and enums when looking for a matching
17643 // tag declaration or definition. See the similar lookup tweak
17644 // in Sema::LookupName; is there a better way to deal with this?
17645 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(Val: SearchDC))
17646 SearchDC = SearchDC->getParent();
17647 } else if (getLangOpts().CPlusPlus) {
17648 // Inside ObjCContainer want to keep it as a lexical decl context but go
17649 // past it (most often to TranslationUnit) to find the semantic decl
17650 // context.
17651 while (isa<ObjCContainerDecl>(Val: SearchDC))
17652 SearchDC = SearchDC->getParent();
17653 }
17654 } else if (getLangOpts().CPlusPlus) {
17655 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17656 // TagDecl the same way as we skip it for named TagDecl.
17657 while (isa<ObjCContainerDecl>(Val: SearchDC))
17658 SearchDC = SearchDC->getParent();
17659 }
17660
17661 if (Previous.isSingleResult() &&
17662 Previous.getFoundDecl()->isTemplateParameter()) {
17663 // Maybe we will complain about the shadowed template parameter.
17664 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17665 // Just pretend that we didn't see the previous declaration.
17666 Previous.clear();
17667 }
17668
17669 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17670 DC->Equals(getStdNamespace())) {
17671 if (Name->isStr(Str: "bad_alloc")) {
17672 // This is a declaration of or a reference to "std::bad_alloc".
17673 isStdBadAlloc = true;
17674
17675 // If std::bad_alloc has been implicitly declared (but made invisible to
17676 // name lookup), fill in this implicit declaration as the previous
17677 // declaration, so that the declarations get chained appropriately.
17678 if (Previous.empty() && StdBadAlloc)
17679 Previous.addDecl(getStdBadAlloc());
17680 } else if (Name->isStr(Str: "align_val_t")) {
17681 isStdAlignValT = true;
17682 if (Previous.empty() && StdAlignValT)
17683 Previous.addDecl(getStdAlignValT());
17684 }
17685 }
17686
17687 // If we didn't find a previous declaration, and this is a reference
17688 // (or friend reference), move to the correct scope. In C++, we
17689 // also need to do a redeclaration lookup there, just in case
17690 // there's a shadow friend decl.
17691 if (Name && Previous.empty() &&
17692 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
17693 if (Invalid) goto CreateNewDecl;
17694 assert(SS.isEmpty());
17695
17696 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
17697 // C++ [basic.scope.pdecl]p5:
17698 // -- for an elaborated-type-specifier of the form
17699 //
17700 // class-key identifier
17701 //
17702 // if the elaborated-type-specifier is used in the
17703 // decl-specifier-seq or parameter-declaration-clause of a
17704 // function defined in namespace scope, the identifier is
17705 // declared as a class-name in the namespace that contains
17706 // the declaration; otherwise, except as a friend
17707 // declaration, the identifier is declared in the smallest
17708 // non-class, non-function-prototype scope that contains the
17709 // declaration.
17710 //
17711 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17712 // C structs and unions.
17713 //
17714 // It is an error in C++ to declare (rather than define) an enum
17715 // type, including via an elaborated type specifier. We'll
17716 // diagnose that later; for now, declare the enum in the same
17717 // scope as we would have picked for any other tag type.
17718 //
17719 // GNU C also supports this behavior as part of its incomplete
17720 // enum types extension, while GNU C++ does not.
17721 //
17722 // Find the context where we'll be declaring the tag.
17723 // FIXME: We would like to maintain the current DeclContext as the
17724 // lexical context,
17725 SearchDC = getTagInjectionContext(DC: SearchDC);
17726
17727 // Find the scope where we'll be declaring the tag.
17728 S = getTagInjectionScope(S, LangOpts: getLangOpts());
17729 } else {
17730 assert(TUK == TUK_Friend);
17731 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: SearchDC);
17732
17733 // C++ [namespace.memdef]p3:
17734 // If a friend declaration in a non-local class first declares a
17735 // class or function, the friend class or function is a member of
17736 // the innermost enclosing namespace.
17737 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17738 : SearchDC->getEnclosingNamespaceContext();
17739 }
17740
17741 // In C++, we need to do a redeclaration lookup to properly
17742 // diagnose some problems.
17743 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17744 // hidden declaration so that we don't get ambiguity errors when using a
17745 // type declared by an elaborated-type-specifier. In C that is not correct
17746 // and we should instead merge compatible types found by lookup.
17747 if (getLangOpts().CPlusPlus) {
17748 // FIXME: This can perform qualified lookups into function contexts,
17749 // which are meaningless.
17750 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17751 LookupQualifiedName(R&: Previous, LookupCtx: SearchDC);
17752 } else {
17753 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17754 LookupName(R&: Previous, S);
17755 }
17756 }
17757
17758 // If we have a known previous declaration to use, then use it.
17759 if (Previous.empty() && SkipBody && SkipBody->Previous)
17760 Previous.addDecl(D: SkipBody->Previous);
17761
17762 if (!Previous.empty()) {
17763 NamedDecl *PrevDecl = Previous.getFoundDecl();
17764 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17765
17766 // It's okay to have a tag decl in the same scope as a typedef
17767 // which hides a tag decl in the same scope. Finding this
17768 // with a redeclaration lookup can only actually happen in C++.
17769 //
17770 // This is also okay for elaborated-type-specifiers, which is
17771 // technically forbidden by the current standard but which is
17772 // okay according to the likely resolution of an open issue;
17773 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17774 if (getLangOpts().CPlusPlus) {
17775 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
17776 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17777 TagDecl *Tag = TT->getDecl();
17778 if (Tag->getDeclName() == Name &&
17779 Tag->getDeclContext()->getRedeclContext()
17780 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17781 PrevDecl = Tag;
17782 Previous.clear();
17783 Previous.addDecl(Tag);
17784 Previous.resolveKind();
17785 }
17786 }
17787 }
17788 }
17789
17790 // If this is a redeclaration of a using shadow declaration, it must
17791 // declare a tag in the same context. In MSVC mode, we allow a
17792 // redefinition if either context is within the other.
17793 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: DirectPrevDecl)) {
17794 auto *OldTag = dyn_cast<TagDecl>(Val: PrevDecl);
17795 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
17796 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17797 !(OldTag && isAcceptableTagRedeclContext(
17798 *this, OldTag->getDeclContext(), SearchDC))) {
17799 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17800 Diag(Shadow->getTargetDecl()->getLocation(),
17801 diag::note_using_decl_target);
17802 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17803 << 0;
17804 // Recover by ignoring the old declaration.
17805 Previous.clear();
17806 goto CreateNewDecl;
17807 }
17808 }
17809
17810 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(Val: PrevDecl)) {
17811 // If this is a use of a previous tag, or if the tag is already declared
17812 // in the same scope (so that the definition/declaration completes or
17813 // rementions the tag), reuse the decl.
17814 if (TUK == TUK_Reference || TUK == TUK_Friend ||
17815 isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
17816 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
17817 // Make sure that this wasn't declared as an enum and now used as a
17818 // struct or something similar.
17819 if (!isAcceptableTagRedeclaration(Previous: PrevTagDecl, NewTag: Kind,
17820 isDefinition: TUK == TUK_Definition, NewTagLoc: KWLoc,
17821 Name)) {
17822 bool SafeToContinue =
17823 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17824 Kind != TagTypeKind::Enum);
17825 if (SafeToContinue)
17826 Diag(KWLoc, diag::err_use_with_wrong_tag)
17827 << Name
17828 << FixItHint::CreateReplacement(SourceRange(KWLoc),
17829 PrevTagDecl->getKindName());
17830 else
17831 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17832 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17833
17834 if (SafeToContinue)
17835 Kind = PrevTagDecl->getTagKind();
17836 else {
17837 // Recover by making this an anonymous redefinition.
17838 Name = nullptr;
17839 Previous.clear();
17840 Invalid = true;
17841 }
17842 }
17843
17844 if (Kind == TagTypeKind::Enum &&
17845 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17846 const EnumDecl *PrevEnum = cast<EnumDecl>(Val: PrevTagDecl);
17847 if (TUK == TUK_Reference || TUK == TUK_Friend)
17848 return PrevTagDecl;
17849
17850 QualType EnumUnderlyingTy;
17851 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17852 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17853 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17854 EnumUnderlyingTy = QualType(T, 0);
17855
17856 // All conflicts with previous declarations are recovered by
17857 // returning the previous declaration, unless this is a definition,
17858 // in which case we want the caller to bail out.
17859 if (CheckEnumRedeclaration(EnumLoc: NameLoc.isValid() ? NameLoc : KWLoc,
17860 IsScoped: ScopedEnum, EnumUnderlyingTy,
17861 IsFixed, Prev: PrevEnum))
17862 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
17863 }
17864
17865 // C++11 [class.mem]p1:
17866 // A member shall not be declared twice in the member-specification,
17867 // except that a nested class or member class template can be declared
17868 // and then later defined.
17869 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
17870 S->isDeclScope(PrevDecl)) {
17871 Diag(NameLoc, diag::ext_member_redeclared);
17872 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17873 }
17874
17875 if (!Invalid) {
17876 // If this is a use, just return the declaration we found, unless
17877 // we have attributes.
17878 if (TUK == TUK_Reference || TUK == TUK_Friend) {
17879 if (!Attrs.empty()) {
17880 // FIXME: Diagnose these attributes. For now, we create a new
17881 // declaration to hold them.
17882 } else if (TUK == TUK_Reference &&
17883 (PrevTagDecl->getFriendObjectKind() ==
17884 Decl::FOK_Undeclared ||
17885 PrevDecl->getOwningModule() != getCurrentModule()) &&
17886 SS.isEmpty()) {
17887 // This declaration is a reference to an existing entity, but
17888 // has different visibility from that entity: it either makes
17889 // a friend visible or it makes a type visible in a new module.
17890 // In either case, create a new declaration. We only do this if
17891 // the declaration would have meant the same thing if no prior
17892 // declaration were found, that is, if it was found in the same
17893 // scope where we would have injected a declaration.
17894 if (!getTagInjectionContext(DC: CurContext)->getRedeclContext()
17895 ->Equals(DC: PrevDecl->getDeclContext()->getRedeclContext()))
17896 return PrevTagDecl;
17897 // This is in the injected scope, create a new declaration in
17898 // that scope.
17899 S = getTagInjectionScope(S, LangOpts: getLangOpts());
17900 } else {
17901 return PrevTagDecl;
17902 }
17903 }
17904
17905 // Diagnose attempts to redefine a tag.
17906 if (TUK == TUK_Definition) {
17907 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17908 // If we're defining a specialization and the previous definition
17909 // is from an implicit instantiation, don't emit an error
17910 // here; we'll catch this in the general case below.
17911 bool IsExplicitSpecializationAfterInstantiation = false;
17912 if (isMemberSpecialization) {
17913 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Def))
17914 IsExplicitSpecializationAfterInstantiation =
17915 RD->getTemplateSpecializationKind() !=
17916 TSK_ExplicitSpecialization;
17917 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: Def))
17918 IsExplicitSpecializationAfterInstantiation =
17919 ED->getTemplateSpecializationKind() !=
17920 TSK_ExplicitSpecialization;
17921 }
17922
17923 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17924 // not keep more that one definition around (merge them). However,
17925 // ensure the decl passes the structural compatibility check in
17926 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17927 NamedDecl *Hidden = nullptr;
17928 if (SkipBody && !hasVisibleDefinition(D: Def, Suggested: &Hidden)) {
17929 // There is a definition of this tag, but it is not visible. We
17930 // explicitly make use of C++'s one definition rule here, and
17931 // assume that this definition is identical to the hidden one
17932 // we already have. Make the existing definition visible and
17933 // use it in place of this one.
17934 if (!getLangOpts().CPlusPlus) {
17935 // Postpone making the old definition visible until after we
17936 // complete parsing the new one and do the structural
17937 // comparison.
17938 SkipBody->CheckSameAsPrevious = true;
17939 SkipBody->New = createTagFromNewDecl();
17940 SkipBody->Previous = Def;
17941 return Def;
17942 } else {
17943 SkipBody->ShouldSkip = true;
17944 SkipBody->Previous = Def;
17945 makeMergedDefinitionVisible(ND: Hidden);
17946 // Carry on and handle it like a normal definition. We'll
17947 // skip starting the definitiion later.
17948 }
17949 } else if (!IsExplicitSpecializationAfterInstantiation) {
17950 // A redeclaration in function prototype scope in C isn't
17951 // visible elsewhere, so merely issue a warning.
17952 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17953 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17954 else
17955 Diag(NameLoc, diag::err_redefinition) << Name;
17956 notePreviousDefinition(Old: Def,
17957 New: NameLoc.isValid() ? NameLoc : KWLoc);
17958 // If this is a redefinition, recover by making this
17959 // struct be anonymous, which will make any later
17960 // references get the previous definition.
17961 Name = nullptr;
17962 Previous.clear();
17963 Invalid = true;
17964 }
17965 } else {
17966 // If the type is currently being defined, complain
17967 // about a nested redefinition.
17968 auto *TD = Context.getTagDeclType(Decl: PrevTagDecl)->getAsTagDecl();
17969 if (TD->isBeingDefined()) {
17970 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17971 Diag(PrevTagDecl->getLocation(),
17972 diag::note_previous_definition);
17973 Name = nullptr;
17974 Previous.clear();
17975 Invalid = true;
17976 }
17977 }
17978
17979 // Okay, this is definition of a previously declared or referenced
17980 // tag. We're going to create a new Decl for it.
17981 }
17982
17983 // Okay, we're going to make a redeclaration. If this is some kind
17984 // of reference, make sure we build the redeclaration in the same DC
17985 // as the original, and ignore the current access specifier.
17986 if (TUK == TUK_Friend || TUK == TUK_Reference) {
17987 SearchDC = PrevTagDecl->getDeclContext();
17988 AS = AS_none;
17989 }
17990 }
17991 // If we get here we have (another) forward declaration or we
17992 // have a definition. Just create a new decl.
17993
17994 } else {
17995 // If we get here, this is a definition of a new tag type in a nested
17996 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17997 // new decl/type. We set PrevDecl to NULL so that the entities
17998 // have distinct types.
17999 Previous.clear();
18000 }
18001 // If we get here, we're going to create a new Decl. If PrevDecl
18002 // is non-NULL, it's a definition of the tag declared by
18003 // PrevDecl. If it's NULL, we have a new definition.
18004
18005 // Otherwise, PrevDecl is not a tag, but was found with tag
18006 // lookup. This is only actually possible in C++, where a few
18007 // things like templates still live in the tag namespace.
18008 } else {
18009 // Use a better diagnostic if an elaborated-type-specifier
18010 // found the wrong kind of type on the first
18011 // (non-redeclaration) lookup.
18012 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
18013 !Previous.isForRedeclaration()) {
18014 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18015 Diag(NameLoc, diag::err_tag_reference_non_tag)
18016 << PrevDecl << NTK << llvm::to_underlying(Kind);
18017 Diag(PrevDecl->getLocation(), diag::note_declared_at);
18018 Invalid = true;
18019
18020 // Otherwise, only diagnose if the declaration is in scope.
18021 } else if (!isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18022 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18023 // do nothing
18024
18025 // Diagnose implicit declarations introduced by elaborated types.
18026 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
18027 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18028 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18029 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18030 Invalid = true;
18031
18032 // Otherwise it's a declaration. Call out a particularly common
18033 // case here.
18034 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18035 unsigned Kind = 0;
18036 if (isa<TypeAliasDecl>(Val: PrevDecl)) Kind = 1;
18037 Diag(NameLoc, diag::err_tag_definition_of_typedef)
18038 << Name << Kind << TND->getUnderlyingType();
18039 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18040 Invalid = true;
18041
18042 // Otherwise, diagnose.
18043 } else {
18044 // The tag name clashes with something else in the target scope,
18045 // issue an error and recover by making this tag be anonymous.
18046 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
18047 notePreviousDefinition(Old: PrevDecl, New: NameLoc);
18048 Name = nullptr;
18049 Invalid = true;
18050 }
18051
18052 // The existing declaration isn't relevant to us; we're in a
18053 // new scope, so clear out the previous declaration.
18054 Previous.clear();
18055 }
18056 }
18057
18058CreateNewDecl:
18059
18060 TagDecl *PrevDecl = nullptr;
18061 if (Previous.isSingleResult())
18062 PrevDecl = cast<TagDecl>(Val: Previous.getFoundDecl());
18063
18064 // If there is an identifier, use the location of the identifier as the
18065 // location of the decl, otherwise use the location of the struct/union
18066 // keyword.
18067 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18068
18069 // Otherwise, create a new declaration. If there is a previous
18070 // declaration of the same entity, the two will be linked via
18071 // PrevDecl.
18072 TagDecl *New;
18073
18074 if (Kind == TagTypeKind::Enum) {
18075 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18076 // enum X { A, B, C } D; D should chain to X.
18077 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18078 PrevDecl: cast_or_null<EnumDecl>(Val: PrevDecl), IsScoped: ScopedEnum,
18079 IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18080
18081 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18082 StdAlignValT = cast<EnumDecl>(Val: New);
18083
18084 // If this is an undefined enum, warn.
18085 if (TUK != TUK_Definition && !Invalid) {
18086 TagDecl *Def;
18087 if (IsFixed && cast<EnumDecl>(Val: New)->isFixed()) {
18088 // C++0x: 7.2p2: opaque-enum-declaration.
18089 // Conflicts are diagnosed above. Do nothing.
18090 }
18091 else if (PrevDecl && (Def = cast<EnumDecl>(Val: PrevDecl)->getDefinition())) {
18092 Diag(Loc, diag::ext_forward_ref_enum_def)
18093 << New;
18094 Diag(Def->getLocation(), diag::note_previous_definition);
18095 } else {
18096 unsigned DiagID = diag::ext_forward_ref_enum;
18097 if (getLangOpts().MSVCCompat)
18098 DiagID = diag::ext_ms_forward_ref_enum;
18099 else if (getLangOpts().CPlusPlus)
18100 DiagID = diag::err_forward_ref_enum;
18101 Diag(Loc, DiagID);
18102 }
18103 }
18104
18105 if (EnumUnderlying) {
18106 EnumDecl *ED = cast<EnumDecl>(Val: New);
18107 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
18108 ED->setIntegerTypeSourceInfo(TI);
18109 else
18110 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
18111 QualType EnumTy = ED->getIntegerType();
18112 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
18113 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
18114 : EnumTy);
18115 assert(ED->isComplete() && "enum with type should be complete");
18116 }
18117 } else {
18118 // struct/union/class
18119
18120 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18121 // struct X { int A; } D; D should chain to X.
18122 if (getLangOpts().CPlusPlus) {
18123 // FIXME: Look for a way to use RecordDecl for simple structs.
18124 New = CXXRecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18125 PrevDecl: cast_or_null<CXXRecordDecl>(Val: PrevDecl));
18126
18127 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18128 StdBadAlloc = cast<CXXRecordDecl>(Val: New);
18129 } else
18130 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18131 PrevDecl: cast_or_null<RecordDecl>(Val: PrevDecl));
18132 }
18133
18134 // Only C23 and later allow defining new types in 'offsetof()'.
18135 if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus &&
18136 !getLangOpts().C23)
18137 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18138 << (OOK == OOK_Macro) << New->getSourceRange();
18139
18140 // C++11 [dcl.type]p3:
18141 // A type-specifier-seq shall not define a class or enumeration [...].
18142 if (!Invalid && getLangOpts().CPlusPlus &&
18143 (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) {
18144 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18145 << Context.getTagDeclType(New);
18146 Invalid = true;
18147 }
18148
18149 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
18150 DC->getDeclKind() == Decl::Enum) {
18151 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18152 << Context.getTagDeclType(New);
18153 Invalid = true;
18154 }
18155
18156 // Maybe add qualifier info.
18157 if (SS.isNotEmpty()) {
18158 if (SS.isSet()) {
18159 // If this is either a declaration or a definition, check the
18160 // nested-name-specifier against the current context.
18161 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
18162 diagnoseQualifiedDeclaration(SS, DC, Name: OrigName, Loc,
18163 /*TemplateId=*/nullptr,
18164 IsMemberSpecialization: isMemberSpecialization))
18165 Invalid = true;
18166
18167 New->setQualifierInfo(SS.getWithLocInContext(Context));
18168 if (TemplateParameterLists.size() > 0) {
18169 New->setTemplateParameterListsInfo(Context, TPLists: TemplateParameterLists);
18170 }
18171 }
18172 else
18173 Invalid = true;
18174 }
18175
18176 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18177 // Add alignment attributes if necessary; these attributes are checked when
18178 // the ASTContext lays out the structure.
18179 //
18180 // It is important for implementing the correct semantics that this
18181 // happen here (in ActOnTag). The #pragma pack stack is
18182 // maintained as a result of parser callbacks which can occur at
18183 // many points during the parsing of a struct declaration (because
18184 // the #pragma tokens are effectively skipped over during the
18185 // parsing of the struct).
18186 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18187 AddAlignmentAttributesForRecord(RD);
18188 AddMsStructLayoutForRecord(RD);
18189 }
18190 }
18191
18192 if (ModulePrivateLoc.isValid()) {
18193 if (isMemberSpecialization)
18194 Diag(New->getLocation(), diag::err_module_private_specialization)
18195 << 2
18196 << FixItHint::CreateRemoval(ModulePrivateLoc);
18197 // __module_private__ does not apply to local classes. However, we only
18198 // diagnose this as an error when the declaration specifiers are
18199 // freestanding. Here, we just ignore the __module_private__.
18200 else if (!SearchDC->isFunctionOrMethod())
18201 New->setModulePrivate();
18202 }
18203
18204 // If this is a specialization of a member class (of a class template),
18205 // check the specialization.
18206 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18207 Invalid = true;
18208
18209 // If we're declaring or defining a tag in function prototype scope in C,
18210 // note that this type can only be used within the function and add it to
18211 // the list of decls to inject into the function definition scope.
18212 if ((Name || Kind == TagTypeKind::Enum) &&
18213 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18214 if (getLangOpts().CPlusPlus) {
18215 // C++ [dcl.fct]p6:
18216 // Types shall not be defined in return or parameter types.
18217 if (TUK == TUK_Definition && !IsTypeSpecifier) {
18218 Diag(Loc, diag::err_type_defined_in_param_type)
18219 << Name;
18220 Invalid = true;
18221 }
18222 } else if (!PrevDecl) {
18223 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
18224 }
18225 }
18226
18227 if (Invalid)
18228 New->setInvalidDecl();
18229
18230 // Set the lexical context. If the tag has a C++ scope specifier, the
18231 // lexical context will be different from the semantic context.
18232 New->setLexicalDeclContext(CurContext);
18233
18234 // Mark this as a friend decl if applicable.
18235 // In Microsoft mode, a friend declaration also acts as a forward
18236 // declaration so we always pass true to setObjectOfFriendDecl to make
18237 // the tag name visible.
18238 if (TUK == TUK_Friend)
18239 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18240
18241 // Set the access specifier.
18242 if (!Invalid && SearchDC->isRecord())
18243 SetMemberAccessSpecifier(New, PrevDecl, AS);
18244
18245 if (PrevDecl)
18246 CheckRedeclarationInModule(New, PrevDecl);
18247
18248 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
18249 New->startDefinition();
18250
18251 ProcessDeclAttributeList(S, New, Attrs);
18252 AddPragmaAttributes(S, New);
18253
18254 // If this has an identifier, add it to the scope stack.
18255 if (TUK == TUK_Friend) {
18256 // We might be replacing an existing declaration in the lookup tables;
18257 // if so, borrow its access specifier.
18258 if (PrevDecl)
18259 New->setAccess(PrevDecl->getAccess());
18260
18261 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18262 DC->makeDeclVisibleInContext(New);
18263 if (Name) // can be null along some error paths
18264 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18265 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18266 } else if (Name) {
18267 S = getNonFieldDeclScope(S);
18268 PushOnScopeChains(New, S, true);
18269 } else {
18270 CurContext->addDecl(New);
18271 }
18272
18273 // If this is the C FILE type, notify the AST context.
18274 if (IdentifierInfo *II = New->getIdentifier())
18275 if (!New->isInvalidDecl() &&
18276 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18277 II->isStr(Str: "FILE"))
18278 Context.setFILEDecl(New);
18279
18280 if (PrevDecl)
18281 mergeDeclAttributes(New, PrevDecl);
18282
18283 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: New)) {
18284 inferGslOwnerPointerAttribute(Record: CXXRD);
18285 inferNullableClassAttribute(CRD: CXXRD);
18286 }
18287
18288 // If there's a #pragma GCC visibility in scope, set the visibility of this
18289 // record.
18290 AddPushedVisibilityAttribute(New);
18291
18292 if (isMemberSpecialization && !New->isInvalidDecl())
18293 CompleteMemberSpecialization(New, Previous);
18294
18295 OwnedDecl = true;
18296 // In C++, don't return an invalid declaration. We can't recover well from
18297 // the cases where we make the type anonymous.
18298 if (Invalid && getLangOpts().CPlusPlus) {
18299 if (New->isBeingDefined())
18300 if (auto RD = dyn_cast<RecordDecl>(Val: New))
18301 RD->completeDefinition();
18302 return true;
18303 } else if (SkipBody && SkipBody->ShouldSkip) {
18304 return SkipBody->Previous;
18305 } else {
18306 return New;
18307 }
18308}
18309
18310void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
18311 AdjustDeclIfTemplate(Decl&: TagD);
18312 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18313
18314 // Enter the tag context.
18315 PushDeclContext(S, Tag);
18316
18317 ActOnDocumentableDecl(D: TagD);
18318
18319 // If there's a #pragma GCC visibility in scope, set the visibility of this
18320 // record.
18321 AddPushedVisibilityAttribute(Tag);
18322}
18323
18324bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
18325 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18326 return false;
18327
18328 // Make the previous decl visible.
18329 makeMergedDefinitionVisible(ND: SkipBody.Previous);
18330 return true;
18331}
18332
18333void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
18334 assert(IDecl->getLexicalParent() == CurContext &&
18335 "The next DeclContext should be lexically contained in the current one.");
18336 CurContext = IDecl;
18337}
18338
18339void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
18340 SourceLocation FinalLoc,
18341 bool IsFinalSpelledSealed,
18342 bool IsAbstract,
18343 SourceLocation LBraceLoc) {
18344 AdjustDeclIfTemplate(Decl&: TagD);
18345 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: TagD);
18346
18347 FieldCollector->StartClass();
18348
18349 if (!Record->getIdentifier())
18350 return;
18351
18352 if (IsAbstract)
18353 Record->markAbstract();
18354
18355 if (FinalLoc.isValid()) {
18356 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18357 IsFinalSpelledSealed
18358 ? FinalAttr::Keyword_sealed
18359 : FinalAttr::Keyword_final));
18360 }
18361 // C++ [class]p2:
18362 // [...] The class-name is also inserted into the scope of the
18363 // class itself; this is known as the injected-class-name. For
18364 // purposes of access checking, the injected-class-name is treated
18365 // as if it were a public member name.
18366 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18367 C: Context, TK: Record->getTagKind(), DC: CurContext, StartLoc: Record->getBeginLoc(),
18368 IdLoc: Record->getLocation(), Id: Record->getIdentifier(),
18369 /*PrevDecl=*/nullptr,
18370 /*DelayTypeCreation=*/true);
18371 Context.getTypeDeclType(InjectedClassName, Record);
18372 InjectedClassName->setImplicit();
18373 InjectedClassName->setAccess(AS_public);
18374 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18375 InjectedClassName->setDescribedClassTemplate(Template);
18376 PushOnScopeChains(InjectedClassName, S);
18377 assert(InjectedClassName->isInjectedClassName() &&
18378 "Broken injected-class-name");
18379}
18380
18381void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
18382 SourceRange BraceRange) {
18383 AdjustDeclIfTemplate(Decl&: TagD);
18384 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18385 Tag->setBraceRange(BraceRange);
18386
18387 // Make sure we "complete" the definition even it is invalid.
18388 if (Tag->isBeingDefined()) {
18389 assert(Tag->isInvalidDecl() && "We should already have completed it");
18390 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
18391 RD->completeDefinition();
18392 }
18393
18394 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
18395 FieldCollector->FinishClass();
18396 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18397 auto *Def = RD->getDefinition();
18398 assert(Def && "The record is expected to have a completed definition");
18399 unsigned NumInitMethods = 0;
18400 for (auto *Method : Def->methods()) {
18401 if (!Method->getIdentifier())
18402 continue;
18403 if (Method->getName() == "__init")
18404 NumInitMethods++;
18405 }
18406 if (NumInitMethods > 1 || !Def->hasInitMethod())
18407 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18408 }
18409 }
18410
18411 // Exit this scope of this tag's definition.
18412 PopDeclContext();
18413
18414 if (getCurLexicalContext()->isObjCContainer() &&
18415 Tag->getDeclContext()->isFileContext())
18416 Tag->setTopLevelDeclInObjCContainer();
18417
18418 // Notify the consumer that we've defined a tag.
18419 if (!Tag->isInvalidDecl())
18420 Consumer.HandleTagDeclDefinition(D: Tag);
18421
18422 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18423 // from XLs and instead matches the XL #pragma pack(1) behavior.
18424 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18425 AlignPackStack.hasValue()) {
18426 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18427 // Only diagnose #pragma align(packed).
18428 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18429 return;
18430 const RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag);
18431 if (!RD)
18432 return;
18433 // Only warn if there is at least 1 bitfield member.
18434 if (llvm::any_of(RD->fields(),
18435 [](const FieldDecl *FD) { return FD->isBitField(); }))
18436 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18437 }
18438}
18439
18440void Sema::ActOnObjCContainerFinishDefinition() {
18441 // Exit this scope of this interface definition.
18442 PopDeclContext();
18443}
18444
18445void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
18446 assert(ObjCCtx == CurContext && "Mismatch of container contexts");
18447 OriginalLexicalContext = ObjCCtx;
18448 ActOnObjCContainerFinishDefinition();
18449}
18450
18451void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
18452 ActOnObjCContainerStartDefinition(IDecl: ObjCCtx);
18453 OriginalLexicalContext = nullptr;
18454}
18455
18456void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
18457 AdjustDeclIfTemplate(Decl&: TagD);
18458 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18459 Tag->setInvalidDecl();
18460
18461 // Make sure we "complete" the definition even it is invalid.
18462 if (Tag->isBeingDefined()) {
18463 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
18464 RD->completeDefinition();
18465 }
18466
18467 // We're undoing ActOnTagStartDefinition here, not
18468 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18469 // the FieldCollector.
18470
18471 PopDeclContext();
18472}
18473
18474// Note that FieldName may be null for anonymous bitfields.
18475ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
18476 const IdentifierInfo *FieldName,
18477 QualType FieldTy, bool IsMsStruct,
18478 Expr *BitWidth) {
18479 assert(BitWidth);
18480 if (BitWidth->containsErrors())
18481 return ExprError();
18482
18483 // C99 6.7.2.1p4 - verify the field type.
18484 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18485 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18486 // Handle incomplete and sizeless types with a specific error.
18487 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18488 diag::err_field_incomplete_or_sizeless))
18489 return ExprError();
18490 if (FieldName)
18491 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18492 << FieldName << FieldTy << BitWidth->getSourceRange();
18493 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18494 << FieldTy << BitWidth->getSourceRange();
18495 } else if (DiagnoseUnexpandedParameterPack(E: const_cast<Expr *>(BitWidth),
18496 UPPC: UPPC_BitFieldWidth))
18497 return ExprError();
18498
18499 // If the bit-width is type- or value-dependent, don't try to check
18500 // it now.
18501 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18502 return BitWidth;
18503
18504 llvm::APSInt Value;
18505 ExprResult ICE = VerifyIntegerConstantExpression(E: BitWidth, Result: &Value, CanFold: AllowFold);
18506 if (ICE.isInvalid())
18507 return ICE;
18508 BitWidth = ICE.get();
18509
18510 // Zero-width bitfield is ok for anonymous field.
18511 if (Value == 0 && FieldName)
18512 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18513 << FieldName << BitWidth->getSourceRange();
18514
18515 if (Value.isSigned() && Value.isNegative()) {
18516 if (FieldName)
18517 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18518 << FieldName << toString(Value, 10);
18519 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18520 << toString(Value, 10);
18521 }
18522
18523 // The size of the bit-field must not exceed our maximum permitted object
18524 // size.
18525 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18526 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18527 << !FieldName << FieldName << toString(Value, 10);
18528 }
18529
18530 if (!FieldTy->isDependentType()) {
18531 uint64_t TypeStorageSize = Context.getTypeSize(T: FieldTy);
18532 uint64_t TypeWidth = Context.getIntWidth(T: FieldTy);
18533 bool BitfieldIsOverwide = Value.ugt(RHS: TypeWidth);
18534
18535 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18536 // ABI.
18537 bool CStdConstraintViolation =
18538 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18539 bool MSBitfieldViolation =
18540 Value.ugt(RHS: TypeStorageSize) &&
18541 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18542 if (CStdConstraintViolation || MSBitfieldViolation) {
18543 unsigned DiagWidth =
18544 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18545 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18546 << (bool)FieldName << FieldName << toString(Value, 10)
18547 << !CStdConstraintViolation << DiagWidth;
18548 }
18549
18550 // Warn on types where the user might conceivably expect to get all
18551 // specified bits as value bits: that's all integral types other than
18552 // 'bool'.
18553 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18554 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18555 << FieldName << toString(Value, 10)
18556 << (unsigned)TypeWidth;
18557 }
18558 }
18559
18560 return BitWidth;
18561}
18562
18563/// ActOnField - Each field of a C struct/union is passed into this in order
18564/// to create a FieldDecl object for it.
18565Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
18566 Declarator &D, Expr *BitfieldWidth) {
18567 FieldDecl *Res = HandleField(S, TagD: cast_if_present<RecordDecl>(Val: TagD), DeclStart,
18568 D, BitfieldWidth,
18569 /*InitStyle=*/ICIS_NoInit, AS: AS_public);
18570 return Res;
18571}
18572
18573/// HandleField - Analyze a field of a C struct or a C++ data member.
18574///
18575FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
18576 SourceLocation DeclStart,
18577 Declarator &D, Expr *BitWidth,
18578 InClassInitStyle InitStyle,
18579 AccessSpecifier AS) {
18580 if (D.isDecompositionDeclarator()) {
18581 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18582 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18583 << Decomp.getSourceRange();
18584 return nullptr;
18585 }
18586
18587 const IdentifierInfo *II = D.getIdentifier();
18588 SourceLocation Loc = DeclStart;
18589 if (II) Loc = D.getIdentifierLoc();
18590
18591 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18592 QualType T = TInfo->getType();
18593 if (getLangOpts().CPlusPlus) {
18594 CheckExtraCXXDefaultArguments(D);
18595
18596 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
18597 UPPC: UPPC_DataMemberType)) {
18598 D.setInvalidType();
18599 T = Context.IntTy;
18600 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18601 }
18602 }
18603
18604 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
18605
18606 if (D.getDeclSpec().isInlineSpecified())
18607 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18608 << getLangOpts().CPlusPlus17;
18609 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18610 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18611 diag::err_invalid_thread)
18612 << DeclSpec::getSpecifierName(TSCS);
18613
18614 // Check to see if this name was declared as a member previously
18615 NamedDecl *PrevDecl = nullptr;
18616 LookupResult Previous(*this, II, Loc, LookupMemberName,
18617 RedeclarationKind::ForVisibleRedeclaration);
18618 LookupName(R&: Previous, S);
18619 switch (Previous.getResultKind()) {
18620 case LookupResult::Found:
18621 case LookupResult::FoundUnresolvedValue:
18622 PrevDecl = Previous.getAsSingle<NamedDecl>();
18623 break;
18624
18625 case LookupResult::FoundOverloaded:
18626 PrevDecl = Previous.getRepresentativeDecl();
18627 break;
18628
18629 case LookupResult::NotFound:
18630 case LookupResult::NotFoundInCurrentInstantiation:
18631 case LookupResult::Ambiguous:
18632 break;
18633 }
18634 Previous.suppressDiagnostics();
18635
18636 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18637 // Maybe we will complain about the shadowed template parameter.
18638 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18639 // Just pretend that we didn't see the previous declaration.
18640 PrevDecl = nullptr;
18641 }
18642
18643 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18644 PrevDecl = nullptr;
18645
18646 bool Mutable
18647 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18648 SourceLocation TSSL = D.getBeginLoc();
18649 FieldDecl *NewFD
18650 = CheckFieldDecl(Name: II, T, TInfo, Record, Loc, Mutable, BitfieldWidth: BitWidth, InitStyle,
18651 TSSL, AS, PrevDecl, D: &D);
18652
18653 if (NewFD->isInvalidDecl())
18654 Record->setInvalidDecl();
18655
18656 if (D.getDeclSpec().isModulePrivateSpecified())
18657 NewFD->setModulePrivate();
18658
18659 if (NewFD->isInvalidDecl() && PrevDecl) {
18660 // Don't introduce NewFD into scope; there's already something
18661 // with the same name in the same scope.
18662 } else if (II) {
18663 PushOnScopeChains(NewFD, S);
18664 } else
18665 Record->addDecl(NewFD);
18666
18667 return NewFD;
18668}
18669
18670/// Build a new FieldDecl and check its well-formedness.
18671///
18672/// This routine builds a new FieldDecl given the fields name, type,
18673/// record, etc. \p PrevDecl should refer to any previous declaration
18674/// with the same name and in the same scope as the field to be
18675/// created.
18676///
18677/// \returns a new FieldDecl.
18678///
18679/// \todo The Declarator argument is a hack. It will be removed once
18680FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
18681 TypeSourceInfo *TInfo,
18682 RecordDecl *Record, SourceLocation Loc,
18683 bool Mutable, Expr *BitWidth,
18684 InClassInitStyle InitStyle,
18685 SourceLocation TSSL,
18686 AccessSpecifier AS, NamedDecl *PrevDecl,
18687 Declarator *D) {
18688 const IdentifierInfo *II = Name.getAsIdentifierInfo();
18689 bool InvalidDecl = false;
18690 if (D) InvalidDecl = D->isInvalidType();
18691
18692 // If we receive a broken type, recover by assuming 'int' and
18693 // marking this declaration as invalid.
18694 if (T.isNull() || T->containsErrors()) {
18695 InvalidDecl = true;
18696 T = Context.IntTy;
18697 }
18698
18699 QualType EltTy = Context.getBaseElementType(QT: T);
18700 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18701 if (RequireCompleteSizedType(Loc, EltTy,
18702 diag::err_field_incomplete_or_sizeless)) {
18703 // Fields of incomplete type force their record to be invalid.
18704 Record->setInvalidDecl();
18705 InvalidDecl = true;
18706 } else {
18707 NamedDecl *Def;
18708 EltTy->isIncompleteType(Def: &Def);
18709 if (Def && Def->isInvalidDecl()) {
18710 Record->setInvalidDecl();
18711 InvalidDecl = true;
18712 }
18713 }
18714 }
18715
18716 // TR 18037 does not allow fields to be declared with address space
18717 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18718 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
18719 Diag(Loc, diag::err_field_with_address_space);
18720 Record->setInvalidDecl();
18721 InvalidDecl = true;
18722 }
18723
18724 if (LangOpts.OpenCL) {
18725 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18726 // used as structure or union field: image, sampler, event or block types.
18727 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18728 T->isBlockPointerType()) {
18729 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18730 Record->setInvalidDecl();
18731 InvalidDecl = true;
18732 }
18733 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18734 // is enabled.
18735 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18736 Ext: "__cl_clang_bitfields", LO: LangOpts)) {
18737 Diag(Loc, diag::err_opencl_bitfields);
18738 InvalidDecl = true;
18739 }
18740 }
18741
18742 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18743 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18744 T.hasQualifiers()) {
18745 InvalidDecl = true;
18746 Diag(Loc, diag::err_anon_bitfield_qualifiers);
18747 }
18748
18749 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18750 // than a variably modified type.
18751 if (!InvalidDecl && T->isVariablyModifiedType()) {
18752 if (!tryToFixVariablyModifiedVarType(
18753 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18754 InvalidDecl = true;
18755 }
18756
18757 // Fields can not have abstract class types
18758 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18759 diag::err_abstract_type_in_decl,
18760 AbstractFieldType))
18761 InvalidDecl = true;
18762
18763 if (InvalidDecl)
18764 BitWidth = nullptr;
18765 // If this is declared as a bit-field, check the bit-field.
18766 if (BitWidth) {
18767 BitWidth =
18768 VerifyBitField(FieldLoc: Loc, FieldName: II, FieldTy: T, IsMsStruct: Record->isMsStruct(C: Context), BitWidth).get();
18769 if (!BitWidth) {
18770 InvalidDecl = true;
18771 BitWidth = nullptr;
18772 }
18773 }
18774
18775 // Check that 'mutable' is consistent with the type of the declaration.
18776 if (!InvalidDecl && Mutable) {
18777 unsigned DiagID = 0;
18778 if (T->isReferenceType())
18779 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18780 : diag::err_mutable_reference;
18781 else if (T.isConstQualified())
18782 DiagID = diag::err_mutable_const;
18783
18784 if (DiagID) {
18785 SourceLocation ErrLoc = Loc;
18786 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18787 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18788 Diag(ErrLoc, DiagID);
18789 if (DiagID != diag::ext_mutable_reference) {
18790 Mutable = false;
18791 InvalidDecl = true;
18792 }
18793 }
18794 }
18795
18796 // C++11 [class.union]p8 (DR1460):
18797 // At most one variant member of a union may have a
18798 // brace-or-equal-initializer.
18799 if (InitStyle != ICIS_NoInit)
18800 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Record), DefaultInitLoc: Loc);
18801
18802 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18803 BitWidth, Mutable, InitStyle);
18804 if (InvalidDecl)
18805 NewFD->setInvalidDecl();
18806
18807 if (PrevDecl && !isa<TagDecl>(Val: PrevDecl) &&
18808 !PrevDecl->isPlaceholderVar(LangOpts: getLangOpts())) {
18809 Diag(Loc, diag::err_duplicate_member) << II;
18810 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18811 NewFD->setInvalidDecl();
18812 }
18813
18814 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18815 if (Record->isUnion()) {
18816 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18817 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(Val: RT->getDecl());
18818 if (RDecl->getDefinition()) {
18819 // C++ [class.union]p1: An object of a class with a non-trivial
18820 // constructor, a non-trivial copy constructor, a non-trivial
18821 // destructor, or a non-trivial copy assignment operator
18822 // cannot be a member of a union, nor can an array of such
18823 // objects.
18824 if (CheckNontrivialField(FD: NewFD))
18825 NewFD->setInvalidDecl();
18826 }
18827 }
18828
18829 // C++ [class.union]p1: If a union contains a member of reference type,
18830 // the program is ill-formed, except when compiling with MSVC extensions
18831 // enabled.
18832 if (EltTy->isReferenceType()) {
18833 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18834 diag::ext_union_member_of_reference_type :
18835 diag::err_union_member_of_reference_type)
18836 << NewFD->getDeclName() << EltTy;
18837 if (!getLangOpts().MicrosoftExt)
18838 NewFD->setInvalidDecl();
18839 }
18840 }
18841 }
18842
18843 // FIXME: We need to pass in the attributes given an AST
18844 // representation, not a parser representation.
18845 if (D) {
18846 // FIXME: The current scope is almost... but not entirely... correct here.
18847 ProcessDeclAttributes(getCurScope(), NewFD, *D);
18848
18849 if (NewFD->hasAttrs())
18850 CheckAlignasUnderalignment(NewFD);
18851 }
18852
18853 // In auto-retain/release, infer strong retension for fields of
18854 // retainable type.
18855 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
18856 NewFD->setInvalidDecl();
18857
18858 if (T.isObjCGCWeak())
18859 Diag(Loc, diag::warn_attribute_weak_on_field);
18860
18861 // PPC MMA non-pointer types are not allowed as field types.
18862 if (Context.getTargetInfo().getTriple().isPPC64() &&
18863 CheckPPCMMAType(Type: T, TypeLoc: NewFD->getLocation()))
18864 NewFD->setInvalidDecl();
18865
18866 NewFD->setAccess(AS);
18867 return NewFD;
18868}
18869
18870bool Sema::CheckNontrivialField(FieldDecl *FD) {
18871 assert(FD);
18872 assert(getLangOpts().CPlusPlus && "valid check only for C++");
18873
18874 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18875 return false;
18876
18877 QualType EltTy = Context.getBaseElementType(FD->getType());
18878 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18879 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(Val: RT->getDecl());
18880 if (RDecl->getDefinition()) {
18881 // We check for copy constructors before constructors
18882 // because otherwise we'll never get complaints about
18883 // copy constructors.
18884
18885 CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;
18886 // We're required to check for any non-trivial constructors. Since the
18887 // implicit default constructor is suppressed if there are any
18888 // user-declared constructors, we just need to check that there is a
18889 // trivial default constructor and a trivial copy constructor. (We don't
18890 // worry about move constructors here, since this is a C++98 check.)
18891 if (RDecl->hasNonTrivialCopyConstructor())
18892 member = CXXSpecialMemberKind::CopyConstructor;
18893 else if (!RDecl->hasTrivialDefaultConstructor())
18894 member = CXXSpecialMemberKind::DefaultConstructor;
18895 else if (RDecl->hasNonTrivialCopyAssignment())
18896 member = CXXSpecialMemberKind::CopyAssignment;
18897 else if (RDecl->hasNonTrivialDestructor())
18898 member = CXXSpecialMemberKind::Destructor;
18899
18900 if (member != CXXSpecialMemberKind::Invalid) {
18901 if (!getLangOpts().CPlusPlus11 &&
18902 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18903 // Objective-C++ ARC: it is an error to have a non-trivial field of
18904 // a union. However, system headers in Objective-C programs
18905 // occasionally have Objective-C lifetime objects within unions,
18906 // and rather than cause the program to fail, we make those
18907 // members unavailable.
18908 SourceLocation Loc = FD->getLocation();
18909 if (getSourceManager().isInSystemHeader(Loc)) {
18910 if (!FD->hasAttr<UnavailableAttr>())
18911 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18912 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18913 return false;
18914 }
18915 }
18916
18917 Diag(
18918 FD->getLocation(),
18919 getLangOpts().CPlusPlus11
18920 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
18921 : diag::err_illegal_union_or_anon_struct_member)
18922 << FD->getParent()->isUnion() << FD->getDeclName()
18923 << llvm::to_underlying(member);
18924 DiagnoseNontrivial(Record: RDecl, CSM: member);
18925 return !getLangOpts().CPlusPlus11;
18926 }
18927 }
18928 }
18929
18930 return false;
18931}
18932
18933/// TranslateIvarVisibility - Translate visibility from a token ID to an
18934/// AST enum value.
18935static ObjCIvarDecl::AccessControl
18936TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
18937 switch (ivarVisibility) {
18938 default: llvm_unreachable("Unknown visitibility kind");
18939 case tok::objc_private: return ObjCIvarDecl::Private;
18940 case tok::objc_public: return ObjCIvarDecl::Public;
18941 case tok::objc_protected: return ObjCIvarDecl::Protected;
18942 case tok::objc_package: return ObjCIvarDecl::Package;
18943 }
18944}
18945
18946/// ActOnIvar - Each ivar field of an objective-c class is passed into this
18947/// in order to create an IvarDecl object for it.
18948Decl *Sema::ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D,
18949 Expr *BitWidth, tok::ObjCKeywordKind Visibility) {
18950
18951 const IdentifierInfo *II = D.getIdentifier();
18952 SourceLocation Loc = DeclStart;
18953 if (II) Loc = D.getIdentifierLoc();
18954
18955 // FIXME: Unnamed fields can be handled in various different ways, for
18956 // example, unnamed unions inject all members into the struct namespace!
18957
18958 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18959 QualType T = TInfo->getType();
18960
18961 if (BitWidth) {
18962 // 6.7.2.1p3, 6.7.2.1p4
18963 BitWidth = VerifyBitField(FieldLoc: Loc, FieldName: II, FieldTy: T, /*IsMsStruct*/false, BitWidth).get();
18964 if (!BitWidth)
18965 D.setInvalidType();
18966 } else {
18967 // Not a bitfield.
18968
18969 // validate II.
18970
18971 }
18972 if (T->isReferenceType()) {
18973 Diag(Loc, diag::err_ivar_reference_type);
18974 D.setInvalidType();
18975 }
18976 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18977 // than a variably modified type.
18978 else if (T->isVariablyModifiedType()) {
18979 if (!tryToFixVariablyModifiedVarType(
18980 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
18981 D.setInvalidType();
18982 }
18983
18984 // Get the visibility (access control) for this ivar.
18985 ObjCIvarDecl::AccessControl ac =
18986 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(ivarVisibility: Visibility)
18987 : ObjCIvarDecl::None;
18988 // Must set ivar's DeclContext to its enclosing interface.
18989 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(Val: CurContext);
18990 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
18991 return nullptr;
18992 ObjCContainerDecl *EnclosingContext;
18993 if (ObjCImplementationDecl *IMPDecl =
18994 dyn_cast<ObjCImplementationDecl>(Val: EnclosingDecl)) {
18995 if (LangOpts.ObjCRuntime.isFragile()) {
18996 // Case of ivar declared in an implementation. Context is that of its class.
18997 EnclosingContext = IMPDecl->getClassInterface();
18998 assert(EnclosingContext && "Implementation has no class interface!");
18999 }
19000 else
19001 EnclosingContext = EnclosingDecl;
19002 } else {
19003 if (ObjCCategoryDecl *CDecl =
19004 dyn_cast<ObjCCategoryDecl>(Val: EnclosingDecl)) {
19005 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
19006 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
19007 return nullptr;
19008 }
19009 }
19010 EnclosingContext = EnclosingDecl;
19011 }
19012
19013 // Construct the decl.
19014 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(
19015 C&: Context, DC: EnclosingContext, StartLoc: DeclStart, IdLoc: Loc, Id: II, T, TInfo, ac, BW: BitWidth);
19016
19017 if (T->containsErrors())
19018 NewID->setInvalidDecl();
19019
19020 if (II) {
19021 NamedDecl *PrevDecl =
19022 LookupSingleName(S, Name: II, Loc, NameKind: LookupMemberName,
19023 Redecl: RedeclarationKind::ForVisibleRedeclaration);
19024 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
19025 && !isa<TagDecl>(Val: PrevDecl)) {
19026 Diag(Loc, diag::err_duplicate_member) << II;
19027 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
19028 NewID->setInvalidDecl();
19029 }
19030 }
19031
19032 // Process attributes attached to the ivar.
19033 ProcessDeclAttributes(S, NewID, D);
19034
19035 if (D.isInvalidType())
19036 NewID->setInvalidDecl();
19037
19038 // In ARC, infer 'retaining' for ivars of retainable type.
19039 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
19040 NewID->setInvalidDecl();
19041
19042 if (D.getDeclSpec().isModulePrivateSpecified())
19043 NewID->setModulePrivate();
19044
19045 if (II) {
19046 // FIXME: When interfaces are DeclContexts, we'll need to add
19047 // these to the interface.
19048 S->AddDecl(NewID);
19049 IdResolver.AddDecl(NewID);
19050 }
19051
19052 if (LangOpts.ObjCRuntime.isNonFragile() &&
19053 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
19054 Diag(Loc, diag::warn_ivars_in_interface);
19055
19056 return NewID;
19057}
19058
19059/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
19060/// class and class extensions. For every class \@interface and class
19061/// extension \@interface, if the last ivar is a bitfield of any type,
19062/// then add an implicit `char :0` ivar to the end of that interface.
19063void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
19064 SmallVectorImpl<Decl *> &AllIvarDecls) {
19065 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19066 return;
19067
19068 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19069 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Val: ivarDecl);
19070
19071 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
19072 return;
19073 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: CurContext);
19074 if (!ID) {
19075 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(Val: CurContext)) {
19076 if (!CD->IsClassExtension())
19077 return;
19078 }
19079 // No need to add this to end of @implementation.
19080 else
19081 return;
19082 }
19083 // All conditions are met. Add a new bitfield to the tail end of ivars.
19084 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19085 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
19086
19087 Ivar = ObjCIvarDecl::Create(C&: Context, DC: cast<ObjCContainerDecl>(Val: CurContext),
19088 StartLoc: DeclLoc, IdLoc: DeclLoc, Id: nullptr,
19089 T: Context.CharTy,
19090 TInfo: Context.getTrivialTypeSourceInfo(T: Context.CharTy,
19091 Loc: DeclLoc),
19092 ac: ObjCIvarDecl::Private, BW,
19093 synthesized: true);
19094 AllIvarDecls.push_back(Ivar);
19095}
19096
19097/// [class.dtor]p4:
19098/// At the end of the definition of a class, overload resolution is
19099/// performed among the prospective destructors declared in that class with
19100/// an empty argument list to select the destructor for the class, also
19101/// known as the selected destructor.
19102///
19103/// We do the overload resolution here, then mark the selected constructor in the AST.
19104/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19105static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
19106 if (!Record->hasUserDeclaredDestructor()) {
19107 return;
19108 }
19109
19110 SourceLocation Loc = Record->getLocation();
19111 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
19112
19113 for (auto *Decl : Record->decls()) {
19114 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19115 if (DD->isInvalidDecl())
19116 continue;
19117 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19118 OCS);
19119 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19120 }
19121 }
19122
19123 if (OCS.empty()) {
19124 return;
19125 }
19126 OverloadCandidateSet::iterator Best;
19127 unsigned Msg = 0;
19128 OverloadCandidateDisplayKind DisplayKind;
19129
19130 switch (OCS.BestViableFunction(S, Loc, Best)) {
19131 case OR_Success:
19132 case OR_Deleted:
19133 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: Best->Function));
19134 break;
19135
19136 case OR_Ambiguous:
19137 Msg = diag::err_ambiguous_destructor;
19138 DisplayKind = OCD_AmbiguousCandidates;
19139 break;
19140
19141 case OR_No_Viable_Function:
19142 Msg = diag::err_no_viable_destructor;
19143 DisplayKind = OCD_AllCandidates;
19144 break;
19145 }
19146
19147 if (Msg) {
19148 // OpenCL have got their own thing going with destructors. It's slightly broken,
19149 // but we allow it.
19150 if (!S.LangOpts.OpenCL) {
19151 PartialDiagnostic Diag = S.PDiag(DiagID: Msg) << Record;
19152 OCS.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, OCD: DisplayKind, Args: {});
19153 Record->setInvalidDecl();
19154 }
19155 // It's a bit hacky: At this point we've raised an error but we want the
19156 // rest of the compiler to continue somehow working. However almost
19157 // everything we'll try to do with the class will depend on there being a
19158 // destructor. So let's pretend the first one is selected and hope for the
19159 // best.
19160 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: OCS.begin()->Function));
19161 }
19162}
19163
19164/// [class.mem.special]p5
19165/// Two special member functions are of the same kind if:
19166/// - they are both default constructors,
19167/// - they are both copy or move constructors with the same first parameter
19168/// type, or
19169/// - they are both copy or move assignment operators with the same first
19170/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19171static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
19172 CXXMethodDecl *M1,
19173 CXXMethodDecl *M2,
19174 CXXSpecialMemberKind CSM) {
19175 // We don't want to compare templates to non-templates: See
19176 // https://github.com/llvm/llvm-project/issues/59206
19177 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
19178 return bool(M1->getDescribedFunctionTemplate()) ==
19179 bool(M2->getDescribedFunctionTemplate());
19180 // FIXME: better resolve CWG
19181 // https://cplusplus.github.io/CWG/issues/2787.html
19182 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
19183 M2->getNonObjectParameter(0)->getType()))
19184 return false;
19185 if (!Context.hasSameType(T1: M1->getFunctionObjectParameterReferenceType(),
19186 T2: M2->getFunctionObjectParameterReferenceType()))
19187 return false;
19188
19189 return true;
19190}
19191
19192/// [class.mem.special]p6:
19193/// An eligible special member function is a special member function for which:
19194/// - the function is not deleted,
19195/// - the associated constraints, if any, are satisfied, and
19196/// - no special member function of the same kind whose associated constraints
19197/// [CWG2595], if any, are satisfied is more constrained.
19198static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
19199 ArrayRef<CXXMethodDecl *> Methods,
19200 CXXSpecialMemberKind CSM) {
19201 SmallVector<bool, 4> SatisfactionStatus;
19202
19203 for (CXXMethodDecl *Method : Methods) {
19204 const Expr *Constraints = Method->getTrailingRequiresClause();
19205 if (!Constraints)
19206 SatisfactionStatus.push_back(Elt: true);
19207 else {
19208 ConstraintSatisfaction Satisfaction;
19209 if (S.CheckFunctionConstraints(Method, Satisfaction))
19210 SatisfactionStatus.push_back(Elt: false);
19211 else
19212 SatisfactionStatus.push_back(Elt: Satisfaction.IsSatisfied);
19213 }
19214 }
19215
19216 for (size_t i = 0; i < Methods.size(); i++) {
19217 if (!SatisfactionStatus[i])
19218 continue;
19219 CXXMethodDecl *Method = Methods[i];
19220 CXXMethodDecl *OrigMethod = Method;
19221 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19222 OrigMethod = cast<CXXMethodDecl>(Val: MF);
19223
19224 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
19225 bool AnotherMethodIsMoreConstrained = false;
19226 for (size_t j = 0; j < Methods.size(); j++) {
19227 if (i == j || !SatisfactionStatus[j])
19228 continue;
19229 CXXMethodDecl *OtherMethod = Methods[j];
19230 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19231 OtherMethod = cast<CXXMethodDecl>(Val: MF);
19232
19233 if (!AreSpecialMemberFunctionsSameKind(Context&: S.Context, M1: OrigMethod, M2: OtherMethod,
19234 CSM))
19235 continue;
19236
19237 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
19238 if (!OtherConstraints)
19239 continue;
19240 if (!Constraints) {
19241 AnotherMethodIsMoreConstrained = true;
19242 break;
19243 }
19244 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
19245 {Constraints},
19246 AnotherMethodIsMoreConstrained)) {
19247 // There was an error with the constraints comparison. Exit the loop
19248 // and don't consider this function eligible.
19249 AnotherMethodIsMoreConstrained = true;
19250 }
19251 if (AnotherMethodIsMoreConstrained)
19252 break;
19253 }
19254 // FIXME: Do not consider deleted methods as eligible after implementing
19255 // DR1734 and DR1496.
19256 if (!AnotherMethodIsMoreConstrained) {
19257 Method->setIneligibleOrNotSelected(false);
19258 Record->addedEligibleSpecialMemberFunction(MD: Method,
19259 SMKind: 1 << llvm::to_underlying(E: CSM));
19260 }
19261 }
19262}
19263
19264static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
19265 CXXRecordDecl *Record) {
19266 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19267 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19268 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19269 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19270 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19271
19272 for (auto *Decl : Record->decls()) {
19273 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19274 if (!MD) {
19275 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19276 if (FTD)
19277 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19278 }
19279 if (!MD)
19280 continue;
19281 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19282 if (CD->isInvalidDecl())
19283 continue;
19284 if (CD->isDefaultConstructor())
19285 DefaultConstructors.push_back(MD);
19286 else if (CD->isCopyConstructor())
19287 CopyConstructors.push_back(MD);
19288 else if (CD->isMoveConstructor())
19289 MoveConstructors.push_back(MD);
19290 } else if (MD->isCopyAssignmentOperator()) {
19291 CopyAssignmentOperators.push_back(MD);
19292 } else if (MD->isMoveAssignmentOperator()) {
19293 MoveAssignmentOperators.push_back(MD);
19294 }
19295 }
19296
19297 SetEligibleMethods(S, Record, Methods: DefaultConstructors,
19298 CSM: CXXSpecialMemberKind::DefaultConstructor);
19299 SetEligibleMethods(S, Record, Methods: CopyConstructors,
19300 CSM: CXXSpecialMemberKind::CopyConstructor);
19301 SetEligibleMethods(S, Record, Methods: MoveConstructors,
19302 CSM: CXXSpecialMemberKind::MoveConstructor);
19303 SetEligibleMethods(S, Record, Methods: CopyAssignmentOperators,
19304 CSM: CXXSpecialMemberKind::CopyAssignment);
19305 SetEligibleMethods(S, Record, Methods: MoveAssignmentOperators,
19306 CSM: CXXSpecialMemberKind::MoveAssignment);
19307}
19308
19309void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19310 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19311 SourceLocation RBrac,
19312 const ParsedAttributesView &Attrs) {
19313 assert(EnclosingDecl && "missing record or interface decl");
19314
19315 // If this is an Objective-C @implementation or category and we have
19316 // new fields here we should reset the layout of the interface since
19317 // it will now change.
19318 if (!Fields.empty() && isa<ObjCContainerDecl>(Val: EnclosingDecl)) {
19319 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(Val: EnclosingDecl);
19320 switch (DC->getKind()) {
19321 default: break;
19322 case Decl::ObjCCategory:
19323 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(Val: DC)->getClassInterface());
19324 break;
19325 case Decl::ObjCImplementation:
19326 Context.
19327 ResetObjCLayout(CD: cast<ObjCImplementationDecl>(Val: DC)->getClassInterface());
19328 break;
19329 }
19330 }
19331
19332 RecordDecl *Record = dyn_cast<RecordDecl>(Val: EnclosingDecl);
19333 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Val: EnclosingDecl);
19334
19335 // Start counting up the number of named members; make sure to include
19336 // members of anonymous structs and unions in the total.
19337 unsigned NumNamedMembers = 0;
19338 if (Record) {
19339 for (const auto *I : Record->decls()) {
19340 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19341 if (IFD->getDeclName())
19342 ++NumNamedMembers;
19343 }
19344 }
19345
19346 // Verify that all the fields are okay.
19347 SmallVector<FieldDecl*, 32> RecFields;
19348
19349 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19350 i != end; ++i) {
19351 FieldDecl *FD = cast<FieldDecl>(Val: *i);
19352
19353 // Get the type for the field.
19354 const Type *FDTy = FD->getType().getTypePtr();
19355
19356 if (!FD->isAnonymousStructOrUnion()) {
19357 // Remember all fields written by the user.
19358 RecFields.push_back(Elt: FD);
19359 }
19360
19361 // If the field is already invalid for some reason, don't emit more
19362 // diagnostics about it.
19363 if (FD->isInvalidDecl()) {
19364 EnclosingDecl->setInvalidDecl();
19365 continue;
19366 }
19367
19368 // C99 6.7.2.1p2:
19369 // A structure or union shall not contain a member with
19370 // incomplete or function type (hence, a structure shall not
19371 // contain an instance of itself, but may contain a pointer to
19372 // an instance of itself), except that the last member of a
19373 // structure with more than one named member may have incomplete
19374 // array type; such a structure (and any union containing,
19375 // possibly recursively, a member that is such a structure)
19376 // shall not be a member of a structure or an element of an
19377 // array.
19378 bool IsLastField = (i + 1 == Fields.end());
19379 if (FDTy->isFunctionType()) {
19380 // Field declared as a function.
19381 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19382 << FD->getDeclName();
19383 FD->setInvalidDecl();
19384 EnclosingDecl->setInvalidDecl();
19385 continue;
19386 } else if (FDTy->isIncompleteArrayType() &&
19387 (Record || isa<ObjCContainerDecl>(Val: EnclosingDecl))) {
19388 if (Record) {
19389 // Flexible array member.
19390 // Microsoft and g++ is more permissive regarding flexible array.
19391 // It will accept flexible array in union and also
19392 // as the sole element of a struct/class.
19393 unsigned DiagID = 0;
19394 if (!Record->isUnion() && !IsLastField) {
19395 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19396 << FD->getDeclName() << FD->getType()
19397 << llvm::to_underlying(Record->getTagKind());
19398 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19399 FD->setInvalidDecl();
19400 EnclosingDecl->setInvalidDecl();
19401 continue;
19402 } else if (Record->isUnion())
19403 DiagID = getLangOpts().MicrosoftExt
19404 ? diag::ext_flexible_array_union_ms
19405 : diag::ext_flexible_array_union_gnu;
19406 else if (NumNamedMembers < 1)
19407 DiagID = getLangOpts().MicrosoftExt
19408 ? diag::ext_flexible_array_empty_aggregate_ms
19409 : diag::ext_flexible_array_empty_aggregate_gnu;
19410
19411 if (DiagID)
19412 Diag(FD->getLocation(), DiagID)
19413 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19414 // While the layout of types that contain virtual bases is not specified
19415 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19416 // virtual bases after the derived members. This would make a flexible
19417 // array member declared at the end of an object not adjacent to the end
19418 // of the type.
19419 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19420 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19421 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19422 if (!getLangOpts().C99)
19423 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19424 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19425
19426 // If the element type has a non-trivial destructor, we would not
19427 // implicitly destroy the elements, so disallow it for now.
19428 //
19429 // FIXME: GCC allows this. We should probably either implicitly delete
19430 // the destructor of the containing class, or just allow this.
19431 QualType BaseElem = Context.getBaseElementType(FD->getType());
19432 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19433 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19434 << FD->getDeclName() << FD->getType();
19435 FD->setInvalidDecl();
19436 EnclosingDecl->setInvalidDecl();
19437 continue;
19438 }
19439 // Okay, we have a legal flexible array member at the end of the struct.
19440 Record->setHasFlexibleArrayMember(true);
19441 } else {
19442 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19443 // unless they are followed by another ivar. That check is done
19444 // elsewhere, after synthesized ivars are known.
19445 }
19446 } else if (!FDTy->isDependentType() &&
19447 RequireCompleteSizedType(
19448 FD->getLocation(), FD->getType(),
19449 diag::err_field_incomplete_or_sizeless)) {
19450 // Incomplete type
19451 FD->setInvalidDecl();
19452 EnclosingDecl->setInvalidDecl();
19453 continue;
19454 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19455 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
19456 // A type which contains a flexible array member is considered to be a
19457 // flexible array member.
19458 Record->setHasFlexibleArrayMember(true);
19459 if (!Record->isUnion()) {
19460 // If this is a struct/class and this is not the last element, reject
19461 // it. Note that GCC supports variable sized arrays in the middle of
19462 // structures.
19463 if (!IsLastField)
19464 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19465 << FD->getDeclName() << FD->getType();
19466 else {
19467 // We support flexible arrays at the end of structs in
19468 // other structs as an extension.
19469 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19470 << FD->getDeclName();
19471 }
19472 }
19473 }
19474 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19475 RequireNonAbstractType(FD->getLocation(), FD->getType(),
19476 diag::err_abstract_type_in_decl,
19477 AbstractIvarType)) {
19478 // Ivars can not have abstract class types
19479 FD->setInvalidDecl();
19480 }
19481 if (Record && FDTTy->getDecl()->hasObjectMember())
19482 Record->setHasObjectMember(true);
19483 if (Record && FDTTy->getDecl()->hasVolatileMember())
19484 Record->setHasVolatileMember(true);
19485 } else if (FDTy->isObjCObjectType()) {
19486 /// A field cannot be an Objective-c object
19487 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19488 << FixItHint::CreateInsertion(FD->getLocation(), "*");
19489 QualType T = Context.getObjCObjectPointerType(OIT: FD->getType());
19490 FD->setType(T);
19491 } else if (Record && Record->isUnion() &&
19492 FD->getType().hasNonTrivialObjCLifetime() &&
19493 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19494 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19495 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
19496 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
19497 // For backward compatibility, fields of C unions declared in system
19498 // headers that have non-trivial ObjC ownership qualifications are marked
19499 // as unavailable unless the qualifier is explicit and __strong. This can
19500 // break ABI compatibility between programs compiled with ARC and MRR, but
19501 // is a better option than rejecting programs using those unions under
19502 // ARC.
19503 FD->addAttr(UnavailableAttr::CreateImplicit(
19504 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19505 FD->getLocation()));
19506 } else if (getLangOpts().ObjC &&
19507 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19508 !Record->hasObjectMember()) {
19509 if (FD->getType()->isObjCObjectPointerType() ||
19510 FD->getType().isObjCGCStrong())
19511 Record->setHasObjectMember(true);
19512 else if (Context.getAsArrayType(T: FD->getType())) {
19513 QualType BaseType = Context.getBaseElementType(FD->getType());
19514 if (BaseType->isRecordType() &&
19515 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19516 Record->setHasObjectMember(true);
19517 else if (BaseType->isObjCObjectPointerType() ||
19518 BaseType.isObjCGCStrong())
19519 Record->setHasObjectMember(true);
19520 }
19521 }
19522
19523 if (Record && !getLangOpts().CPlusPlus &&
19524 !shouldIgnoreForRecordTriviality(FD)) {
19525 QualType FT = FD->getType();
19526 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
19527 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19528 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
19529 Record->isUnion())
19530 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19531 }
19532 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
19533 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
19534 Record->setNonTrivialToPrimitiveCopy(true);
19535 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19536 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19537 }
19538 if (FT.isDestructedType()) {
19539 Record->setNonTrivialToPrimitiveDestroy(true);
19540 Record->setParamDestroyedInCallee(true);
19541 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19542 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19543 }
19544
19545 if (const auto *RT = FT->getAs<RecordType>()) {
19546 if (RT->getDecl()->getArgPassingRestrictions() ==
19547 RecordArgPassingKind::CanNeverPassInRegs)
19548 Record->setArgPassingRestrictions(
19549 RecordArgPassingKind::CanNeverPassInRegs);
19550 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
19551 Record->setArgPassingRestrictions(
19552 RecordArgPassingKind::CanNeverPassInRegs);
19553 }
19554
19555 if (Record && FD->getType().isVolatileQualified())
19556 Record->setHasVolatileMember(true);
19557 // Keep track of the number of named members.
19558 if (FD->getIdentifier())
19559 ++NumNamedMembers;
19560 }
19561
19562 // Okay, we successfully defined 'Record'.
19563 if (Record) {
19564 bool Completed = false;
19565 if (S) {
19566 Scope *Parent = S->getParent();
19567 if (Parent && Parent->isTypeAliasScope() &&
19568 Parent->isTemplateParamScope())
19569 Record->setInvalidDecl();
19570 }
19571
19572 if (CXXRecord) {
19573 if (!CXXRecord->isInvalidDecl()) {
19574 // Set access bits correctly on the directly-declared conversions.
19575 for (CXXRecordDecl::conversion_iterator
19576 I = CXXRecord->conversion_begin(),
19577 E = CXXRecord->conversion_end(); I != E; ++I)
19578 I.setAccess((*I)->getAccess());
19579 }
19580
19581 // Add any implicitly-declared members to this class.
19582 AddImplicitlyDeclaredMembersToClass(ClassDecl: CXXRecord);
19583
19584 if (!CXXRecord->isDependentType()) {
19585 if (!CXXRecord->isInvalidDecl()) {
19586 // If we have virtual base classes, we may end up finding multiple
19587 // final overriders for a given virtual function. Check for this
19588 // problem now.
19589 if (CXXRecord->getNumVBases()) {
19590 CXXFinalOverriderMap FinalOverriders;
19591 CXXRecord->getFinalOverriders(FinaOverriders&: FinalOverriders);
19592
19593 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19594 MEnd = FinalOverriders.end();
19595 M != MEnd; ++M) {
19596 for (OverridingMethods::iterator SO = M->second.begin(),
19597 SOEnd = M->second.end();
19598 SO != SOEnd; ++SO) {
19599 assert(SO->second.size() > 0 &&
19600 "Virtual function without overriding functions?");
19601 if (SO->second.size() == 1)
19602 continue;
19603
19604 // C++ [class.virtual]p2:
19605 // In a derived class, if a virtual member function of a base
19606 // class subobject has more than one final overrider the
19607 // program is ill-formed.
19608 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19609 << (const NamedDecl *)M->first << Record;
19610 Diag(M->first->getLocation(),
19611 diag::note_overridden_virtual_function);
19612 for (OverridingMethods::overriding_iterator
19613 OM = SO->second.begin(),
19614 OMEnd = SO->second.end();
19615 OM != OMEnd; ++OM)
19616 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19617 << (const NamedDecl *)M->first << OM->Method->getParent();
19618
19619 Record->setInvalidDecl();
19620 }
19621 }
19622 CXXRecord->completeDefinition(FinalOverriders: &FinalOverriders);
19623 Completed = true;
19624 }
19625 }
19626 ComputeSelectedDestructor(S&: *this, Record: CXXRecord);
19627 ComputeSpecialMemberFunctionsEligiblity(S&: *this, Record: CXXRecord);
19628 }
19629 }
19630
19631 if (!Completed)
19632 Record->completeDefinition();
19633
19634 // Handle attributes before checking the layout.
19635 ProcessDeclAttributeList(S, Record, Attrs);
19636
19637 // Check to see if a FieldDecl is a pointer to a function.
19638 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19639 const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
19640 if (!FD) {
19641 // Check whether this is a forward declaration that was inserted by
19642 // Clang. This happens when a non-forward declared / defined type is
19643 // used, e.g.:
19644 //
19645 // struct foo {
19646 // struct bar *(*f)();
19647 // struct bar *(*g)();
19648 // };
19649 //
19650 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19651 // incomplete definition.
19652 if (const auto *TD = dyn_cast<TagDecl>(Val: D))
19653 return !TD->isCompleteDefinition();
19654 return false;
19655 }
19656 QualType FieldType = FD->getType().getDesugaredType(Context);
19657 if (isa<PointerType>(Val: FieldType)) {
19658 QualType PointeeType = cast<PointerType>(Val&: FieldType)->getPointeeType();
19659 return PointeeType.getDesugaredType(Context)->isFunctionType();
19660 }
19661 return false;
19662 };
19663
19664 // Maybe randomize the record's decls. We automatically randomize a record
19665 // of function pointers, unless it has the "no_randomize_layout" attribute.
19666 if (!getLangOpts().CPlusPlus &&
19667 (Record->hasAttr<RandomizeLayoutAttr>() ||
19668 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19669 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19670 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19671 !Record->isRandomized()) {
19672 SmallVector<Decl *, 32> NewDeclOrdering;
19673 if (randstruct::randomizeStructureLayout(Context, RD: Record,
19674 FinalOrdering&: NewDeclOrdering))
19675 Record->reorderDecls(Decls: NewDeclOrdering);
19676 }
19677
19678 // We may have deferred checking for a deleted destructor. Check now.
19679 if (CXXRecord) {
19680 auto *Dtor = CXXRecord->getDestructor();
19681 if (Dtor && Dtor->isImplicit() &&
19682 ShouldDeleteSpecialMember(Dtor, CXXSpecialMemberKind::Destructor)) {
19683 CXXRecord->setImplicitDestructorIsDeleted();
19684 SetDeclDeleted(dcl: Dtor, DelLoc: CXXRecord->getLocation());
19685 }
19686 }
19687
19688 if (Record->hasAttrs()) {
19689 CheckAlignasUnderalignment(Record);
19690
19691 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19692 checkMSInheritanceAttrOnDefinition(RD: cast<CXXRecordDecl>(Val: Record),
19693 Range: IA->getRange(), BestCase: IA->getBestCase(),
19694 SemanticSpelling: IA->getInheritanceModel());
19695 }
19696
19697 // Check if the structure/union declaration is a type that can have zero
19698 // size in C. For C this is a language extension, for C++ it may cause
19699 // compatibility problems.
19700 bool CheckForZeroSize;
19701 if (!getLangOpts().CPlusPlus) {
19702 CheckForZeroSize = true;
19703 } else {
19704 // For C++ filter out types that cannot be referenced in C code.
19705 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record);
19706 CheckForZeroSize =
19707 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19708 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19709 CXXRecord->isCLike();
19710 }
19711 if (CheckForZeroSize) {
19712 bool ZeroSize = true;
19713 bool IsEmpty = true;
19714 unsigned NonBitFields = 0;
19715 for (RecordDecl::field_iterator I = Record->field_begin(),
19716 E = Record->field_end();
19717 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19718 IsEmpty = false;
19719 if (I->isUnnamedBitField()) {
19720 if (!I->isZeroLengthBitField(Ctx: Context))
19721 ZeroSize = false;
19722 } else {
19723 ++NonBitFields;
19724 QualType FieldType = I->getType();
19725 if (FieldType->isIncompleteType() ||
19726 !Context.getTypeSizeInChars(T: FieldType).isZero())
19727 ZeroSize = false;
19728 }
19729 }
19730
19731 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19732 // allowed in C++, but warn if its declaration is inside
19733 // extern "C" block.
19734 if (ZeroSize) {
19735 Diag(RecLoc, getLangOpts().CPlusPlus ?
19736 diag::warn_zero_size_struct_union_in_extern_c :
19737 diag::warn_zero_size_struct_union_compat)
19738 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19739 }
19740
19741 // Structs without named members are extension in C (C99 6.7.2.1p7),
19742 // but are accepted by GCC.
19743 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
19744 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
19745 diag::ext_no_named_members_in_struct_union)
19746 << Record->isUnion();
19747 }
19748 }
19749 } else {
19750 ObjCIvarDecl **ClsFields =
19751 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19752 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: EnclosingDecl)) {
19753 ID->setEndOfDefinitionLoc(RBrac);
19754 // Add ivar's to class's DeclContext.
19755 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19756 ClsFields[i]->setLexicalDeclContext(ID);
19757 ID->addDecl(ClsFields[i]);
19758 }
19759 // Must enforce the rule that ivars in the base classes may not be
19760 // duplicates.
19761 if (ID->getSuperClass())
19762 DiagnoseDuplicateIvars(ID, SID: ID->getSuperClass());
19763 } else if (ObjCImplementationDecl *IMPDecl =
19764 dyn_cast<ObjCImplementationDecl>(Val: EnclosingDecl)) {
19765 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19766 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19767 // Ivar declared in @implementation never belongs to the implementation.
19768 // Only it is in implementation's lexical context.
19769 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19770 CheckImplementationIvars(ImpDecl: IMPDecl, Fields: ClsFields, nIvars: RecFields.size(), Loc: RBrac);
19771 IMPDecl->setIvarLBraceLoc(LBrac);
19772 IMPDecl->setIvarRBraceLoc(RBrac);
19773 } else if (ObjCCategoryDecl *CDecl =
19774 dyn_cast<ObjCCategoryDecl>(Val: EnclosingDecl)) {
19775 // case of ivars in class extension; all other cases have been
19776 // reported as errors elsewhere.
19777 // FIXME. Class extension does not have a LocEnd field.
19778 // CDecl->setLocEnd(RBrac);
19779 // Add ivar's to class extension's DeclContext.
19780 // Diagnose redeclaration of private ivars.
19781 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19782 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19783 if (IDecl) {
19784 if (const ObjCIvarDecl *ClsIvar =
19785 IDecl->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
19786 Diag(ClsFields[i]->getLocation(),
19787 diag::err_duplicate_ivar_declaration);
19788 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19789 continue;
19790 }
19791 for (const auto *Ext : IDecl->known_extensions()) {
19792 if (const ObjCIvarDecl *ClsExtIvar
19793 = Ext->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
19794 Diag(ClsFields[i]->getLocation(),
19795 diag::err_duplicate_ivar_declaration);
19796 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19797 continue;
19798 }
19799 }
19800 }
19801 ClsFields[i]->setLexicalDeclContext(CDecl);
19802 CDecl->addDecl(ClsFields[i]);
19803 }
19804 CDecl->setIvarLBraceLoc(LBrac);
19805 CDecl->setIvarRBraceLoc(RBrac);
19806 }
19807 }
19808 ProcessAPINotes(Record);
19809}
19810
19811/// Determine whether the given integral value is representable within
19812/// the given type T.
19813static bool isRepresentableIntegerValue(ASTContext &Context,
19814 llvm::APSInt &Value,
19815 QualType T) {
19816 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19817 "Integral type required!");
19818 unsigned BitWidth = Context.getIntWidth(T);
19819
19820 if (Value.isUnsigned() || Value.isNonNegative()) {
19821 if (T->isSignedIntegerOrEnumerationType())
19822 --BitWidth;
19823 return Value.getActiveBits() <= BitWidth;
19824 }
19825 return Value.getSignificantBits() <= BitWidth;
19826}
19827
19828// Given an integral type, return the next larger integral type
19829// (or a NULL type of no such type exists).
19830static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
19831 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19832 // enum checking below.
19833 assert((T->isIntegralType(Context) ||
19834 T->isEnumeralType()) && "Integral type required!");
19835 const unsigned NumTypes = 4;
19836 QualType SignedIntegralTypes[NumTypes] = {
19837 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19838 };
19839 QualType UnsignedIntegralTypes[NumTypes] = {
19840 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19841 Context.UnsignedLongLongTy
19842 };
19843
19844 unsigned BitWidth = Context.getTypeSize(T);
19845 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19846 : UnsignedIntegralTypes;
19847 for (unsigned I = 0; I != NumTypes; ++I)
19848 if (Context.getTypeSize(T: Types[I]) > BitWidth)
19849 return Types[I];
19850
19851 return QualType();
19852}
19853
19854EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
19855 EnumConstantDecl *LastEnumConst,
19856 SourceLocation IdLoc,
19857 IdentifierInfo *Id,
19858 Expr *Val) {
19859 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19860 llvm::APSInt EnumVal(IntWidth);
19861 QualType EltTy;
19862
19863 if (Val && DiagnoseUnexpandedParameterPack(E: Val, UPPC: UPPC_EnumeratorValue))
19864 Val = nullptr;
19865
19866 if (Val)
19867 Val = DefaultLvalueConversion(E: Val).get();
19868
19869 if (Val) {
19870 if (Enum->isDependentType() || Val->isTypeDependent() ||
19871 Val->containsErrors())
19872 EltTy = Context.DependentTy;
19873 else {
19874 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19875 // underlying type, but do allow it in all other contexts.
19876 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19877 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19878 // constant-expression in the enumerator-definition shall be a converted
19879 // constant expression of the underlying type.
19880 EltTy = Enum->getIntegerType();
19881 ExprResult Converted =
19882 CheckConvertedConstantExpression(From: Val, T: EltTy, Value&: EnumVal,
19883 CCE: CCEK_Enumerator);
19884 if (Converted.isInvalid())
19885 Val = nullptr;
19886 else
19887 Val = Converted.get();
19888 } else if (!Val->isValueDependent() &&
19889 !(Val =
19890 VerifyIntegerConstantExpression(E: Val, Result: &EnumVal, CanFold: AllowFold)
19891 .get())) {
19892 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19893 } else {
19894 if (Enum->isComplete()) {
19895 EltTy = Enum->getIntegerType();
19896
19897 // In Obj-C and Microsoft mode, require the enumeration value to be
19898 // representable in the underlying type of the enumeration. In C++11,
19899 // we perform a non-narrowing conversion as part of converted constant
19900 // expression checking.
19901 if (!isRepresentableIntegerValue(Context, Value&: EnumVal, T: EltTy)) {
19902 if (Context.getTargetInfo()
19903 .getTriple()
19904 .isWindowsMSVCEnvironment()) {
19905 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19906 } else {
19907 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19908 }
19909 }
19910
19911 // Cast to the underlying type.
19912 Val = ImpCastExprToType(E: Val, Type: EltTy,
19913 CK: EltTy->isBooleanType() ? CK_IntegralToBoolean
19914 : CK_IntegralCast)
19915 .get();
19916 } else if (getLangOpts().CPlusPlus) {
19917 // C++11 [dcl.enum]p5:
19918 // If the underlying type is not fixed, the type of each enumerator
19919 // is the type of its initializing value:
19920 // - If an initializer is specified for an enumerator, the
19921 // initializing value has the same type as the expression.
19922 EltTy = Val->getType();
19923 } else {
19924 // C99 6.7.2.2p2:
19925 // The expression that defines the value of an enumeration constant
19926 // shall be an integer constant expression that has a value
19927 // representable as an int.
19928
19929 // Complain if the value is not representable in an int.
19930 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
19931 Diag(IdLoc, diag::ext_enum_value_not_int)
19932 << toString(EnumVal, 10) << Val->getSourceRange()
19933 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19934 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19935 // Force the type of the expression to 'int'.
19936 Val = ImpCastExprToType(E: Val, Type: Context.IntTy, CK: CK_IntegralCast).get();
19937 }
19938 EltTy = Val->getType();
19939 }
19940 }
19941 }
19942 }
19943
19944 if (!Val) {
19945 if (Enum->isDependentType())
19946 EltTy = Context.DependentTy;
19947 else if (!LastEnumConst) {
19948 // C++0x [dcl.enum]p5:
19949 // If the underlying type is not fixed, the type of each enumerator
19950 // is the type of its initializing value:
19951 // - If no initializer is specified for the first enumerator, the
19952 // initializing value has an unspecified integral type.
19953 //
19954 // GCC uses 'int' for its unspecified integral type, as does
19955 // C99 6.7.2.2p3.
19956 if (Enum->isFixed()) {
19957 EltTy = Enum->getIntegerType();
19958 }
19959 else {
19960 EltTy = Context.IntTy;
19961 }
19962 } else {
19963 // Assign the last value + 1.
19964 EnumVal = LastEnumConst->getInitVal();
19965 ++EnumVal;
19966 EltTy = LastEnumConst->getType();
19967
19968 // Check for overflow on increment.
19969 if (EnumVal < LastEnumConst->getInitVal()) {
19970 // C++0x [dcl.enum]p5:
19971 // If the underlying type is not fixed, the type of each enumerator
19972 // is the type of its initializing value:
19973 //
19974 // - Otherwise the type of the initializing value is the same as
19975 // the type of the initializing value of the preceding enumerator
19976 // unless the incremented value is not representable in that type,
19977 // in which case the type is an unspecified integral type
19978 // sufficient to contain the incremented value. If no such type
19979 // exists, the program is ill-formed.
19980 QualType T = getNextLargerIntegralType(Context, T: EltTy);
19981 if (T.isNull() || Enum->isFixed()) {
19982 // There is no integral type larger enough to represent this
19983 // value. Complain, then allow the value to wrap around.
19984 EnumVal = LastEnumConst->getInitVal();
19985 EnumVal = EnumVal.zext(width: EnumVal.getBitWidth() * 2);
19986 ++EnumVal;
19987 if (Enum->isFixed())
19988 // When the underlying type is fixed, this is ill-formed.
19989 Diag(IdLoc, diag::err_enumerator_wrapped)
19990 << toString(EnumVal, 10)
19991 << EltTy;
19992 else
19993 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19994 << toString(EnumVal, 10);
19995 } else {
19996 EltTy = T;
19997 }
19998
19999 // Retrieve the last enumerator's value, extent that type to the
20000 // type that is supposed to be large enough to represent the incremented
20001 // value, then increment.
20002 EnumVal = LastEnumConst->getInitVal();
20003 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20004 EnumVal = EnumVal.zextOrTrunc(width: Context.getIntWidth(T: EltTy));
20005 ++EnumVal;
20006
20007 // If we're not in C++, diagnose the overflow of enumerator values,
20008 // which in C99 means that the enumerator value is not representable in
20009 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
20010 // permits enumerator values that are representable in some larger
20011 // integral type.
20012 if (!getLangOpts().CPlusPlus && !T.isNull())
20013 Diag(IdLoc, diag::warn_enum_value_overflow);
20014 } else if (!getLangOpts().CPlusPlus &&
20015 !EltTy->isDependentType() &&
20016 !isRepresentableIntegerValue(Context, Value&: EnumVal, T: EltTy)) {
20017 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20018 Diag(IdLoc, diag::ext_enum_value_not_int)
20019 << toString(EnumVal, 10) << 1;
20020 }
20021 }
20022 }
20023
20024 if (!EltTy->isDependentType()) {
20025 // Make the enumerator value match the signedness and size of the
20026 // enumerator's type.
20027 EnumVal = EnumVal.extOrTrunc(width: Context.getIntWidth(T: EltTy));
20028 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20029 }
20030
20031 return EnumConstantDecl::Create(C&: Context, DC: Enum, L: IdLoc, Id, T: EltTy,
20032 E: Val, V: EnumVal);
20033}
20034
20035SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
20036 SourceLocation IILoc) {
20037 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20038 !getLangOpts().CPlusPlus)
20039 return SkipBodyInfo();
20040
20041 // We have an anonymous enum definition. Look up the first enumerator to
20042 // determine if we should merge the definition with an existing one and
20043 // skip the body.
20044 NamedDecl *PrevDecl = LookupSingleName(S, Name: II, Loc: IILoc, NameKind: LookupOrdinaryName,
20045 Redecl: forRedeclarationInCurContext());
20046 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(Val: PrevDecl);
20047 if (!PrevECD)
20048 return SkipBodyInfo();
20049
20050 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20051 NamedDecl *Hidden;
20052 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20053 SkipBodyInfo Skip;
20054 Skip.Previous = Hidden;
20055 return Skip;
20056 }
20057
20058 return SkipBodyInfo();
20059}
20060
20061Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20062 SourceLocation IdLoc, IdentifierInfo *Id,
20063 const ParsedAttributesView &Attrs,
20064 SourceLocation EqualLoc, Expr *Val) {
20065 EnumDecl *TheEnumDecl = cast<EnumDecl>(Val: theEnumDecl);
20066 EnumConstantDecl *LastEnumConst =
20067 cast_or_null<EnumConstantDecl>(Val: lastEnumConst);
20068
20069 // The scope passed in may not be a decl scope. Zip up the scope tree until
20070 // we find one that is.
20071 S = getNonFieldDeclScope(S);
20072
20073 // Verify that there isn't already something declared with this name in this
20074 // scope.
20075 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20076 RedeclarationKind::ForVisibleRedeclaration);
20077 LookupName(R, S);
20078 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20079
20080 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20081 // Maybe we will complain about the shadowed template parameter.
20082 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20083 // Just pretend that we didn't see the previous declaration.
20084 PrevDecl = nullptr;
20085 }
20086
20087 // C++ [class.mem]p15:
20088 // If T is the name of a class, then each of the following shall have a name
20089 // different from T:
20090 // - every enumerator of every member of class T that is an unscoped
20091 // enumerated type
20092 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
20093 DiagnoseClassNameShadow(DC: TheEnumDecl->getDeclContext(),
20094 NameInfo: DeclarationNameInfo(Id, IdLoc));
20095
20096 EnumConstantDecl *New =
20097 CheckEnumConstant(Enum: TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20098 if (!New)
20099 return nullptr;
20100
20101 if (PrevDecl) {
20102 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(Val: PrevDecl)) {
20103 // Check for other kinds of shadowing not already handled.
20104 CheckShadow(New, PrevDecl, R);
20105 }
20106
20107 // When in C++, we may get a TagDecl with the same name; in this case the
20108 // enum constant will 'hide' the tag.
20109 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20110 "Received TagDecl when not in C++!");
20111 if (!isa<TagDecl>(Val: PrevDecl) && isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
20112 if (isa<EnumConstantDecl>(PrevDecl))
20113 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
20114 else
20115 Diag(IdLoc, diag::err_redefinition) << Id;
20116 notePreviousDefinition(Old: PrevDecl, New: IdLoc);
20117 return nullptr;
20118 }
20119 }
20120
20121 // Process attributes.
20122 ProcessDeclAttributeList(S, New, Attrs);
20123 AddPragmaAttributes(S, New);
20124 ProcessAPINotes(New);
20125
20126 // Register this decl in the current scope stack.
20127 New->setAccess(TheEnumDecl->getAccess());
20128 PushOnScopeChains(New, S);
20129
20130 ActOnDocumentableDecl(New);
20131
20132 return New;
20133}
20134
20135// Returns true when the enum initial expression does not trigger the
20136// duplicate enum warning. A few common cases are exempted as follows:
20137// Element2 = Element1
20138// Element2 = Element1 + 1
20139// Element2 = Element1 - 1
20140// Where Element2 and Element1 are from the same enum.
20141static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
20142 Expr *InitExpr = ECD->getInitExpr();
20143 if (!InitExpr)
20144 return true;
20145 InitExpr = InitExpr->IgnoreImpCasts();
20146
20147 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: InitExpr)) {
20148 if (!BO->isAdditiveOp())
20149 return true;
20150 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: BO->getRHS());
20151 if (!IL)
20152 return true;
20153 if (IL->getValue() != 1)
20154 return true;
20155
20156 InitExpr = BO->getLHS();
20157 }
20158
20159 // This checks if the elements are from the same enum.
20160 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InitExpr);
20161 if (!DRE)
20162 return true;
20163
20164 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(Val: DRE->getDecl());
20165 if (!EnumConstant)
20166 return true;
20167
20168 if (cast<EnumDecl>(TagDecl::castFromDeclContext(DC: ECD->getDeclContext())) !=
20169 Enum)
20170 return true;
20171
20172 return false;
20173}
20174
20175// Emits a warning when an element is implicitly set a value that
20176// a previous element has already been set to.
20177static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
20178 EnumDecl *Enum, QualType EnumType) {
20179 // Avoid anonymous enums
20180 if (!Enum->getIdentifier())
20181 return;
20182
20183 // Only check for small enums.
20184 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20185 return;
20186
20187 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
20188 return;
20189
20190 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20191 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20192
20193 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20194
20195 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20196 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20197
20198 // Use int64_t as a key to avoid needing special handling for map keys.
20199 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20200 llvm::APSInt Val = D->getInitVal();
20201 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20202 };
20203
20204 DuplicatesVector DupVector;
20205 ValueToVectorMap EnumMap;
20206
20207 // Populate the EnumMap with all values represented by enum constants without
20208 // an initializer.
20209 for (auto *Element : Elements) {
20210 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: Element);
20211
20212 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20213 // this constant. Skip this enum since it may be ill-formed.
20214 if (!ECD) {
20215 return;
20216 }
20217
20218 // Constants with initializers are handled in the next loop.
20219 if (ECD->getInitExpr())
20220 continue;
20221
20222 // Duplicate values are handled in the next loop.
20223 EnumMap.insert(x: {EnumConstantToKey(ECD), ECD});
20224 }
20225
20226 if (EnumMap.size() == 0)
20227 return;
20228
20229 // Create vectors for any values that has duplicates.
20230 for (auto *Element : Elements) {
20231 // The last loop returned if any constant was null.
20232 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Val: Element);
20233 if (!ValidDuplicateEnum(ECD, Enum))
20234 continue;
20235
20236 auto Iter = EnumMap.find(x: EnumConstantToKey(ECD));
20237 if (Iter == EnumMap.end())
20238 continue;
20239
20240 DeclOrVector& Entry = Iter->second;
20241 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
20242 // Ensure constants are different.
20243 if (D == ECD)
20244 continue;
20245
20246 // Create new vector and push values onto it.
20247 auto Vec = std::make_unique<ECDVector>();
20248 Vec->push_back(Elt: D);
20249 Vec->push_back(Elt: ECD);
20250
20251 // Update entry to point to the duplicates vector.
20252 Entry = Vec.get();
20253
20254 // Store the vector somewhere we can consult later for quick emission of
20255 // diagnostics.
20256 DupVector.emplace_back(Args: std::move(Vec));
20257 continue;
20258 }
20259
20260 ECDVector *Vec = Entry.get<ECDVector*>();
20261 // Make sure constants are not added more than once.
20262 if (*Vec->begin() == ECD)
20263 continue;
20264
20265 Vec->push_back(Elt: ECD);
20266 }
20267
20268 // Emit diagnostics.
20269 for (const auto &Vec : DupVector) {
20270 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20271
20272 // Emit warning for one enum constant.
20273 auto *FirstECD = Vec->front();
20274 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20275 << FirstECD << toString(FirstECD->getInitVal(), 10)
20276 << FirstECD->getSourceRange();
20277
20278 // Emit one note for each of the remaining enum constants with
20279 // the same value.
20280 for (auto *ECD : llvm::drop_begin(*Vec))
20281 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20282 << ECD << toString(ECD->getInitVal(), 10)
20283 << ECD->getSourceRange();
20284 }
20285}
20286
20287bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20288 bool AllowMask) const {
20289 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20290 assert(ED->isCompleteDefinition() && "expected enum definition");
20291
20292 auto R = FlagBitsCache.insert(KV: std::make_pair(x&: ED, y: llvm::APInt()));
20293 llvm::APInt &FlagBits = R.first->second;
20294
20295 if (R.second) {
20296 for (auto *E : ED->enumerators()) {
20297 const auto &EVal = E->getInitVal();
20298 // Only single-bit enumerators introduce new flag values.
20299 if (EVal.isPowerOf2())
20300 FlagBits = FlagBits.zext(width: EVal.getBitWidth()) | EVal;
20301 }
20302 }
20303
20304 // A value is in a flag enum if either its bits are a subset of the enum's
20305 // flag bits (the first condition) or we are allowing masks and the same is
20306 // true of its complement (the second condition). When masks are allowed, we
20307 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20308 //
20309 // While it's true that any value could be used as a mask, the assumption is
20310 // that a mask will have all of the insignificant bits set. Anything else is
20311 // likely a logic error.
20312 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(width: Val.getBitWidth());
20313 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20314}
20315
20316void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
20317 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20318 const ParsedAttributesView &Attrs) {
20319 EnumDecl *Enum = cast<EnumDecl>(Val: EnumDeclX);
20320 QualType EnumType = Context.getTypeDeclType(Enum);
20321
20322 ProcessDeclAttributeList(S, Enum, Attrs);
20323 ProcessAPINotes(Enum);
20324
20325 if (Enum->isDependentType()) {
20326 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20327 EnumConstantDecl *ECD =
20328 cast_or_null<EnumConstantDecl>(Val: Elements[i]);
20329 if (!ECD) continue;
20330
20331 ECD->setType(EnumType);
20332 }
20333
20334 Enum->completeDefinition(NewType: Context.DependentTy, PromotionType: Context.DependentTy, NumPositiveBits: 0, NumNegativeBits: 0);
20335 return;
20336 }
20337
20338 // TODO: If the result value doesn't fit in an int, it must be a long or long
20339 // long value. ISO C does not support this, but GCC does as an extension,
20340 // emit a warning.
20341 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20342 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
20343 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
20344
20345 // Verify that all the values are okay, compute the size of the values, and
20346 // reverse the list.
20347 unsigned NumNegativeBits = 0;
20348 unsigned NumPositiveBits = 0;
20349
20350 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20351 EnumConstantDecl *ECD =
20352 cast_or_null<EnumConstantDecl>(Val: Elements[i]);
20353 if (!ECD) continue; // Already issued a diagnostic.
20354
20355 const llvm::APSInt &InitVal = ECD->getInitVal();
20356
20357 // Keep track of the size of positive and negative values.
20358 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
20359 // If the enumerator is zero that should still be counted as a positive
20360 // bit since we need a bit to store the value zero.
20361 unsigned ActiveBits = InitVal.getActiveBits();
20362 NumPositiveBits = std::max(l: {NumPositiveBits, ActiveBits, 1u});
20363 } else {
20364 NumNegativeBits =
20365 std::max(a: NumNegativeBits, b: (unsigned)InitVal.getSignificantBits());
20366 }
20367 }
20368
20369 // If we have an empty set of enumerators we still need one bit.
20370 // From [dcl.enum]p8
20371 // If the enumerator-list is empty, the values of the enumeration are as if
20372 // the enumeration had a single enumerator with value 0
20373 if (!NumPositiveBits && !NumNegativeBits)
20374 NumPositiveBits = 1;
20375
20376 // Figure out the type that should be used for this enum.
20377 QualType BestType;
20378 unsigned BestWidth;
20379
20380 // C++0x N3000 [conv.prom]p3:
20381 // An rvalue of an unscoped enumeration type whose underlying
20382 // type is not fixed can be converted to an rvalue of the first
20383 // of the following types that can represent all the values of
20384 // the enumeration: int, unsigned int, long int, unsigned long
20385 // int, long long int, or unsigned long long int.
20386 // C99 6.4.4.3p2:
20387 // An identifier declared as an enumeration constant has type int.
20388 // The C99 rule is modified by a gcc extension
20389 QualType BestPromotionType;
20390
20391 bool Packed = Enum->hasAttr<PackedAttr>();
20392 // -fshort-enums is the equivalent to specifying the packed attribute on all
20393 // enum definitions.
20394 if (LangOpts.ShortEnums)
20395 Packed = true;
20396
20397 // If the enum already has a type because it is fixed or dictated by the
20398 // target, promote that type instead of analyzing the enumerators.
20399 if (Enum->isComplete()) {
20400 BestType = Enum->getIntegerType();
20401 if (Context.isPromotableIntegerType(T: BestType))
20402 BestPromotionType = Context.getPromotedIntegerType(PromotableType: BestType);
20403 else
20404 BestPromotionType = BestType;
20405
20406 BestWidth = Context.getIntWidth(T: BestType);
20407 }
20408 else if (NumNegativeBits) {
20409 // If there is a negative value, figure out the smallest integer type (of
20410 // int/long/longlong) that fits.
20411 // If it's packed, check also if it fits a char or a short.
20412 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
20413 BestType = Context.SignedCharTy;
20414 BestWidth = CharWidth;
20415 } else if (Packed && NumNegativeBits <= ShortWidth &&
20416 NumPositiveBits < ShortWidth) {
20417 BestType = Context.ShortTy;
20418 BestWidth = ShortWidth;
20419 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
20420 BestType = Context.IntTy;
20421 BestWidth = IntWidth;
20422 } else {
20423 BestWidth = Context.getTargetInfo().getLongWidth();
20424
20425 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
20426 BestType = Context.LongTy;
20427 } else {
20428 BestWidth = Context.getTargetInfo().getLongLongWidth();
20429
20430 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
20431 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20432 BestType = Context.LongLongTy;
20433 }
20434 }
20435 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
20436 } else {
20437 // If there is no negative value, figure out the smallest type that fits
20438 // all of the enumerator values.
20439 // If it's packed, check also if it fits a char or a short.
20440 if (Packed && NumPositiveBits <= CharWidth) {
20441 BestType = Context.UnsignedCharTy;
20442 BestPromotionType = Context.IntTy;
20443 BestWidth = CharWidth;
20444 } else if (Packed && NumPositiveBits <= ShortWidth) {
20445 BestType = Context.UnsignedShortTy;
20446 BestPromotionType = Context.IntTy;
20447 BestWidth = ShortWidth;
20448 } else if (NumPositiveBits <= IntWidth) {
20449 BestType = Context.UnsignedIntTy;
20450 BestWidth = IntWidth;
20451 BestPromotionType
20452 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20453 ? Context.UnsignedIntTy : Context.IntTy;
20454 } else if (NumPositiveBits <=
20455 (BestWidth = Context.getTargetInfo().getLongWidth())) {
20456 BestType = Context.UnsignedLongTy;
20457 BestPromotionType
20458 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20459 ? Context.UnsignedLongTy : Context.LongTy;
20460 } else {
20461 BestWidth = Context.getTargetInfo().getLongLongWidth();
20462 if (NumPositiveBits > BestWidth) {
20463 // This can happen with bit-precise integer types, but those are not
20464 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
20465 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
20466 // a 128-bit integer, we should consider doing the same.
20467 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20468 }
20469 BestType = Context.UnsignedLongLongTy;
20470 BestPromotionType
20471 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20472 ? Context.UnsignedLongLongTy : Context.LongLongTy;
20473 }
20474 }
20475
20476 // Loop over all of the enumerator constants, changing their types to match
20477 // the type of the enum if needed.
20478 for (auto *D : Elements) {
20479 auto *ECD = cast_or_null<EnumConstantDecl>(Val: D);
20480 if (!ECD) continue; // Already issued a diagnostic.
20481
20482 // Standard C says the enumerators have int type, but we allow, as an
20483 // extension, the enumerators to be larger than int size. If each
20484 // enumerator value fits in an int, type it as an int, otherwise type it the
20485 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20486 // that X has type 'int', not 'unsigned'.
20487
20488 // Determine whether the value fits into an int.
20489 llvm::APSInt InitVal = ECD->getInitVal();
20490
20491 // If it fits into an integer type, force it. Otherwise force it to match
20492 // the enum decl type.
20493 QualType NewTy;
20494 unsigned NewWidth;
20495 bool NewSign;
20496 if (!getLangOpts().CPlusPlus &&
20497 !Enum->isFixed() &&
20498 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
20499 NewTy = Context.IntTy;
20500 NewWidth = IntWidth;
20501 NewSign = true;
20502 } else if (ECD->getType() == BestType) {
20503 // Already the right type!
20504 if (getLangOpts().CPlusPlus)
20505 // C++ [dcl.enum]p4: Following the closing brace of an
20506 // enum-specifier, each enumerator has the type of its
20507 // enumeration.
20508 ECD->setType(EnumType);
20509 continue;
20510 } else {
20511 NewTy = BestType;
20512 NewWidth = BestWidth;
20513 NewSign = BestType->isSignedIntegerOrEnumerationType();
20514 }
20515
20516 // Adjust the APSInt value.
20517 InitVal = InitVal.extOrTrunc(width: NewWidth);
20518 InitVal.setIsSigned(NewSign);
20519 ECD->setInitVal(C: Context, V: InitVal);
20520
20521 // Adjust the Expr initializer and type.
20522 if (ECD->getInitExpr() &&
20523 !Context.hasSameType(T1: NewTy, T2: ECD->getInitExpr()->getType()))
20524 ECD->setInitExpr(ImplicitCastExpr::Create(
20525 Context, T: NewTy, Kind: CK_IntegralCast, Operand: ECD->getInitExpr(),
20526 /*base paths*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()));
20527 if (getLangOpts().CPlusPlus)
20528 // C++ [dcl.enum]p4: Following the closing brace of an
20529 // enum-specifier, each enumerator has the type of its
20530 // enumeration.
20531 ECD->setType(EnumType);
20532 else
20533 ECD->setType(NewTy);
20534 }
20535
20536 Enum->completeDefinition(NewType: BestType, PromotionType: BestPromotionType,
20537 NumPositiveBits, NumNegativeBits);
20538
20539 CheckForDuplicateEnumValues(S&: *this, Elements, Enum, EnumType);
20540
20541 if (Enum->isClosedFlag()) {
20542 for (Decl *D : Elements) {
20543 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: D);
20544 if (!ECD) continue; // Already issued a diagnostic.
20545
20546 llvm::APSInt InitVal = ECD->getInitVal();
20547 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20548 !IsValueInFlagEnum(Enum, InitVal, true))
20549 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20550 << ECD << Enum;
20551 }
20552 }
20553
20554 // Now that the enum type is defined, ensure it's not been underaligned.
20555 if (Enum->hasAttrs())
20556 CheckAlignasUnderalignment(Enum);
20557}
20558
20559Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
20560 SourceLocation StartLoc,
20561 SourceLocation EndLoc) {
20562 StringLiteral *AsmString = cast<StringLiteral>(Val: expr);
20563
20564 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(C&: Context, DC: CurContext,
20565 Str: AsmString, AsmLoc: StartLoc,
20566 RParenLoc: EndLoc);
20567 CurContext->addDecl(New);
20568 return New;
20569}
20570
20571TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {
20572 auto *New = TopLevelStmtDecl::Create(C&: Context, /*Statement=*/nullptr);
20573 CurContext->addDecl(New);
20574 PushDeclContext(S, New);
20575 PushFunctionScope();
20576 PushCompoundScope(IsStmtExpr: false);
20577 return New;
20578}
20579
20580void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {
20581 D->setStmt(Statement);
20582 PopCompoundScope();
20583 PopFunctionScopeInfo();
20584 PopDeclContext();
20585}
20586
20587void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
20588 IdentifierInfo* AliasName,
20589 SourceLocation PragmaLoc,
20590 SourceLocation NameLoc,
20591 SourceLocation AliasNameLoc) {
20592 NamedDecl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc,
20593 NameKind: LookupOrdinaryName);
20594 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20595 AttributeCommonInfo::Form::Pragma());
20596 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20597 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20598
20599 // If a declaration that:
20600 // 1) declares a function or a variable
20601 // 2) has external linkage
20602 // already exists, add a label attribute to it.
20603 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
20604 if (isDeclExternC(PrevDecl))
20605 PrevDecl->addAttr(A: Attr);
20606 else
20607 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20608 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20609 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20610 } else
20611 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20612}
20613
20614void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
20615 SourceLocation PragmaLoc,
20616 SourceLocation NameLoc) {
20617 Decl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc, NameKind: LookupOrdinaryName);
20618
20619 if (PrevDecl) {
20620 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20621 } else {
20622 (void)WeakUndeclaredIdentifiers[Name].insert(X: WeakInfo(nullptr, NameLoc));
20623 }
20624}
20625
20626void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
20627 IdentifierInfo* AliasName,
20628 SourceLocation PragmaLoc,
20629 SourceLocation NameLoc,
20630 SourceLocation AliasNameLoc) {
20631 Decl *PrevDecl = LookupSingleName(S: TUScope, Name: AliasName, Loc: AliasNameLoc,
20632 NameKind: LookupOrdinaryName);
20633 WeakInfo W = WeakInfo(Name, NameLoc);
20634
20635 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
20636 if (!PrevDecl->hasAttr<AliasAttr>())
20637 if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: PrevDecl))
20638 DeclApplyPragmaWeak(S: TUScope, ND, W);
20639 } else {
20640 (void)WeakUndeclaredIdentifiers[AliasName].insert(X: W);
20641 }
20642}
20643
20644ObjCContainerDecl *Sema::getObjCDeclContext() const {
20645 return (dyn_cast_or_null<ObjCContainerDecl>(Val: CurContext));
20646}
20647
20648Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
20649 bool Final) {
20650 assert(FD && "Expected non-null FunctionDecl");
20651
20652 // SYCL functions can be template, so we check if they have appropriate
20653 // attribute prior to checking if it is a template.
20654 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20655 return FunctionEmissionStatus::Emitted;
20656
20657 // Templates are emitted when they're instantiated.
20658 if (FD->isDependentContext())
20659 return FunctionEmissionStatus::TemplateDiscarded;
20660
20661 // Check whether this function is an externally visible definition.
20662 auto IsEmittedForExternalSymbol = [this, FD]() {
20663 // We have to check the GVA linkage of the function's *definition* -- if we
20664 // only have a declaration, we don't know whether or not the function will
20665 // be emitted, because (say) the definition could include "inline".
20666 const FunctionDecl *Def = FD->getDefinition();
20667
20668 return Def && !isDiscardableGVALinkage(
20669 L: getASTContext().GetGVALinkageForFunction(FD: Def));
20670 };
20671
20672 if (LangOpts.OpenMPIsTargetDevice) {
20673 // In OpenMP device mode we will not emit host only functions, or functions
20674 // we don't need due to their linkage.
20675 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20676 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20677 // DevTy may be changed later by
20678 // #pragma omp declare target to(*) device_type(*).
20679 // Therefore DevTy having no value does not imply host. The emission status
20680 // will be checked again at the end of compilation unit with Final = true.
20681 if (DevTy)
20682 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20683 return FunctionEmissionStatus::OMPDiscarded;
20684 // If we have an explicit value for the device type, or we are in a target
20685 // declare context, we need to emit all extern and used symbols.
20686 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20687 if (IsEmittedForExternalSymbol())
20688 return FunctionEmissionStatus::Emitted;
20689 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20690 // we'll omit it.
20691 if (Final)
20692 return FunctionEmissionStatus::OMPDiscarded;
20693 } else if (LangOpts.OpenMP > 45) {
20694 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20695 // function. In 5.0, no_host was introduced which might cause a function to
20696 // be ommitted.
20697 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20698 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20699 if (DevTy)
20700 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20701 return FunctionEmissionStatus::OMPDiscarded;
20702 }
20703
20704 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20705 return FunctionEmissionStatus::Emitted;
20706
20707 if (LangOpts.CUDA) {
20708 // When compiling for device, host functions are never emitted. Similarly,
20709 // when compiling for host, device and global functions are never emitted.
20710 // (Technically, we do emit a host-side stub for global functions, but this
20711 // doesn't count for our purposes here.)
20712 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: FD);
20713 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20714 return FunctionEmissionStatus::CUDADiscarded;
20715 if (!LangOpts.CUDAIsDevice &&
20716 (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))
20717 return FunctionEmissionStatus::CUDADiscarded;
20718
20719 if (IsEmittedForExternalSymbol())
20720 return FunctionEmissionStatus::Emitted;
20721 }
20722
20723 // Otherwise, the function is known-emitted if it's in our set of
20724 // known-emitted functions.
20725 return FunctionEmissionStatus::Unknown;
20726}
20727
20728bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
20729 // Host-side references to a __global__ function refer to the stub, so the
20730 // function itself is never emitted and therefore should not be marked.
20731 // If we have host fn calls kernel fn calls host+device, the HD function
20732 // does not get instantiated on the host. We model this by omitting at the
20733 // call to the kernel from the callgraph. This ensures that, when compiling
20734 // for host, only HD functions actually called from the host get marked as
20735 // known-emitted.
20736 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20737 CUDA().IdentifyTarget(D: Callee) == CUDAFunctionTarget::Global;
20738}
20739

source code of clang/lib/Sema/SemaDecl.cpp