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/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
27#include "clang/AST/MangleNumberingContext.h"
28#include "clang/AST/NonTrivialTypeVisitor.h"
29#include "clang/AST/Randstruct.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/Type.h"
32#include "clang/Basic/Builtins.h"
33#include "clang/Basic/HLSLRuntime.h"
34#include "clang/Basic/PartialDiagnostic.h"
35#include "clang/Basic/SourceManager.h"
36#include "clang/Basic/TargetInfo.h"
37#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
38#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
39#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
40#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
41#include "clang/Sema/CXXFieldCollector.h"
42#include "clang/Sema/DeclSpec.h"
43#include "clang/Sema/DelayedDiagnostic.h"
44#include "clang/Sema/Initialization.h"
45#include "clang/Sema/Lookup.h"
46#include "clang/Sema/ParsedTemplate.h"
47#include "clang/Sema/Scope.h"
48#include "clang/Sema/ScopeInfo.h"
49#include "clang/Sema/SemaAMDGPU.h"
50#include "clang/Sema/SemaARM.h"
51#include "clang/Sema/SemaCUDA.h"
52#include "clang/Sema/SemaHLSL.h"
53#include "clang/Sema/SemaInternal.h"
54#include "clang/Sema/SemaObjC.h"
55#include "clang/Sema/SemaOpenACC.h"
56#include "clang/Sema/SemaOpenMP.h"
57#include "clang/Sema/SemaPPC.h"
58#include "clang/Sema/SemaRISCV.h"
59#include "clang/Sema/SemaSYCL.h"
60#include "clang/Sema/SemaSwift.h"
61#include "clang/Sema/SemaWasm.h"
62#include "clang/Sema/Template.h"
63#include "llvm/ADT/ArrayRef.h"
64#include "llvm/ADT/STLForwardCompat.h"
65#include "llvm/ADT/ScopeExit.h"
66#include "llvm/ADT/SmallPtrSet.h"
67#include "llvm/ADT/SmallString.h"
68#include "llvm/ADT/StringExtras.h"
69#include "llvm/ADT/StringRef.h"
70#include "llvm/Support/SaveAndRestore.h"
71#include "llvm/TargetParser/Triple.h"
72#include <algorithm>
73#include <cstring>
74#include <optional>
75#include <unordered_map>
76
77using namespace clang;
78using namespace sema;
79
80Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
81 if (OwnedType) {
82 Decl *Group[2] = { OwnedType, Ptr };
83 return DeclGroupPtrTy::make(P: DeclGroupRef::Create(C&: Context, Decls: Group, NumDecls: 2));
84 }
85
86 return DeclGroupPtrTy::make(P: DeclGroupRef(Ptr));
87}
88
89namespace {
90
91class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
92 public:
93 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
94 bool AllowTemplates = false,
95 bool AllowNonTemplates = true)
96 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
97 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
98 WantExpressionKeywords = false;
99 WantCXXNamedCasts = false;
100 WantRemainingKeywords = false;
101 }
102
103 bool ValidateCandidate(const TypoCorrection &candidate) override {
104 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
105 if (!AllowInvalidDecl && ND->isInvalidDecl())
106 return false;
107
108 if (getAsTypeTemplateDecl(D: ND))
109 return AllowTemplates;
110
111 bool IsType = isa<TypeDecl>(Val: ND) || isa<ObjCInterfaceDecl>(Val: ND);
112 if (!IsType)
113 return false;
114
115 if (AllowNonTemplates)
116 return true;
117
118 // An injected-class-name of a class template (specialization) is valid
119 // as a template or as a non-template.
120 if (AllowTemplates) {
121 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
122 if (!RD || !RD->isInjectedClassName())
123 return false;
124 RD = cast<CXXRecordDecl>(Val: RD->getDeclContext());
125 return RD->getDescribedClassTemplate() ||
126 isa<ClassTemplateSpecializationDecl>(Val: RD);
127 }
128
129 return false;
130 }
131
132 return !WantClassName && candidate.isKeyword();
133 }
134
135 std::unique_ptr<CorrectionCandidateCallback> clone() override {
136 return std::make_unique<TypeNameValidatorCCC>(args&: *this);
137 }
138
139 private:
140 bool AllowInvalidDecl;
141 bool WantClassName;
142 bool AllowTemplates;
143 bool AllowNonTemplates;
144};
145
146} // end anonymous namespace
147
148void Sema::checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK,
149 TypeDecl *TD, SourceLocation NameLoc) {
150 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
151 auto *FoundRD = dyn_cast<CXXRecordDecl>(Val: TD);
152 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
153 FoundRD->isInjectedClassName() &&
154 declaresSameEntity(D1: LookupRD, D2: cast<Decl>(Val: FoundRD->getParent()))) {
155 Diag(Loc: NameLoc,
156 DiagID: DCK == DiagCtorKind::Typename
157 ? diag::ext_out_of_line_qualified_id_type_names_constructor
158 : diag::err_out_of_line_qualified_id_type_names_constructor)
159 << TD->getIdentifier() << /*Type=*/1
160 << 0 /*if any keyword was present, it was 'typename'*/;
161 }
162
163 DiagnoseUseOfDecl(D: TD, Locs: NameLoc);
164 MarkAnyDeclReferenced(Loc: TD->getLocation(), D: TD, /*OdrUse=*/MightBeOdrUse: false);
165}
166
167namespace {
168enum class UnqualifiedTypeNameLookupResult {
169 NotFound,
170 FoundNonType,
171 FoundType
172};
173} // end anonymous namespace
174
175/// Tries to perform unqualified lookup of the type decls in bases for
176/// dependent class.
177/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
178/// type decl, \a FoundType if only type decls are found.
179static UnqualifiedTypeNameLookupResult
180lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
181 SourceLocation NameLoc,
182 const CXXRecordDecl *RD) {
183 if (!RD->hasDefinition())
184 return UnqualifiedTypeNameLookupResult::NotFound;
185 // Look for type decls in base classes.
186 UnqualifiedTypeNameLookupResult FoundTypeDecl =
187 UnqualifiedTypeNameLookupResult::NotFound;
188 for (const auto &Base : RD->bases()) {
189 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
190 if (BaseRD) {
191 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
192 Val: Base.getType().getCanonicalType())) {
193 // Look for type decls in dependent base classes that have known primary
194 // templates.
195 if (!TST->isDependentType())
196 continue;
197 auto *TD = TST->getTemplateName().getAsTemplateDecl();
198 if (!TD)
199 continue;
200 if (auto *BasePrimaryTemplate =
201 dyn_cast_or_null<CXXRecordDecl>(Val: TD->getTemplatedDecl())) {
202 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
203 BaseRD = BasePrimaryTemplate;
204 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: TD)) {
205 if (const ClassTemplatePartialSpecializationDecl *PS =
206 CTD->findPartialSpecialization(T: Base.getType()))
207 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
208 BaseRD = PS;
209 }
210 }
211 }
212 if (BaseRD) {
213 for (NamedDecl *ND : BaseRD->lookup(Name: &II)) {
214 if (!isa<TypeDecl>(Val: ND))
215 return UnqualifiedTypeNameLookupResult::FoundNonType;
216 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
217 }
218 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
219 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD: BaseRD)) {
220 case UnqualifiedTypeNameLookupResult::FoundNonType:
221 return UnqualifiedTypeNameLookupResult::FoundNonType;
222 case UnqualifiedTypeNameLookupResult::FoundType:
223 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
224 break;
225 case UnqualifiedTypeNameLookupResult::NotFound:
226 break;
227 }
228 }
229 }
230 }
231
232 return FoundTypeDecl;
233}
234
235static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
236 const IdentifierInfo &II,
237 SourceLocation NameLoc) {
238 // Lookup in the parent class template context, if any.
239 const CXXRecordDecl *RD = nullptr;
240 UnqualifiedTypeNameLookupResult FoundTypeDecl =
241 UnqualifiedTypeNameLookupResult::NotFound;
242 for (DeclContext *DC = S.CurContext;
243 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
244 DC = DC->getParent()) {
245 // Look for type decls in dependent base classes that have known primary
246 // templates.
247 RD = dyn_cast<CXXRecordDecl>(Val: DC);
248 if (RD && RD->getDescribedClassTemplate())
249 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
250 }
251 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
252 return nullptr;
253
254 // We found some types in dependent base classes. Recover as if the user
255 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
256 // allowed. We'll fully resolve the lookup during template instantiation.
257 S.Diag(Loc: NameLoc, DiagID: diag::ext_found_in_dependent_base) << &II;
258
259 ASTContext &Context = S.Context;
260 NestedNameSpecifier NNS(Context.getCanonicalTagType(TD: RD).getTypePtr());
261 QualType T =
262 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
263
264 CXXScopeSpec SS;
265 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
266
267 TypeLocBuilder Builder;
268 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
269 DepTL.setNameLoc(NameLoc);
270 DepTL.setElaboratedKeywordLoc(SourceLocation());
271 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
272 return S.CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
273}
274
275ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
276 Scope *S, CXXScopeSpec *SS, bool isClassName,
277 bool HasTrailingDot, ParsedType ObjectTypePtr,
278 bool IsCtorOrDtorName,
279 bool WantNontrivialTypeSourceInfo,
280 bool IsClassTemplateDeductionContext,
281 ImplicitTypenameContext AllowImplicitTypename,
282 IdentifierInfo **CorrectedII) {
283 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
284 // FIXME: Consider allowing this outside C++1z mode as an extension.
285 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
286 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
287 !HasTrailingDot;
288
289 // Determine where we will perform name lookup.
290 DeclContext *LookupCtx = nullptr;
291 if (ObjectTypePtr) {
292 QualType ObjectType = ObjectTypePtr.get();
293 if (ObjectType->isRecordType())
294 LookupCtx = computeDeclContext(T: ObjectType);
295 } else if (SS && SS->isNotEmpty()) {
296 LookupCtx = computeDeclContext(SS: *SS, EnteringContext: false);
297
298 if (!LookupCtx) {
299 if (isDependentScopeSpecifier(SS: *SS)) {
300 // C++ [temp.res]p3:
301 // A qualified-id that refers to a type and in which the
302 // nested-name-specifier depends on a template-parameter (14.6.2)
303 // shall be prefixed by the keyword typename to indicate that the
304 // qualified-id denotes a type, forming an
305 // elaborated-type-specifier (7.1.5.3).
306 //
307 // We therefore do not perform any name lookup if the result would
308 // refer to a member of an unknown specialization.
309 // In C++2a, in several contexts a 'typename' is not required. Also
310 // allow this as an extension.
311 if (IsImplicitTypename) {
312 if (AllowImplicitTypename == ImplicitTypenameContext::No)
313 return nullptr;
314 SourceLocation QualifiedLoc = SS->getRange().getBegin();
315 // FIXME: Defer the diagnostic after we build the type and use it.
316 auto DB = DiagCompat(Loc: QualifiedLoc, CompatDiagId: diag_compat::implicit_typename)
317 << Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
318 NNS: SS->getScopeRep(), Name: &II);
319 if (!getLangOpts().CPlusPlus20)
320 DB << FixItHint::CreateInsertion(InsertionLoc: QualifiedLoc, Code: "typename ");
321 }
322
323 // We know from the grammar that this name refers to a type,
324 // so build a dependent node to describe the type.
325 if (WantNontrivialTypeSourceInfo)
326 return ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II, IdLoc: NameLoc,
327 IsImplicitTypename: (ImplicitTypenameContext)IsImplicitTypename)
328 .get();
329
330 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
331 QualType T = CheckTypenameType(
332 Keyword: IsImplicitTypename ? ElaboratedTypeKeyword::Typename
333 : ElaboratedTypeKeyword::None,
334 KeywordLoc: SourceLocation(), QualifierLoc, II, IILoc: NameLoc);
335 return ParsedType::make(P: T);
336 }
337
338 return nullptr;
339 }
340
341 if (!LookupCtx->isDependentContext() &&
342 RequireCompleteDeclContext(SS&: *SS, DC: LookupCtx))
343 return nullptr;
344 }
345
346 // In the case where we know that the identifier is a class name, we know that
347 // it is a type declaration (struct, class, union or enum) so we can use tag
348 // name lookup.
349 //
350 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
351 // the component name of the type-name or simple-template-id is type-only.
352 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
353 LookupResult Result(*this, &II, NameLoc, Kind);
354 if (LookupCtx) {
355 // Perform "qualified" name lookup into the declaration context we
356 // computed, which is either the type of the base of a member access
357 // expression or the declaration context associated with a prior
358 // nested-name-specifier.
359 LookupQualifiedName(R&: Result, LookupCtx);
360
361 if (ObjectTypePtr && Result.empty()) {
362 // C++ [basic.lookup.classref]p3:
363 // If the unqualified-id is ~type-name, the type-name is looked up
364 // in the context of the entire postfix-expression. If the type T of
365 // the object expression is of a class type C, the type-name is also
366 // looked up in the scope of class C. At least one of the lookups shall
367 // find a name that refers to (possibly cv-qualified) T.
368 LookupName(R&: Result, S);
369 }
370 } else {
371 // Perform unqualified name lookup.
372 LookupName(R&: Result, S);
373
374 // For unqualified lookup in a class template in MSVC mode, look into
375 // dependent base classes where the primary class template is known.
376 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
377 if (ParsedType TypeInBase =
378 recoverFromTypeInKnownDependentBase(S&: *this, II, NameLoc))
379 return TypeInBase;
380 }
381 }
382
383 NamedDecl *IIDecl = nullptr;
384 UsingShadowDecl *FoundUsingShadow = nullptr;
385 switch (Result.getResultKind()) {
386 case LookupResultKind::NotFound:
387 if (CorrectedII) {
388 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
389 AllowDeducedTemplate);
390 TypoCorrection Correction =
391 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Kind, S, SS, CCC,
392 Mode: CorrectTypoKind::ErrorRecovery);
393 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
394 TemplateTy Template;
395 bool MemberOfUnknownSpecialization;
396 UnqualifiedId TemplateName;
397 TemplateName.setIdentifier(Id: NewII, IdLoc: NameLoc);
398 NestedNameSpecifier NNS = Correction.getCorrectionSpecifier();
399 CXXScopeSpec NewSS, *NewSSPtr = SS;
400 if (SS && NNS) {
401 NewSS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
402 NewSSPtr = &NewSS;
403 }
404 if (Correction && (NNS || NewII != &II) &&
405 // Ignore a correction to a template type as the to-be-corrected
406 // identifier is not a template (typo correction for template names
407 // is handled elsewhere).
408 !(getLangOpts().CPlusPlus && NewSSPtr &&
409 isTemplateName(S, SS&: *NewSSPtr, hasTemplateKeyword: false, Name: TemplateName, ObjectType: nullptr, EnteringContext: false,
410 Template, MemberOfUnknownSpecialization))) {
411 ParsedType Ty = getTypeName(II: *NewII, NameLoc, S, SS: NewSSPtr,
412 isClassName, HasTrailingDot, ObjectTypePtr,
413 IsCtorOrDtorName,
414 WantNontrivialTypeSourceInfo,
415 IsClassTemplateDeductionContext);
416 if (Ty) {
417 diagnoseTypo(Correction,
418 TypoDiag: PDiag(DiagID: diag::err_unknown_type_or_class_name_suggest)
419 << Result.getLookupName() << isClassName);
420 if (SS && NNS)
421 SS->MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
422 *CorrectedII = NewII;
423 return Ty;
424 }
425 }
426 }
427 Result.suppressDiagnostics();
428 return nullptr;
429 case LookupResultKind::NotFoundInCurrentInstantiation:
430 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
431 QualType T = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
432 NNS: SS->getScopeRep(), Name: &II);
433 TypeLocBuilder TLB;
434 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T);
435 TL.setElaboratedKeywordLoc(SourceLocation());
436 TL.setQualifierLoc(SS->getWithLocInContext(Context));
437 TL.setNameLoc(NameLoc);
438 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
439 }
440 [[fallthrough]];
441 case LookupResultKind::FoundOverloaded:
442 case LookupResultKind::FoundUnresolvedValue:
443 Result.suppressDiagnostics();
444 return nullptr;
445
446 case LookupResultKind::Ambiguous:
447 // Recover from type-hiding ambiguities by hiding the type. We'll
448 // do the lookup again when looking for an object, and we can
449 // diagnose the error then. If we don't do this, then the error
450 // about hiding the type will be immediately followed by an error
451 // that only makes sense if the identifier was treated like a type.
452 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
453 Result.suppressDiagnostics();
454 return nullptr;
455 }
456
457 // Look to see if we have a type anywhere in the list of results.
458 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
459 Res != ResEnd; ++Res) {
460 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
461 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
462 Val: RealRes) ||
463 (AllowDeducedTemplate && getAsTypeTemplateDecl(D: RealRes))) {
464 if (!IIDecl ||
465 // Make the selection of the recovery decl deterministic.
466 RealRes->getLocation() < IIDecl->getLocation()) {
467 IIDecl = RealRes;
468 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Res);
469 }
470 }
471 }
472
473 if (!IIDecl) {
474 // None of the entities we found is a type, so there is no way
475 // to even assume that the result is a type. In this case, don't
476 // complain about the ambiguity. The parser will either try to
477 // perform this lookup again (e.g., as an object name), which
478 // will produce the ambiguity, or will complain that it expected
479 // a type name.
480 Result.suppressDiagnostics();
481 return nullptr;
482 }
483
484 // We found a type within the ambiguous lookup; diagnose the
485 // ambiguity and then return that type. This might be the right
486 // answer, or it might not be, but it suppresses any attempt to
487 // perform the name lookup again.
488 break;
489
490 case LookupResultKind::Found:
491 IIDecl = Result.getFoundDecl();
492 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Result.begin());
493 break;
494 }
495
496 assert(IIDecl && "Didn't find decl");
497
498 TypeLocBuilder TLB;
499 if (TypeDecl *TD = dyn_cast<TypeDecl>(Val: IIDecl)) {
500 checkTypeDeclType(LookupCtx,
501 DCK: IsImplicitTypename ? DiagCtorKind::Implicit
502 : DiagCtorKind::None,
503 TD, NameLoc);
504 QualType T;
505 if (FoundUsingShadow) {
506 T = Context.getUsingType(Keyword: ElaboratedTypeKeyword::None,
507 Qualifier: SS ? SS->getScopeRep() : std::nullopt,
508 D: FoundUsingShadow);
509 if (!WantNontrivialTypeSourceInfo)
510 return ParsedType::make(P: T);
511 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
512 QualifierLoc: SS ? SS->getWithLocInContext(Context)
513 : NestedNameSpecifierLoc(),
514 NameLoc);
515 } else if (auto *Tag = dyn_cast<TagDecl>(Val: TD)) {
516 T = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
517 Qualifier: SS ? SS->getScopeRep() : std::nullopt, TD: Tag,
518 /*OwnsTag=*/false);
519 if (!WantNontrivialTypeSourceInfo)
520 return ParsedType::make(P: T);
521 auto TL = TLB.push<TagTypeLoc>(T);
522 TL.setElaboratedKeywordLoc(SourceLocation());
523 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
524 : NestedNameSpecifierLoc());
525 TL.setNameLoc(NameLoc);
526 } else if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TD);
527 TN && !isa<ObjCTypeParamDecl>(Val: TN)) {
528 T = Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
529 Qualifier: SS ? SS->getScopeRep() : std::nullopt, Decl: TN);
530 if (!WantNontrivialTypeSourceInfo)
531 return ParsedType::make(P: T);
532 TLB.push<TypedefTypeLoc>(T).set(
533 /*ElaboratedKeywordLoc=*/SourceLocation(),
534 QualifierLoc: SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
535 NameLoc);
536 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TD)) {
537 T = Context.getUnresolvedUsingType(Keyword: ElaboratedTypeKeyword::None,
538 Qualifier: SS ? SS->getScopeRep() : std::nullopt,
539 D: UD);
540 if (!WantNontrivialTypeSourceInfo)
541 return ParsedType::make(P: T);
542 TLB.push<UnresolvedUsingTypeLoc>(T).set(
543 /*ElaboratedKeywordLoc=*/SourceLocation(),
544 QualifierLoc: SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
545 NameLoc);
546 } else {
547 T = Context.getTypeDeclType(Decl: TD);
548 if (!WantNontrivialTypeSourceInfo)
549 return ParsedType::make(P: T);
550 if (isa<ObjCTypeParamType>(Val: T))
551 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
552 else
553 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
554 }
555 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
556 }
557
558 if (getLangOpts().HLSL) {
559 if (auto *TD = dyn_cast_or_null<TemplateDecl>(
560 Val: getAsTemplateNameDecl(D: IIDecl, /*AllowFunctionTemplates=*/false,
561 /*AllowDependent=*/false))) {
562 QualType ShorthandTy = HLSL().ActOnTemplateShorthand(Template: TD, NameLoc);
563 if (!ShorthandTy.isNull())
564 return ParsedType::make(P: ShorthandTy);
565 }
566 }
567
568 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(Val: IIDecl)) {
569 (void)DiagnoseUseOfDecl(D: IDecl, Locs: NameLoc);
570 if (!HasTrailingDot) {
571 // FIXME: Support UsingType for this case.
572 QualType T = Context.getObjCInterfaceType(Decl: IDecl);
573 if (!WantNontrivialTypeSourceInfo)
574 return ParsedType::make(P: T);
575 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
576 TL.setNameLoc(NameLoc);
577 // FIXME: Pass in this source location.
578 TL.setNameEndLoc(NameLoc);
579 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
580 }
581 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: IIDecl)) {
582 (void)DiagnoseUseOfDecl(D: UD, Locs: NameLoc);
583 // Recover with 'int'
584 return ParsedType::make(P: Context.IntTy);
585 } else if (AllowDeducedTemplate) {
586 if (auto *TD = getAsTypeTemplateDecl(D: IIDecl)) {
587 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
588 // FIXME: Support UsingType here.
589 TemplateName Template = Context.getQualifiedTemplateName(
590 Qualifier: SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
591 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
592 QualType T = Context.getDeducedTemplateSpecializationType(
593 DK: DeducedKind::Undeduced, DeducedAsType: QualType(), Keyword: ElaboratedTypeKeyword::None,
594 Template);
595 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
596 TL.setElaboratedKeywordLoc(SourceLocation());
597 TL.setNameLoc(NameLoc);
598 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
599 : NestedNameSpecifierLoc());
600 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
601 }
602 }
603
604 // As it's not plausibly a type, suppress diagnostics.
605 Result.suppressDiagnostics();
606 return nullptr;
607}
608
609// Builds a fake NNS for the given decl context.
610static NestedNameSpecifier
611synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
612 for (;; DC = DC->getLookupParent()) {
613 DC = DC->getPrimaryContext();
614 auto *ND = dyn_cast<NamespaceDecl>(Val: DC);
615 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
616 return NestedNameSpecifier(Context, ND, std::nullopt);
617 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
618 return NestedNameSpecifier(Context.getCanonicalTagType(TD: RD)->getTypePtr());
619 if (isa<TranslationUnitDecl>(Val: DC))
620 return NestedNameSpecifier::getGlobal();
621 }
622 llvm_unreachable("something isn't in TU scope?");
623}
624
625/// Find the parent class with dependent bases of the innermost enclosing method
626/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
627/// up allowing unqualified dependent type names at class-level, which MSVC
628/// correctly rejects.
629static const CXXRecordDecl *
630findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
631 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
632 DC = DC->getPrimaryContext();
633 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
634 if (MD->getParent()->hasAnyDependentBases())
635 return MD->getParent();
636 }
637 return nullptr;
638}
639
640ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
641 SourceLocation NameLoc,
642 bool IsTemplateTypeArg) {
643 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
644
645 NestedNameSpecifier NNS = std::nullopt;
646 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
647 // If we weren't able to parse a default template argument, delay lookup
648 // until instantiation time by making a non-dependent DependentTypeName. We
649 // pretend we saw a NestedNameSpecifier referring to the current scope, and
650 // lookup is retried.
651 // FIXME: This hurts our diagnostic quality, since we get errors like "no
652 // type named 'Foo' in 'current_namespace'" when the user didn't write any
653 // name specifiers.
654 NNS = synthesizeCurrentNestedNameSpecifier(Context, DC: CurContext);
655 Diag(Loc: NameLoc, DiagID: diag::ext_ms_delayed_template_argument) << &II;
656 } else if (const CXXRecordDecl *RD =
657 findRecordWithDependentBasesOfEnclosingMethod(DC: CurContext)) {
658 // Build a DependentNameType that will perform lookup into RD at
659 // instantiation time.
660 NNS = NestedNameSpecifier(Context.getCanonicalTagType(TD: RD)->getTypePtr());
661
662 // Diagnose that this identifier was undeclared, and retry the lookup during
663 // template instantiation.
664 Diag(Loc: NameLoc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base) << &II
665 << RD;
666 } else {
667 // This is not a situation that we should recover from.
668 return ParsedType();
669 }
670
671 QualType T =
672 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
673
674 // Build type location information. We synthesized the qualifier, so we have
675 // to build a fake NestedNameSpecifierLoc.
676 NestedNameSpecifierLocBuilder NNSLocBuilder;
677 NNSLocBuilder.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
678 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
679
680 TypeLocBuilder Builder;
681 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
682 DepTL.setNameLoc(NameLoc);
683 DepTL.setElaboratedKeywordLoc(SourceLocation());
684 DepTL.setQualifierLoc(QualifierLoc);
685 return CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
686}
687
688DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
689 // Do a tag name lookup in this scope.
690 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
691 LookupName(R, S, AllowBuiltinCreation: false);
692 R.suppressDiagnostics();
693 if (R.getResultKind() == LookupResultKind::Found)
694 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
695 switch (TD->getTagKind()) {
696 case TagTypeKind::Struct:
697 return DeclSpec::TST_struct;
698 case TagTypeKind::Interface:
699 return DeclSpec::TST_interface;
700 case TagTypeKind::Union:
701 return DeclSpec::TST_union;
702 case TagTypeKind::Class:
703 return DeclSpec::TST_class;
704 case TagTypeKind::Enum:
705 return DeclSpec::TST_enum;
706 }
707 }
708
709 return DeclSpec::TST_unspecified;
710}
711
712bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
713 if (!CurContext->isRecord())
714 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
715
716 switch (SS->getScopeRep().getKind()) {
717 case NestedNameSpecifier::Kind::MicrosoftSuper:
718 return true;
719 case NestedNameSpecifier::Kind::Type: {
720 QualType T(SS->getScopeRep().getAsType(), 0);
721 for (const auto &Base : cast<CXXRecordDecl>(Val: CurContext)->bases())
722 if (Context.hasSameUnqualifiedType(T1: T, T2: Base.getType()))
723 return true;
724 [[fallthrough]];
725 }
726 default:
727 return S->isFunctionPrototypeScope();
728 }
729}
730
731void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
732 SourceLocation IILoc,
733 Scope *S,
734 CXXScopeSpec *SS,
735 ParsedType &SuggestedType,
736 bool IsTemplateName) {
737 // Don't report typename errors for editor placeholders.
738 if (II->isEditorPlaceholder())
739 return;
740 // We don't have anything to suggest (yet).
741 SuggestedType = nullptr;
742
743 // There may have been a typo in the name of the type. Look up typo
744 // results, in case we have something that we can suggest.
745 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
746 /*AllowTemplates=*/IsTemplateName,
747 /*AllowNonTemplates=*/!IsTemplateName);
748 if (TypoCorrection Corrected =
749 CorrectTypo(Typo: DeclarationNameInfo(II, IILoc), LookupKind: LookupOrdinaryName, S, SS,
750 CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
751 // FIXME: Support error recovery for the template-name case.
752 bool CanRecover = !IsTemplateName;
753 if (Corrected.isKeyword()) {
754 // We corrected to a keyword.
755 diagnoseTypo(Correction: Corrected,
756 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
757 : diag::err_unknown_typename_suggest)
758 << II);
759 II = Corrected.getCorrectionAsIdentifierInfo();
760 } else {
761 // We found a similarly-named type or interface; suggest that.
762 if (!SS || !SS->isSet()) {
763 diagnoseTypo(Correction: Corrected,
764 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
765 : diag::err_unknown_typename_suggest)
766 << II, ErrorRecovery: CanRecover);
767 } else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false)) {
768 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
769 bool DroppedSpecifier =
770 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
771 diagnoseTypo(Correction: Corrected,
772 TypoDiag: PDiag(DiagID: IsTemplateName
773 ? diag::err_no_member_template_suggest
774 : diag::err_unknown_nested_typename_suggest)
775 << II << DC << DroppedSpecifier << SS->getRange(),
776 ErrorRecovery: CanRecover);
777 } else {
778 llvm_unreachable("could not have corrected a typo here");
779 }
780
781 if (!CanRecover)
782 return;
783
784 CXXScopeSpec tmpSS;
785 if (Corrected.getCorrectionSpecifier())
786 tmpSS.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
787 R: SourceRange(IILoc));
788 // FIXME: Support class template argument deduction here.
789 SuggestedType =
790 getTypeName(II: *Corrected.getCorrectionAsIdentifierInfo(), NameLoc: IILoc, S,
791 SS: tmpSS.isSet() ? &tmpSS : SS, isClassName: false, HasTrailingDot: false, ObjectTypePtr: nullptr,
792 /*IsCtorOrDtorName=*/false,
793 /*WantNontrivialTypeSourceInfo=*/true);
794 }
795 return;
796 }
797
798 if (getLangOpts().CPlusPlus && !IsTemplateName) {
799 // See if II is a class template that the user forgot to pass arguments to.
800 UnqualifiedId Name;
801 Name.setIdentifier(Id: II, IdLoc: IILoc);
802 CXXScopeSpec EmptySS;
803 TemplateTy TemplateResult;
804 bool MemberOfUnknownSpecialization;
805 if (isTemplateName(S, SS&: SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
806 Name, ObjectType: nullptr, EnteringContext: true, Template&: TemplateResult,
807 MemberOfUnknownSpecialization) == TNK_Type_template) {
808 diagnoseMissingTemplateArguments(Name: TemplateResult.get(), Loc: IILoc);
809 return;
810 }
811 }
812
813 // FIXME: Should we move the logic that tries to recover from a missing tag
814 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
815
816 if (!SS || (!SS->isSet() && !SS->isInvalid()))
817 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_template
818 : diag::err_unknown_typename)
819 << II;
820 else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false))
821 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_member_template
822 : diag::err_typename_nested_not_found)
823 << II << DC << SS->getRange();
824 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
825 SuggestedType =
826 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
827 } else if (isDependentScopeSpecifier(SS: *SS)) {
828 unsigned DiagID = diag::err_typename_missing;
829 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
830 DiagID = diag::ext_typename_missing;
831
832 SuggestedType =
833 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
834
835 Diag(Loc: SS->getRange().getBegin(), DiagID)
836 << GetTypeFromParser(Ty: SuggestedType)
837 << SourceRange(SS->getRange().getBegin(), IILoc)
838 << FixItHint::CreateInsertion(InsertionLoc: SS->getRange().getBegin(), Code: "typename ");
839 } else {
840 assert(SS && SS->isInvalid() &&
841 "Invalid scope specifier has already been diagnosed");
842 }
843}
844
845/// Determine whether the given result set contains either a type name
846/// or
847static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
848 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
849 NextToken.is(K: tok::less);
850
851 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
852 if (isa<TypeDecl>(Val: *I) || isa<ObjCInterfaceDecl>(Val: *I))
853 return true;
854
855 if (CheckTemplate && isa<TemplateDecl>(Val: *I))
856 return true;
857 }
858
859 return false;
860}
861
862static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
863 Scope *S, CXXScopeSpec &SS,
864 IdentifierInfo *&Name,
865 SourceLocation NameLoc) {
866 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
867 SemaRef.LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
868 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
869 StringRef FixItTagName;
870 switch (Tag->getTagKind()) {
871 case TagTypeKind::Class:
872 FixItTagName = "class ";
873 break;
874
875 case TagTypeKind::Enum:
876 FixItTagName = "enum ";
877 break;
878
879 case TagTypeKind::Struct:
880 FixItTagName = "struct ";
881 break;
882
883 case TagTypeKind::Interface:
884 FixItTagName = "__interface ";
885 break;
886
887 case TagTypeKind::Union:
888 FixItTagName = "union ";
889 break;
890 }
891
892 StringRef TagName = FixItTagName.drop_back();
893 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_use_of_tag_name_without_tag)
894 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
895 << FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: FixItTagName);
896
897 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
898 I != IEnd; ++I)
899 SemaRef.Diag(Loc: (*I)->getLocation(), DiagID: diag::note_decl_hiding_tag_type)
900 << Name << TagName;
901
902 // Replace lookup results with just the tag decl.
903 Result.clear(Kind: Sema::LookupTagName);
904 SemaRef.LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType());
905 return true;
906 }
907
908 return false;
909}
910
911Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
912 IdentifierInfo *&Name,
913 SourceLocation NameLoc,
914 const Token &NextToken,
915 CorrectionCandidateCallback *CCC) {
916 DeclarationNameInfo NameInfo(Name, NameLoc);
917 ObjCMethodDecl *CurMethod = getCurMethodDecl();
918
919 assert(NextToken.isNot(tok::coloncolon) &&
920 "parse nested name specifiers before calling ClassifyName");
921 if (getLangOpts().CPlusPlus && SS.isSet() &&
922 isCurrentClassName(II: *Name, S, SS: &SS)) {
923 // Per [class.qual]p2, this names the constructors of SS, not the
924 // injected-class-name. We don't have a classification for that.
925 // There's not much point caching this result, since the parser
926 // will reject it later.
927 return NameClassification::Unknown();
928 }
929
930 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
931 LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType(),
932 /*AllowBuiltinCreation=*/!CurMethod);
933
934 if (SS.isInvalid())
935 return NameClassification::Error();
936
937 // For unqualified lookup in a class template in MSVC mode, look into
938 // dependent base classes where the primary class template is known.
939 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
940 if (ParsedType TypeInBase =
941 recoverFromTypeInKnownDependentBase(S&: *this, II: *Name, NameLoc))
942 return TypeInBase;
943 }
944
945 // Perform lookup for Objective-C instance variables (including automatically
946 // synthesized instance variables), if we're in an Objective-C method.
947 // FIXME: This lookup really, really needs to be folded in to the normal
948 // unqualified lookup mechanism.
949 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(R&: Result, NextToken)) {
950 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Name);
951 if (Ivar.isInvalid())
952 return NameClassification::Error();
953 if (Ivar.isUsable())
954 return NameClassification::NonType(D: cast<NamedDecl>(Val: Ivar.get()));
955
956 // We defer builtin creation until after ivar lookup inside ObjC methods.
957 if (Result.empty())
958 LookupBuiltin(R&: Result);
959 }
960
961 bool SecondTry = false;
962 bool IsFilteredTemplateName = false;
963
964Corrected:
965 switch (Result.getResultKind()) {
966 case LookupResultKind::NotFound:
967 // If an unqualified-id is followed by a '(', then we have a function
968 // call.
969 if (SS.isEmpty() && NextToken.is(K: tok::l_paren)) {
970 // In C++, this is an ADL-only call.
971 // FIXME: Reference?
972 if (getLangOpts().CPlusPlus)
973 return NameClassification::UndeclaredNonType();
974
975 // C90 6.3.2.2:
976 // If the expression that precedes the parenthesized argument list in a
977 // function call consists solely of an identifier, and if no
978 // declaration is visible for this identifier, the identifier is
979 // implicitly declared exactly as if, in the innermost block containing
980 // the function call, the declaration
981 //
982 // extern int identifier ();
983 //
984 // appeared.
985 //
986 // We also allow this in C99 as an extension. However, this is not
987 // allowed in all language modes as functions without prototypes may not
988 // be supported.
989 if (getLangOpts().implicitFunctionsAllowed()) {
990 if (NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *Name, S))
991 return NameClassification::NonType(D);
992 }
993 }
994
995 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(K: tok::less)) {
996 // In C++20 onwards, this could be an ADL-only call to a function
997 // template, and we're required to assume that this is a template name.
998 //
999 // FIXME: Find a way to still do typo correction in this case.
1000 TemplateName Template =
1001 Context.getAssumedTemplateName(Name: NameInfo.getName());
1002 return NameClassification::UndeclaredTemplate(Name: Template);
1003 }
1004
1005 // In C, we first see whether there is a tag type by the same name, in
1006 // which case it's likely that the user just forgot to write "enum",
1007 // "struct", or "union".
1008 if (!getLangOpts().CPlusPlus && !SecondTry &&
1009 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1010 break;
1011 }
1012
1013 // Perform typo correction to determine if there is another name that is
1014 // close to this name.
1015 if (!SecondTry && CCC) {
1016 SecondTry = true;
1017 if (TypoCorrection Corrected =
1018 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Result.getLookupKind(), S,
1019 SS: &SS, CCC&: *CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
1020 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1021 unsigned QualifiedDiag = diag::err_no_member_suggest;
1022
1023 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1024 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1025 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1026 UnderlyingFirstDecl && isa<TemplateDecl>(Val: UnderlyingFirstDecl)) {
1027 UnqualifiedDiag = diag::err_no_template_suggest;
1028 QualifiedDiag = diag::err_no_member_template_suggest;
1029 } else if (UnderlyingFirstDecl &&
1030 (isa<TypeDecl>(Val: UnderlyingFirstDecl) ||
1031 isa<ObjCInterfaceDecl>(Val: UnderlyingFirstDecl) ||
1032 isa<ObjCCompatibleAliasDecl>(Val: UnderlyingFirstDecl))) {
1033 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1034 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1035 }
1036
1037 if (SS.isEmpty()) {
1038 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: UnqualifiedDiag) << Name);
1039 } else {// FIXME: is this even reachable? Test it.
1040 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
1041 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1042 Name->getName() == CorrectedStr;
1043 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: QualifiedDiag)
1044 << Name << computeDeclContext(SS, EnteringContext: false)
1045 << DroppedSpecifier << SS.getRange());
1046 }
1047
1048 // Update the name, so that the caller has the new name.
1049 Name = Corrected.getCorrectionAsIdentifierInfo();
1050
1051 // Typo correction corrected to a keyword.
1052 if (Corrected.isKeyword())
1053 return Name;
1054
1055 // Also update the LookupResult...
1056 // FIXME: This should probably go away at some point
1057 Result.clear();
1058 Result.setLookupName(Corrected.getCorrection());
1059 if (FirstDecl)
1060 Result.addDecl(D: FirstDecl);
1061
1062 // If we found an Objective-C instance variable, let
1063 // LookupInObjCMethod build the appropriate expression to
1064 // reference the ivar.
1065 // FIXME: This is a gross hack.
1066 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1067 DeclResult R =
1068 ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Ivar->getIdentifier());
1069 if (R.isInvalid())
1070 return NameClassification::Error();
1071 if (R.isUsable())
1072 return NameClassification::NonType(D: Ivar);
1073 }
1074
1075 goto Corrected;
1076 }
1077 }
1078
1079 // We failed to correct; just fall through and let the parser deal with it.
1080 Result.suppressDiagnostics();
1081 return NameClassification::Unknown();
1082
1083 case LookupResultKind::NotFoundInCurrentInstantiation: {
1084 // We performed name lookup into the current instantiation, and there were
1085 // dependent bases, so we treat this result the same way as any other
1086 // dependent nested-name-specifier.
1087
1088 // C++ [temp.res]p2:
1089 // A name used in a template declaration or definition and that is
1090 // dependent on a template-parameter is assumed not to name a type
1091 // unless the applicable name lookup finds a type name or the name is
1092 // qualified by the keyword typename.
1093 //
1094 // FIXME: If the next token is '<', we might want to ask the parser to
1095 // perform some heroics to see if we actually have a
1096 // template-argument-list, which would indicate a missing 'template'
1097 // keyword here.
1098 return NameClassification::DependentNonType();
1099 }
1100
1101 case LookupResultKind::Found:
1102 case LookupResultKind::FoundOverloaded:
1103 case LookupResultKind::FoundUnresolvedValue:
1104 break;
1105
1106 case LookupResultKind::Ambiguous:
1107 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1108 hasAnyAcceptableTemplateNames(R&: Result, /*AllowFunctionTemplates=*/true,
1109 /*AllowDependent=*/false)) {
1110 // C++ [temp.local]p3:
1111 // A lookup that finds an injected-class-name (10.2) can result in an
1112 // ambiguity in certain cases (for example, if it is found in more than
1113 // one base class). If all of the injected-class-names that are found
1114 // refer to specializations of the same class template, and if the name
1115 // is followed by a template-argument-list, the reference refers to the
1116 // class template itself and not a specialization thereof, and is not
1117 // ambiguous.
1118 //
1119 // This filtering can make an ambiguous result into an unambiguous one,
1120 // so try again after filtering out template names.
1121 FilterAcceptableTemplateNames(R&: Result);
1122 if (!Result.isAmbiguous()) {
1123 IsFilteredTemplateName = true;
1124 break;
1125 }
1126 }
1127
1128 // Diagnose the ambiguity and return an error.
1129 return NameClassification::Error();
1130 }
1131
1132 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1133 (IsFilteredTemplateName ||
1134 hasAnyAcceptableTemplateNames(
1135 R&: Result, /*AllowFunctionTemplates=*/true,
1136 /*AllowDependent=*/false,
1137 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1138 getLangOpts().CPlusPlus20))) {
1139 // C++ [temp.names]p3:
1140 // After name lookup (3.4) finds that a name is a template-name or that
1141 // an operator-function-id or a literal- operator-id refers to a set of
1142 // overloaded functions any member of which is a function template if
1143 // this is followed by a <, the < is always taken as the delimiter of a
1144 // template-argument-list and never as the less-than operator.
1145 // C++2a [temp.names]p2:
1146 // A name is also considered to refer to a template if it is an
1147 // unqualified-id followed by a < and name lookup finds either one
1148 // or more functions or finds nothing.
1149 if (!IsFilteredTemplateName)
1150 FilterAcceptableTemplateNames(R&: Result);
1151
1152 bool IsFunctionTemplate;
1153 bool IsVarTemplate;
1154 TemplateName Template;
1155 if (Result.end() - Result.begin() > 1) {
1156 IsFunctionTemplate = true;
1157 Template = Context.getOverloadedTemplateName(Begin: Result.begin(),
1158 End: Result.end());
1159 } else if (!Result.empty()) {
1160 auto *TD = cast<TemplateDecl>(Val: getAsTemplateNameDecl(
1161 D: *Result.begin(), /*AllowFunctionTemplates=*/true,
1162 /*AllowDependent=*/false));
1163 IsFunctionTemplate = isa<FunctionTemplateDecl>(Val: TD);
1164 IsVarTemplate = isa<VarTemplateDecl>(Val: TD);
1165
1166 UsingShadowDecl *FoundUsingShadow =
1167 dyn_cast<UsingShadowDecl>(Val: *Result.begin());
1168 assert(!FoundUsingShadow ||
1169 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1170 Template = Context.getQualifiedTemplateName(
1171 Qualifier: SS.getScopeRep(),
1172 /*TemplateKeyword=*/false,
1173 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1174 } else {
1175 // All results were non-template functions. This is a function template
1176 // name.
1177 IsFunctionTemplate = true;
1178 Template = Context.getAssumedTemplateName(Name: NameInfo.getName());
1179 }
1180
1181 if (IsFunctionTemplate) {
1182 // Function templates always go through overload resolution, at which
1183 // point we'll perform the various checks (e.g., accessibility) we need
1184 // to based on which function we selected.
1185 Result.suppressDiagnostics();
1186
1187 return NameClassification::FunctionTemplate(Name: Template);
1188 }
1189
1190 return IsVarTemplate ? NameClassification::VarTemplate(Name: Template)
1191 : NameClassification::TypeTemplate(Name: Template);
1192 }
1193
1194 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1195 QualType T;
1196 TypeLocBuilder TLB;
1197 if (const auto *USD = dyn_cast<UsingShadowDecl>(Val: Found)) {
1198 T = Context.getUsingType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
1199 D: USD);
1200 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1201 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1202 } else {
1203 T = Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
1204 Decl: Type);
1205 if (isa<TagType>(Val: T)) {
1206 auto TTL = TLB.push<TagTypeLoc>(T);
1207 TTL.setElaboratedKeywordLoc(SourceLocation());
1208 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1209 TTL.setNameLoc(NameLoc);
1210 } else if (isa<TypedefType>(Val: T)) {
1211 TLB.push<TypedefTypeLoc>(T).set(
1212 /*ElaboratedKeywordLoc=*/SourceLocation(),
1213 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1214 } else if (isa<UnresolvedUsingType>(Val: T)) {
1215 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1216 /*ElaboratedKeywordLoc=*/SourceLocation(),
1217 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1218 } else {
1219 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1220 }
1221 }
1222 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
1223 };
1224
1225 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1226 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: FirstDecl)) {
1227 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1228 MarkAnyDeclReferenced(Loc: Type->getLocation(), D: Type, /*OdrUse=*/MightBeOdrUse: false);
1229 return BuildTypeFor(Type, *Result.begin());
1230 }
1231
1232 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Val: FirstDecl);
1233 if (!Class) {
1234 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1235 if (ObjCCompatibleAliasDecl *Alias =
1236 dyn_cast<ObjCCompatibleAliasDecl>(Val: FirstDecl))
1237 Class = Alias->getClassInterface();
1238 }
1239
1240 if (Class) {
1241 DiagnoseUseOfDecl(D: Class, Locs: NameLoc);
1242
1243 if (NextToken.is(K: tok::period)) {
1244 // Interface. <something> is parsed as a property reference expression.
1245 // Just return "unknown" as a fall-through for now.
1246 Result.suppressDiagnostics();
1247 return NameClassification::Unknown();
1248 }
1249
1250 QualType T = Context.getObjCInterfaceType(Decl: Class);
1251 return ParsedType::make(P: T);
1252 }
1253
1254 if (isa<ConceptDecl>(Val: FirstDecl)) {
1255 // We want to preserve the UsingShadowDecl for concepts.
1256 if (auto *USD = dyn_cast<UsingShadowDecl>(Val: Result.getRepresentativeDecl()))
1257 return NameClassification::Concept(Name: TemplateName(USD));
1258 return NameClassification::Concept(
1259 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1260 }
1261
1262 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: FirstDecl)) {
1263 (void)DiagnoseUseOfDecl(D: EmptyD, Locs: NameLoc);
1264 return NameClassification::Error();
1265 }
1266
1267 // We can have a type template here if we're classifying a template argument.
1268 if (isa<TemplateDecl>(Val: FirstDecl) && !isa<FunctionTemplateDecl>(Val: FirstDecl) &&
1269 !isa<VarTemplateDecl>(Val: FirstDecl))
1270 return NameClassification::TypeTemplate(
1271 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1272
1273 // Check for a tag type hidden by a non-type decl in a few cases where it
1274 // seems likely a type is wanted instead of the non-type that was found.
1275 bool NextIsOp = NextToken.isOneOf(Ks: tok::amp, Ks: tok::star);
1276 if ((NextToken.is(K: tok::identifier) ||
1277 (NextIsOp &&
1278 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1279 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1280 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1281 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1282 return BuildTypeFor(Type, *Result.begin());
1283 }
1284
1285 // If we already know which single declaration is referenced, just annotate
1286 // that declaration directly. Defer resolving even non-overloaded class
1287 // member accesses, as we need to defer certain access checks until we know
1288 // the context.
1289 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1290 if (Result.isSingleResult() && !ADL &&
1291 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(Val: FirstDecl)))
1292 return NameClassification::NonType(D: Result.getRepresentativeDecl());
1293
1294 // Otherwise, this is an overload set that we will need to resolve later.
1295 Result.suppressDiagnostics();
1296 return NameClassification::OverloadSet(E: UnresolvedLookupExpr::Create(
1297 Context, NamingClass: Result.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
1298 NameInfo: Result.getLookupNameInfo(), RequiresADL: ADL, Begin: Result.begin(), End: Result.end(),
1299 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1300}
1301
1302ExprResult
1303Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1304 SourceLocation NameLoc) {
1305 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1306 CXXScopeSpec SS;
1307 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1308 return BuildDeclarationNameExpr(SS, R&: Result, /*ADL=*/NeedsADL: true);
1309}
1310
1311ExprResult
1312Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1313 IdentifierInfo *Name,
1314 SourceLocation NameLoc,
1315 bool IsAddressOfOperand) {
1316 DeclarationNameInfo NameInfo(Name, NameLoc);
1317 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1318 NameInfo, isAddressOfOperand: IsAddressOfOperand,
1319 /*TemplateArgs=*/nullptr);
1320}
1321
1322ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1323 NamedDecl *Found,
1324 SourceLocation NameLoc,
1325 const Token &NextToken) {
1326 if (getCurMethodDecl() && SS.isEmpty())
1327 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Val: Found->getUnderlyingDecl()))
1328 return ObjC().BuildIvarRefExpr(S, Loc: NameLoc, IV: Ivar);
1329
1330 // Reconstruct the lookup result.
1331 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1332 Result.addDecl(D: Found);
1333 Result.resolveKind();
1334
1335 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1336 return BuildDeclarationNameExpr(SS, R&: Result, NeedsADL: ADL, /*AcceptInvalidDecl=*/true);
1337}
1338
1339ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1340 // For an implicit class member access, transform the result into a member
1341 // access expression if necessary.
1342 auto *ULE = cast<UnresolvedLookupExpr>(Val: E);
1343 if ((*ULE->decls_begin())->isCXXClassMember()) {
1344 CXXScopeSpec SS;
1345 SS.Adopt(Other: ULE->getQualifierLoc());
1346
1347 // Reconstruct the lookup result.
1348 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1349 LookupOrdinaryName);
1350 Result.setNamingClass(ULE->getNamingClass());
1351 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1352 Result.addDecl(D: *I, AS: I.getAccess());
1353 Result.resolveKind();
1354 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc: SourceLocation(), R&: Result,
1355 TemplateArgs: nullptr, S);
1356 }
1357
1358 // Otherwise, this is already in the form we needed, and no further checks
1359 // are necessary.
1360 return ULE;
1361}
1362
1363Sema::TemplateNameKindForDiagnostics
1364Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1365 auto *TD = Name.getAsTemplateDecl();
1366 if (!TD)
1367 return TemplateNameKindForDiagnostics::DependentTemplate;
1368 if (isa<ClassTemplateDecl>(Val: TD))
1369 return TemplateNameKindForDiagnostics::ClassTemplate;
1370 if (isa<FunctionTemplateDecl>(Val: TD))
1371 return TemplateNameKindForDiagnostics::FunctionTemplate;
1372 if (isa<VarTemplateDecl>(Val: TD))
1373 return TemplateNameKindForDiagnostics::VarTemplate;
1374 if (isa<TypeAliasTemplateDecl>(Val: TD))
1375 return TemplateNameKindForDiagnostics::AliasTemplate;
1376 if (isa<TemplateTemplateParmDecl>(Val: TD))
1377 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1378 if (isa<ConceptDecl>(Val: TD))
1379 return TemplateNameKindForDiagnostics::Concept;
1380 return TemplateNameKindForDiagnostics::DependentTemplate;
1381}
1382
1383void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1384 assert(DC->getLexicalParent() == CurContext &&
1385 "The next DeclContext should be lexically contained in the current one.");
1386 CurContext = DC;
1387 if (S)
1388 S->setEntity(DC);
1389}
1390
1391void Sema::PopDeclContext() {
1392 assert(CurContext && "DeclContext imbalance!");
1393
1394 CurContext = CurContext->getLexicalParent();
1395 assert(CurContext && "Popped translation unit!");
1396}
1397
1398Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1399 Decl *D) {
1400 // Unlike PushDeclContext, the context to which we return is not necessarily
1401 // the containing DC of TD, because the new context will be some pre-existing
1402 // TagDecl definition instead of a fresh one.
1403 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1404 CurContext = cast<TagDecl>(Val: D)->getDefinition();
1405 assert(CurContext && "skipping definition of undefined tag");
1406 // Start lookups from the parent of the current context; we don't want to look
1407 // into the pre-existing complete definition.
1408 S->setEntity(CurContext->getLookupParent());
1409 return Result;
1410}
1411
1412void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1413 CurContext = static_cast<decltype(CurContext)>(Context);
1414}
1415
1416void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1417 // C++0x [basic.lookup.unqual]p13:
1418 // A name used in the definition of a static data member of class
1419 // X (after the qualified-id of the static member) is looked up as
1420 // if the name was used in a member function of X.
1421 // C++0x [basic.lookup.unqual]p14:
1422 // If a variable member of a namespace is defined outside of the
1423 // scope of its namespace then any name used in the definition of
1424 // the variable member (after the declarator-id) is looked up as
1425 // if the definition of the variable member occurred in its
1426 // namespace.
1427 // Both of these imply that we should push a scope whose context
1428 // is the semantic context of the declaration. We can't use
1429 // PushDeclContext here because that context is not necessarily
1430 // lexically contained in the current context. Fortunately,
1431 // the containing scope should have the appropriate information.
1432
1433 assert(!S->getEntity() && "scope already has entity");
1434
1435#ifndef NDEBUG
1436 Scope *Ancestor = S->getParent();
1437 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1438 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1439#endif
1440
1441 CurContext = DC;
1442 S->setEntity(DC);
1443
1444 if (S->getParent()->isTemplateParamScope()) {
1445 // Also set the corresponding entities for all immediately-enclosing
1446 // template parameter scopes.
1447 EnterTemplatedContext(S: S->getParent(), DC);
1448 }
1449}
1450
1451void Sema::ExitDeclaratorContext(Scope *S) {
1452 assert(S->getEntity() == CurContext && "Context imbalance!");
1453
1454 // Switch back to the lexical context. The safety of this is
1455 // enforced by an assert in EnterDeclaratorContext.
1456 Scope *Ancestor = S->getParent();
1457 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1458 CurContext = Ancestor->getEntity();
1459
1460 // We don't need to do anything with the scope, which is going to
1461 // disappear.
1462}
1463
1464void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1465 assert(S->isTemplateParamScope() &&
1466 "expected to be initializing a template parameter scope");
1467
1468 // C++20 [temp.local]p7:
1469 // In the definition of a member of a class template that appears outside
1470 // of the class template definition, the name of a member of the class
1471 // template hides the name of a template-parameter of any enclosing class
1472 // templates (but not a template-parameter of the member if the member is a
1473 // class or function template).
1474 // C++20 [temp.local]p9:
1475 // In the definition of a class template or in the definition of a member
1476 // of such a template that appears outside of the template definition, for
1477 // each non-dependent base class (13.8.2.1), if the name of the base class
1478 // or the name of a member of the base class is the same as the name of a
1479 // template-parameter, the base class name or member name hides the
1480 // template-parameter name (6.4.10).
1481 //
1482 // This means that a template parameter scope should be searched immediately
1483 // after searching the DeclContext for which it is a template parameter
1484 // scope. For example, for
1485 // template<typename T> template<typename U> template<typename V>
1486 // void N::A<T>::B<U>::f(...)
1487 // we search V then B<U> (and base classes) then U then A<T> (and base
1488 // classes) then T then N then ::.
1489 unsigned ScopeDepth = getTemplateDepth(S);
1490 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1491 DeclContext *SearchDCAfterScope = DC;
1492 for (; DC; DC = DC->getLookupParent()) {
1493 if (const TemplateParameterList *TPL =
1494 cast<Decl>(Val: DC)->getDescribedTemplateParams()) {
1495 unsigned DCDepth = TPL->getDepth() + 1;
1496 if (DCDepth > ScopeDepth)
1497 continue;
1498 if (ScopeDepth == DCDepth)
1499 SearchDCAfterScope = DC = DC->getLookupParent();
1500 break;
1501 }
1502 }
1503 S->setLookupEntity(SearchDCAfterScope);
1504 }
1505}
1506
1507void Sema::ActOnReenterFunctionPrototypeParams(Scope *S,
1508 ArrayRef<ParmVarDecl *> Params) {
1509 for (ParmVarDecl *Param : Params)
1510 if (Param->getIdentifier()) {
1511 S->AddDecl(D: Param);
1512 IdResolver.AddDecl(D: Param);
1513 }
1514}
1515
1516void Sema::ActOnExitFunctionPrototypeParams(Scope *S,
1517 ArrayRef<ParmVarDecl *> Params) {
1518 // Remove in reverse so each name is the most recent one when it is removed.
1519 for (ParmVarDecl *Param : llvm::reverse(C&: Params))
1520 if (Param->getIdentifier()) {
1521 IdResolver.RemoveDecl(D: Param);
1522 S->RemoveDecl(D: Param);
1523 }
1524}
1525
1526void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1527 // We assume that the caller has already called
1528 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1529 FunctionDecl *FD = D->getAsFunction();
1530 if (!FD)
1531 return;
1532
1533 // Same implementation as PushDeclContext, but enters the context
1534 // from the lexical parent, rather than the top-level class.
1535 assert(CurContext == FD->getLexicalParent() &&
1536 "The next DeclContext should be lexically contained in the current one.");
1537 CurContext = FD;
1538 S->setEntity(CurContext);
1539
1540 ActOnReenterFunctionPrototypeParams(S, Params: FD->parameters());
1541}
1542
1543void Sema::ActOnExitFunctionContext() {
1544 // Same implementation as PopDeclContext, but returns to the lexical parent,
1545 // rather than the top-level class.
1546 assert(CurContext && "DeclContext imbalance!");
1547 CurContext = CurContext->getLexicalParent();
1548 assert(CurContext && "Popped translation unit!");
1549}
1550
1551/// Determine whether overloading is allowed for a new function
1552/// declaration considering prior declarations of the same name.
1553///
1554/// This routine determines whether overloading is possible, not
1555/// whether a new declaration actually overloads a previous one.
1556/// It will return true in C++ (where overloads are always permitted)
1557/// or, as a C extension, when either the new declaration or a
1558/// previous one is declared with the 'overloadable' attribute.
1559static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1560 ASTContext &Context,
1561 const FunctionDecl *New) {
1562 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1563 return true;
1564
1565 // Multiversion function declarations are not overloads in the
1566 // usual sense of that term, but lookup will report that an
1567 // overload set was found if more than one multiversion function
1568 // declaration is present for the same name. It is therefore
1569 // inadequate to assume that some prior declaration(s) had
1570 // the overloadable attribute; checking is required. Since one
1571 // declaration is permitted to omit the attribute, it is necessary
1572 // to check at least two; hence the 'any_of' check below. Note that
1573 // the overloadable attribute is implicitly added to declarations
1574 // that were required to have it but did not.
1575 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1576 return llvm::any_of(Range: Previous, P: [](const NamedDecl *ND) {
1577 return ND->hasAttr<OverloadableAttr>();
1578 });
1579 } else if (Previous.getResultKind() == LookupResultKind::Found)
1580 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1581
1582 return false;
1583}
1584
1585void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1586 // Move up the scope chain until we find the nearest enclosing
1587 // non-transparent context. The declaration will be introduced into this
1588 // scope.
1589 while (S->getEntity() && S->getEntity()->isTransparentContext())
1590 S = S->getParent();
1591
1592 // Add scoped declarations into their context, so that they can be
1593 // found later. Declarations without a context won't be inserted
1594 // into any context.
1595 if (AddToContext)
1596 CurContext->addDecl(D);
1597
1598 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1599 // are function-local declarations.
1600 if (getLangOpts().CPlusPlus && D->isOutOfLine()) {
1601 if (!S->getFnParent())
1602 return;
1603
1604 // Even inside a function, an out-of-line definition of a type that is
1605 // nested inside a local class must not be pushed into the enclosing
1606 // function scope. For example:
1607 //
1608 // class A { public: class B; };
1609 // class A::B {}; // out-of-line definition inside the function
1610 // B b; // must fail - only A::B is valid
1611 // Wrapper{B{}} // must also fail
1612 //
1613 // Per C++ scoping rules only the qualified form A::B is accessible.
1614 // Without this guard, PushOnScopeChains would add B to the function's
1615 // local scope, making it findable via unqualified lookup, which is
1616 // incorrect. The condition targets TagDecls (class/struct/union/enum)
1617 // whose DeclContext is a CXXRecordDecl, i.e., types that are members
1618 // of a local class being defined out-of-line.
1619 if (isa<TagDecl>(Val: D) && isa<CXXRecordDecl>(Val: D->getDeclContext()))
1620 return;
1621 }
1622
1623 // Template instantiations should also not be pushed into scope.
1624 if (isa<FunctionDecl>(Val: D) &&
1625 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization())
1626 return;
1627
1628 if (isa<UsingEnumDecl>(Val: D) && D->getDeclName().isEmpty()) {
1629 S->AddDecl(D);
1630 return;
1631 }
1632 // If this replaces anything in the current scope,
1633 IdentifierResolver::iterator I = IdResolver.begin(Name: D->getDeclName()),
1634 IEnd = IdResolver.end();
1635 for (; I != IEnd; ++I) {
1636 if (S->isDeclScope(D: *I) && D->declarationReplaces(OldD: *I)) {
1637 S->RemoveDecl(D: *I);
1638 IdResolver.RemoveDecl(D: *I);
1639
1640 // Should only need to replace one decl.
1641 break;
1642 }
1643 }
1644
1645 S->AddDecl(D);
1646
1647 if (isa<LabelDecl>(Val: D) && !cast<LabelDecl>(Val: D)->isGnuLocal()) {
1648 // Implicitly-generated labels may end up getting generated in an order that
1649 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1650 // the label at the appropriate place in the identifier chain.
1651 for (I = IdResolver.begin(Name: D->getDeclName()); I != IEnd; ++I) {
1652 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1653 if (IDC == CurContext) {
1654 if (!S->isDeclScope(D: *I))
1655 continue;
1656 } else if (IDC->Encloses(DC: CurContext))
1657 break;
1658 }
1659
1660 IdResolver.InsertDeclAfter(Pos: I, D);
1661 } else {
1662 IdResolver.AddDecl(D);
1663 }
1664 warnOnReservedIdentifier(D);
1665}
1666
1667bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1668 bool AllowInlineNamespace) const {
1669 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1670}
1671
1672bool Sema::isTagRedeclarationInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1673 bool AllowInlineNamespace) const {
1674 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1675 return true;
1676
1677 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: D))
1678 return isDeclInScope(D: Shadow->getTargetDecl(), Ctx, S, AllowInlineNamespace);
1679
1680 return false;
1681}
1682
1683Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1684 DeclContext *TargetDC = DC->getPrimaryContext();
1685 do {
1686 if (DeclContext *ScopeDC = S->getEntity())
1687 if (ScopeDC->getPrimaryContext() == TargetDC)
1688 return S;
1689 } while ((S = S->getParent()));
1690
1691 return nullptr;
1692}
1693
1694static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1695 DeclContext*,
1696 ASTContext&);
1697
1698void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1699 bool ConsiderLinkage,
1700 bool AllowInlineNamespace) {
1701 LookupResult::Filter F = R.makeFilter();
1702 while (F.hasNext()) {
1703 NamedDecl *D = F.next();
1704
1705 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1706 continue;
1707
1708 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1709 continue;
1710
1711 F.erase();
1712 }
1713
1714 F.done();
1715}
1716
1717static bool isImplicitInstantiation(NamedDecl *D) {
1718 if (auto *VD = dyn_cast<VarDecl>(Val: D))
1719 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1720 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
1721 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1722 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1723 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1724
1725 return false;
1726}
1727
1728bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1729 // [module.interface]p7:
1730 // A declaration is attached to a module as follows:
1731 // - If the declaration is a non-dependent friend declaration that nominates a
1732 // function with a declarator-id that is a qualified-id or template-id or that
1733 // nominates a class other than with an elaborated-type-specifier with neither
1734 // a nested-name-specifier nor a simple-template-id, it is attached to the
1735 // module to which the friend is attached ([basic.link]).
1736 if (New->getFriendObjectKind() &&
1737 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1738 New->setLocalOwningModule(Old->getOwningModule());
1739 makeMergedDefinitionVisible(ND: New);
1740 return false;
1741 }
1742
1743 // Although we have questions for the module ownership of implicit
1744 // instantiations, it should be sure that we shouldn't diagnose the
1745 // redeclaration of incorrect module ownership for different implicit
1746 // instantiations in different modules. We will diagnose the redeclaration of
1747 // incorrect module ownership for the template itself.
1748 if (isImplicitInstantiation(D: New) || isImplicitInstantiation(D: Old))
1749 return false;
1750
1751 Module *NewM = New->getOwningModule();
1752 Module *OldM = Old->getOwningModule();
1753
1754 if (NewM && NewM->isPrivateModule())
1755 NewM = NewM->Parent;
1756 if (OldM && OldM->isPrivateModule())
1757 OldM = OldM->Parent;
1758
1759 if (NewM == OldM)
1760 return false;
1761
1762 if (NewM && OldM) {
1763 // A module implementation unit has visibility of the decls in its
1764 // implicitly imported interface.
1765 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1766 return false;
1767
1768 // Partitions are part of the module, but a partition could import another
1769 // module, so verify that the PMIs agree.
1770 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1771 getASTContext().isInSameModule(M1: NewM, M2: OldM))
1772 return false;
1773 }
1774
1775 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1776 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1777 if (NewIsModuleInterface || OldIsModuleInterface) {
1778 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1779 // if a declaration of D [...] appears in the purview of a module, all
1780 // other such declarations shall appear in the purview of the same module
1781 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_owning_module)
1782 << New
1783 << NewIsModuleInterface
1784 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1785 << OldIsModuleInterface
1786 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1787 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1788 New->setInvalidDecl();
1789 return true;
1790 }
1791
1792 return false;
1793}
1794
1795bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1796 // [module.interface]p1:
1797 // An export-declaration shall inhabit a namespace scope.
1798 //
1799 // So it is meaningless to talk about redeclaration which is not at namespace
1800 // scope.
1801 if (!New->getLexicalDeclContext()
1802 ->getNonTransparentContext()
1803 ->isFileContext() ||
1804 !Old->getLexicalDeclContext()
1805 ->getNonTransparentContext()
1806 ->isFileContext())
1807 return false;
1808
1809 bool IsNewExported = New->isInExportDeclContext();
1810 bool IsOldExported = Old->isInExportDeclContext();
1811
1812 // It should be irrevelant if both of them are not exported.
1813 if (!IsNewExported && !IsOldExported)
1814 return false;
1815
1816 if (IsOldExported)
1817 return false;
1818
1819 // If the Old declaration are not attached to named modules
1820 // and the New declaration are attached to global module.
1821 // It should be fine to allow the export since it doesn't change
1822 // the linkage of declarations. See
1823 // https://github.com/llvm/llvm-project/issues/98583 for details.
1824 if (!Old->isInNamedModule() && New->getOwningModule() &&
1825 New->getOwningModule()->isImplicitGlobalModule())
1826 return false;
1827
1828 assert(IsNewExported);
1829
1830 auto Lk = Old->getFormalLinkage();
1831 int S = 0;
1832 if (Lk == Linkage::Internal)
1833 S = 1;
1834 else if (Lk == Linkage::Module)
1835 S = 2;
1836 Diag(Loc: New->getLocation(), DiagID: diag::err_redeclaration_non_exported) << New << S;
1837 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1838 return true;
1839}
1840
1841bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1842 if (CheckRedeclarationModuleOwnership(New, Old))
1843 return true;
1844
1845 if (CheckRedeclarationExported(New, Old))
1846 return true;
1847
1848 return false;
1849}
1850
1851bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1852 const NamedDecl *Old) const {
1853 assert(getASTContext().isSameEntity(New, Old) &&
1854 "New and Old are not the same definition, we should diagnostic it "
1855 "immediately instead of checking it.");
1856 assert(const_cast<Sema *>(this)->isReachable(New) &&
1857 const_cast<Sema *>(this)->isReachable(Old) &&
1858 "We shouldn't see unreachable definitions here.");
1859
1860 Module *NewM = New->getOwningModule();
1861 Module *OldM = Old->getOwningModule();
1862
1863 // We only checks for named modules here. The header like modules is skipped.
1864 // FIXME: This is not right if we import the header like modules in the module
1865 // purview.
1866 //
1867 // For example, assuming "header.h" provides definition for `D`.
1868 // ```C++
1869 // //--- M.cppm
1870 // export module M;
1871 // import "header.h"; // or #include "header.h" but import it by clang modules
1872 // actually.
1873 //
1874 // //--- Use.cpp
1875 // import M;
1876 // import "header.h"; // or uses clang modules.
1877 // ```
1878 //
1879 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1880 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1881 // reject it. But the current implementation couldn't detect the case since we
1882 // don't record the information about the importee modules.
1883 //
1884 // But this might not be painful in practice. Since the design of C++20 Named
1885 // Modules suggests us to use headers in global module fragment instead of
1886 // module purview.
1887 if (NewM && NewM->isHeaderLikeModule())
1888 NewM = nullptr;
1889 if (OldM && OldM->isHeaderLikeModule())
1890 OldM = nullptr;
1891
1892 if (!NewM && !OldM)
1893 return true;
1894
1895 // [basic.def.odr]p14.3
1896 // Each such definition shall not be attached to a named module
1897 // ([module.unit]).
1898 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1899 return true;
1900
1901 // Then New and Old lives in the same TU if their share one same module unit.
1902 if (NewM)
1903 NewM = NewM->getTopLevelModule();
1904 if (OldM)
1905 OldM = OldM->getTopLevelModule();
1906 return OldM == NewM;
1907}
1908
1909static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1910 if (D->getDeclContext()->isFileContext())
1911 return false;
1912
1913 return isa<UsingShadowDecl>(Val: D) ||
1914 isa<UnresolvedUsingTypenameDecl>(Val: D) ||
1915 isa<UnresolvedUsingValueDecl>(Val: D);
1916}
1917
1918/// Removes using shadow declarations not at class scope from the lookup
1919/// results.
1920static void RemoveUsingDecls(LookupResult &R) {
1921 LookupResult::Filter F = R.makeFilter();
1922 while (F.hasNext())
1923 if (isUsingDeclNotAtClassScope(D: F.next()))
1924 F.erase();
1925
1926 F.done();
1927}
1928
1929/// Check for this common pattern:
1930/// @code
1931/// class S {
1932/// S(const S&); // DO NOT IMPLEMENT
1933/// void operator=(const S&); // DO NOT IMPLEMENT
1934/// };
1935/// @endcode
1936static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1937 // FIXME: Should check for private access too but access is set after we get
1938 // the decl here.
1939 if (D->doesThisDeclarationHaveABody())
1940 return false;
1941
1942 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: D))
1943 return CD->isCopyConstructor();
1944 return D->isCopyAssignmentOperator();
1945}
1946
1947bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1948 const DeclContext *DC = D->getDeclContext();
1949 while (!DC->isTranslationUnit()) {
1950 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Val: DC)){
1951 if (!RD->hasNameForLinkage())
1952 return true;
1953 }
1954 DC = DC->getParent();
1955 }
1956
1957 return !D->isExternallyVisible();
1958}
1959
1960bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1961 assert(D);
1962
1963 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1964 return false;
1965
1966 // Ignore all entities declared within templates, and out-of-line definitions
1967 // of members of class templates.
1968 if (D->getDeclContext()->isDependentContext() ||
1969 D->getLexicalDeclContext()->isDependentContext())
1970 return false;
1971
1972 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1973 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1974 return false;
1975 // A non-out-of-line declaration of a member specialization was implicitly
1976 // instantiated; it's the out-of-line declaration that we're interested in.
1977 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1978 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1979 return false;
1980
1981 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
1982 if (MD->isVirtual() || IsDisallowedCopyOrAssign(D: MD))
1983 return false;
1984 } else {
1985 // 'static inline' functions are defined in headers; don't warn.
1986 if (FD->isInlined() && !isMainFileLoc(Loc: FD->getLocation()))
1987 return false;
1988 }
1989
1990 if (FD->doesThisDeclarationHaveABody() &&
1991 Context.DeclMustBeEmitted(D: FD))
1992 return false;
1993 } else if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1994 // Constants and utility variables are defined in headers with internal
1995 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1996 // like "inline".)
1997 if (!isMainFileLoc(Loc: VD->getLocation()))
1998 return false;
1999
2000 if (Context.DeclMustBeEmitted(D: VD))
2001 return false;
2002
2003 if (VD->isStaticDataMember() &&
2004 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2005 return false;
2006 if (VD->isStaticDataMember() &&
2007 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2008 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
2009 return false;
2010
2011 if (VD->isInline() && !isMainFileLoc(Loc: VD->getLocation()))
2012 return false;
2013 } else {
2014 return false;
2015 }
2016
2017 // Only warn for unused decls internal to the translation unit.
2018 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
2019 // for inline functions defined in the main source file, for instance.
2020 return mightHaveNonExternalLinkage(D);
2021}
2022
2023void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
2024 if (!D)
2025 return;
2026
2027 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
2028 const FunctionDecl *First = FD->getFirstDecl();
2029 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
2030 return; // First should already be in the vector.
2031 }
2032
2033 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2034 const VarDecl *First = VD->getFirstDecl();
2035 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
2036 return; // First should already be in the vector.
2037 }
2038
2039 if (ShouldWarnIfUnusedFileScopedDecl(D))
2040 UnusedFileScopedDecls.push_back(LocalValue: D);
2041}
2042
2043static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
2044 const NamedDecl *D) {
2045 if (D->isInvalidDecl())
2046 return false;
2047
2048 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: D)) {
2049 // For a decomposition declaration, warn if none of the bindings are
2050 // referenced, instead of if the variable itself is referenced (which
2051 // it is, by the bindings' expressions).
2052 bool IsAllIgnored = true;
2053 for (const auto *BD : DD->bindings()) {
2054 if (BD->isReferenced())
2055 return false;
2056 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2057 BD->hasAttr<UnusedAttr>());
2058 }
2059 if (IsAllIgnored)
2060 return false;
2061 } else if (!D->getDeclName()) {
2062 return false;
2063 } else if (D->isReferenced() || D->isUsed()) {
2064 return false;
2065 }
2066
2067 if (D->isPlaceholderVar(LangOpts))
2068 return false;
2069
2070 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2071 D->hasAttr<CleanupAttr>())
2072 return false;
2073
2074 if (isa<LabelDecl>(Val: D))
2075 return true;
2076
2077 // Except for labels, we only care about unused decls that are local to
2078 // functions.
2079 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2080 if (const auto *R = dyn_cast<CXXRecordDecl>(Val: D->getDeclContext()))
2081 // For dependent types, the diagnostic is deferred.
2082 WithinFunction =
2083 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2084 if (!WithinFunction)
2085 return false;
2086
2087 if (isa<TypedefNameDecl>(Val: D))
2088 return true;
2089
2090 // White-list anything that isn't a local variable.
2091 if (!isa<VarDecl>(Val: D) || isa<ParmVarDecl>(Val: D) || isa<ImplicitParamDecl>(Val: D))
2092 return false;
2093
2094 // Types of valid local variables should be complete, so this should succeed.
2095 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2096
2097 const Expr *Init = VD->getInit();
2098 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Val: Init))
2099 Init = Cleanups->getSubExpr();
2100
2101 const auto *Ty = VD->getType().getTypePtr();
2102
2103 // Only look at the outermost level of typedef.
2104 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2105 // Allow anything marked with __attribute__((unused)).
2106 if (TT->getDecl()->hasAttr<UnusedAttr>())
2107 return false;
2108 }
2109
2110 // Warn for reference variables whose initializtion performs lifetime
2111 // extension.
2112 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Val: Init);
2113 MTE && MTE->getExtendingDecl()) {
2114 Ty = VD->getType().getNonReferenceType().getTypePtr();
2115 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2116 }
2117
2118 // If we failed to complete the type for some reason, or if the type is
2119 // dependent, don't diagnose the variable.
2120 if (Ty->isIncompleteType() || Ty->isDependentType())
2121 return false;
2122
2123 // Look at the element type to ensure that the warning behaviour is
2124 // consistent for both scalars and arrays.
2125 Ty = Ty->getBaseElementTypeUnsafe();
2126
2127 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2128 if (Tag->hasAttr<UnusedAttr>())
2129 return false;
2130
2131 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
2132 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2133 return false;
2134
2135 if (Init) {
2136 const auto *Construct =
2137 dyn_cast<CXXConstructExpr>(Val: Init->IgnoreImpCasts());
2138 if (Construct && !Construct->isElidable()) {
2139 const CXXConstructorDecl *CD = Construct->getConstructor();
2140 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2141 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2142 return false;
2143 }
2144
2145 // Suppress the warning if we don't know how this is constructed, and
2146 // it could possibly be non-trivial constructor.
2147 if (Init->isTypeDependent()) {
2148 for (const CXXConstructorDecl *Ctor : RD->ctors())
2149 if (!Ctor->isTrivial())
2150 return false;
2151 }
2152
2153 // Suppress the warning if the constructor is unresolved because
2154 // its arguments are dependent.
2155 if (isa<CXXUnresolvedConstructExpr>(Val: Init))
2156 return false;
2157 }
2158 }
2159 }
2160
2161 // TODO: __attribute__((unused)) templates?
2162 }
2163
2164 return true;
2165}
2166
2167static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2168 FixItHint &Hint) {
2169 if (isa<LabelDecl>(Val: D)) {
2170 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2171 loc: D->getEndLoc(), TKind: tok::colon, SM: Ctx.getSourceManager(), LangOpts: Ctx.getLangOpts(),
2172 /*SkipTrailingWhitespaceAndNewline=*/SkipTrailingWhitespaceAndNewLine: false);
2173 if (AfterColon.isInvalid())
2174 return;
2175 Hint = FixItHint::CreateRemoval(
2176 RemoveRange: CharSourceRange::getCharRange(B: D->getBeginLoc(), E: AfterColon));
2177 }
2178}
2179
2180void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2181 DiagnoseUnusedNestedTypedefs(
2182 D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2183}
2184
2185void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2186 DiagReceiverTy DiagReceiver) {
2187 if (D->isDependentType())
2188 return;
2189
2190 for (auto *TmpD : D->decls()) {
2191 if (const auto *T = dyn_cast<TypedefNameDecl>(Val: TmpD))
2192 DiagnoseUnusedDecl(ND: T, DiagReceiver);
2193 else if(const auto *R = dyn_cast<RecordDecl>(Val: TmpD))
2194 DiagnoseUnusedNestedTypedefs(D: R, DiagReceiver);
2195 }
2196}
2197
2198void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2199 DiagnoseUnusedDecl(
2200 ND: D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2201}
2202
2203void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2204 if (!ShouldDiagnoseUnusedDecl(LangOpts: getLangOpts(), D))
2205 return;
2206
2207 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
2208 // typedefs can be referenced later on, so the diagnostics are emitted
2209 // at end-of-translation-unit.
2210 UnusedLocalTypedefNameCandidates.insert(Ptr: TD);
2211 return;
2212 }
2213
2214 FixItHint Hint;
2215 GenerateFixForUnusedDecl(D, Ctx&: Context, Hint);
2216
2217 unsigned DiagID;
2218 if (isa<VarDecl>(Val: D) && cast<VarDecl>(Val: D)->isExceptionVariable())
2219 DiagID = diag::warn_unused_exception_param;
2220 else if (isa<LabelDecl>(Val: D))
2221 DiagID = diag::warn_unused_label;
2222 else
2223 DiagID = diag::warn_unused_variable;
2224
2225 SourceLocation DiagLoc = D->getLocation();
2226 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2227}
2228
2229void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2230 DiagReceiverTy DiagReceiver) {
2231 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2232 // it's not really unused.
2233 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2234 return;
2235
2236 // In C++, `_` variables behave as if they were maybe_unused
2237 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(LangOpts: getLangOpts()))
2238 return;
2239
2240 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2241
2242 if (Ty->isReferenceType() || Ty->isDependentType())
2243 return;
2244
2245 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2246 if (Tag->hasAttr<UnusedAttr>())
2247 return;
2248 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2249 // mimic gcc's behavior.
2250 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag);
2251 RD && !RD->hasAttr<WarnUnusedAttr>())
2252 return;
2253 }
2254
2255 // Don't warn on volatile file-scope variables. They are visible beyond their
2256 // declaring function and writes to them could be observable side effects.
2257 if (VD->getType().isVolatileQualified() && VD->isFileVarDecl())
2258 return;
2259
2260 // Don't warn about __block Objective-C pointer variables, as they might
2261 // be assigned in the block but not used elsewhere for the purpose of lifetime
2262 // extension.
2263 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2264 return;
2265
2266 // Don't warn about Objective-C pointer variables with precise lifetime
2267 // semantics; they can be used to ensure ARC releases the object at a known
2268 // time, which may mean assignment but no other references.
2269 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2270 return;
2271
2272 auto iter = RefsMinusAssignments.find(Val: VD->getCanonicalDecl());
2273 if (iter == RefsMinusAssignments.end())
2274 return;
2275
2276 assert(iter->getSecond() >= 0 &&
2277 "Found a negative number of references to a VarDecl");
2278 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2279 // Assume the given VarDecl is "used" if its ref count stored in
2280 // `RefMinusAssignments` is positive, with one exception.
2281 //
2282 // For a C++ variable whose decl (with initializer) entirely consist the
2283 // condition expression of a if/while/for construct,
2284 // Clang creates a DeclRefExpr for the condition expression rather than a
2285 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2286 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2287 // used in the body of the if/while/for construct.
2288 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2289 if (!UnusedCXXCondDecl)
2290 return;
2291 }
2292
2293 unsigned DiagID;
2294 if (isa<ParmVarDecl>(Val: VD))
2295 DiagID = diag::warn_unused_but_set_parameter;
2296 else if (VD->isFileVarDecl())
2297 DiagID = diag::warn_unused_but_set_global;
2298 else
2299 DiagID = diag::warn_unused_but_set_variable;
2300 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2301}
2302
2303static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2304 Sema::DiagReceiverTy DiagReceiver) {
2305 // Verify that we have no forward references left. If so, there was a goto
2306 // or address of a label taken, but no definition of it. Label fwd
2307 // definitions are indicated with a null substmt which is also not a resolved
2308 // MS inline assembly label name.
2309 bool Diagnose = false;
2310 if (L->isMSAsmLabel())
2311 Diagnose = !L->isResolvedMSAsmLabel();
2312 else
2313 Diagnose = L->getStmt() == nullptr;
2314 if (Diagnose)
2315 DiagReceiver(L->getLocation(), S.PDiag(DiagID: diag::err_undeclared_label_use)
2316 << L);
2317}
2318
2319void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2320 S->applyNRVO();
2321
2322 if (S->decl_empty()) return;
2323 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2324 "Scope shouldn't contain decls!");
2325
2326 /// We visit the decls in non-deterministic order, but we want diagnostics
2327 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2328 /// and sort the diagnostics before emitting them, after we visited all decls.
2329 struct LocAndDiag {
2330 SourceLocation Loc;
2331 std::optional<SourceLocation> PreviousDeclLoc;
2332 PartialDiagnostic PD;
2333 };
2334 SmallVector<LocAndDiag, 16> DeclDiags;
2335 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2336 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: std::nullopt, .PD: std::move(PD)});
2337 };
2338 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2339 SourceLocation PreviousDeclLoc,
2340 PartialDiagnostic PD) {
2341 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: PreviousDeclLoc, .PD: std::move(PD)});
2342 };
2343
2344 for (auto *TmpD : S->decls()) {
2345 assert(TmpD && "This decl didn't get pushed??");
2346
2347 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2348 NamedDecl *D = cast<NamedDecl>(Val: TmpD);
2349
2350 // Diagnose unused variables in this scope.
2351 if (!S->hasUnrecoverableErrorOccurred()) {
2352 DiagnoseUnusedDecl(D, DiagReceiver: addDiag);
2353 if (const auto *RD = dyn_cast<RecordDecl>(Val: D))
2354 DiagnoseUnusedNestedTypedefs(D: RD, DiagReceiver: addDiag);
2355 // Wait until end of TU to diagnose internal linkage file vars.
2356 if (auto *VD = dyn_cast<VarDecl>(Val: D);
2357 VD && !VD->isInternalLinkageFileVar()) {
2358 DiagnoseUnusedButSetDecl(VD, DiagReceiver: addDiag);
2359 RefsMinusAssignments.erase(Val: VD->getCanonicalDecl());
2360 }
2361 }
2362
2363 if (!D->getDeclName()) continue;
2364
2365 // If this was a forward reference to a label, verify it was defined.
2366 if (LabelDecl *LD = dyn_cast<LabelDecl>(Val: D))
2367 CheckPoppedLabel(L: LD, S&: *this, DiagReceiver: addDiag);
2368
2369 // Partial translation units that are created in incremental processing must
2370 // not clean up the IdResolver because PTUs should take into account the
2371 // declarations that came from previous PTUs.
2372 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2373 getLangOpts().CPlusPlus)
2374 IdResolver.RemoveDecl(D);
2375
2376 // Warn on it if we are shadowing a declaration.
2377 auto ShadowI = ShadowingDecls.find(Val: D);
2378 if (ShadowI != ShadowingDecls.end()) {
2379 if (const auto *FD = dyn_cast<FieldDecl>(Val: ShadowI->second)) {
2380 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2381 PDiag(DiagID: diag::warn_ctor_parm_shadows_field)
2382 << D << FD << FD->getParent());
2383 }
2384 ShadowingDecls.erase(I: ShadowI);
2385 }
2386 }
2387
2388 llvm::sort(C&: DeclDiags,
2389 Comp: [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2390 // The particular order for diagnostics is not important, as long
2391 // as the order is deterministic. Using the raw location is going
2392 // to generally be in source order unless there are macro
2393 // expansions involved.
2394 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2395 });
2396 for (const LocAndDiag &D : DeclDiags) {
2397 Diag(Loc: D.Loc, PD: D.PD);
2398 if (D.PreviousDeclLoc)
2399 Diag(Loc: *D.PreviousDeclLoc, DiagID: diag::note_previous_declaration);
2400 }
2401}
2402
2403Scope *Sema::getNonFieldDeclScope(Scope *S) {
2404 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2405 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2406 (S->isClassScope() && !getLangOpts().CPlusPlus))
2407 S = S->getParent();
2408 return S;
2409}
2410
2411static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2412 ASTContext::GetBuiltinTypeError Error) {
2413 switch (Error) {
2414 case ASTContext::GE_None:
2415 return "";
2416 case ASTContext::GE_Missing_type:
2417 return BuiltinInfo.getHeaderName(ID);
2418 case ASTContext::GE_Missing_stdio:
2419 return "stdio.h";
2420 case ASTContext::GE_Missing_setjmp:
2421 return "setjmp.h";
2422 case ASTContext::GE_Missing_ucontext:
2423 return "ucontext.h";
2424 }
2425 llvm_unreachable("unhandled error kind");
2426}
2427
2428FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2429 unsigned ID, SourceLocation Loc) {
2430 DeclContext *Parent = Context.getTranslationUnitDecl();
2431
2432 if (getLangOpts().CPlusPlus) {
2433 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2434 C&: Context, DC: Parent, ExternLoc: Loc, LangLoc: Loc, Lang: LinkageSpecLanguageIDs::C, HasBraces: false);
2435 CLinkageDecl->setImplicit();
2436 Parent->addDecl(D: CLinkageDecl);
2437 Parent = CLinkageDecl;
2438 }
2439
2440 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified;
2441 if (Context.BuiltinInfo.isImmediate(ID)) {
2442 assert(getLangOpts().CPlusPlus20 &&
2443 "consteval builtins should only be available in C++20 mode");
2444 ConstexprKind = ConstexprSpecKind::Consteval;
2445 }
2446
2447 FunctionDecl *New = FunctionDecl::Create(
2448 C&: Context, DC: Parent, StartLoc: Loc, NLoc: Loc, N: II, T: Type, /*TInfo=*/nullptr, SC: SC_Extern,
2449 UsesFPIntrin: getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2450 hasWrittenPrototype: Type->isFunctionProtoType(), ConstexprKind);
2451 New->setImplicit();
2452 New->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID));
2453
2454 // Create Decl objects for each parameter, adding them to the
2455 // FunctionDecl.
2456 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: Type)) {
2457 SmallVector<ParmVarDecl *, 16> Params;
2458 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2459 ParmVarDecl *parm = ParmVarDecl::Create(
2460 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
2461 T: FT->getParamType(i), /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
2462 parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
2463 Params.push_back(Elt: parm);
2464 }
2465 New->setParams(Params);
2466 }
2467
2468 AddKnownFunctionAttributes(FD: New);
2469 return New;
2470}
2471
2472NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2473 Scope *S, bool ForRedeclaration,
2474 SourceLocation Loc) {
2475 LookupNecessaryTypesForBuiltin(S, ID);
2476
2477 ASTContext::GetBuiltinTypeError Error;
2478 QualType R = Context.GetBuiltinType(ID, Error);
2479 if (Error) {
2480 if (!ForRedeclaration)
2481 return nullptr;
2482
2483 // If we have a builtin without an associated type we should not emit a
2484 // warning when we were not able to find a type for it.
2485 if (Error == ASTContext::GE_Missing_type ||
2486 Context.BuiltinInfo.allowTypeMismatch(ID))
2487 return nullptr;
2488
2489 // If we could not find a type for setjmp it is because the jmp_buf type was
2490 // not defined prior to the setjmp declaration.
2491 if (Error == ASTContext::GE_Missing_setjmp) {
2492 Diag(Loc, DiagID: diag::warn_implicit_decl_no_jmp_buf)
2493 << Context.BuiltinInfo.getName(ID);
2494 return nullptr;
2495 }
2496
2497 // Generally, we emit a warning that the declaration requires the
2498 // appropriate header.
2499 Diag(Loc, DiagID: diag::warn_implicit_decl_requires_sysheader)
2500 << getHeaderName(BuiltinInfo&: Context.BuiltinInfo, ID, Error)
2501 << Context.BuiltinInfo.getName(ID);
2502 return nullptr;
2503 }
2504
2505 if (!ForRedeclaration &&
2506 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2507 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2508 Diag(Loc, DiagID: LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2509 : diag::ext_implicit_lib_function_decl)
2510 << Context.BuiltinInfo.getName(ID) << R;
2511 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2512 Diag(Loc, DiagID: diag::note_include_header_or_declare)
2513 << Header << Context.BuiltinInfo.getName(ID);
2514 }
2515
2516 if (R.isNull())
2517 return nullptr;
2518
2519 FunctionDecl *New = CreateBuiltin(II, Type: R, ID, Loc);
2520 RegisterLocallyScopedExternCDecl(ND: New, S);
2521
2522 // TUScope is the translation-unit scope to insert this function into.
2523 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2524 // relate Scopes to DeclContexts, and probably eliminate CurContext
2525 // entirely, but we're not there yet.
2526 DeclContext *SavedContext = CurContext;
2527 CurContext = New->getDeclContext();
2528 PushOnScopeChains(D: New, S: TUScope);
2529 CurContext = SavedContext;
2530 return New;
2531}
2532
2533/// Typedef declarations don't have linkage, but they still denote the same
2534/// entity if their types are the same.
2535/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2536/// isSameEntity.
2537static void
2538filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl,
2539 LookupResult &Previous) {
2540 // This is only interesting when modules are enabled.
2541 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2542 return;
2543
2544 // Empty sets are uninteresting.
2545 if (Previous.empty())
2546 return;
2547
2548 LookupResult::Filter Filter = Previous.makeFilter();
2549 while (Filter.hasNext()) {
2550 NamedDecl *Old = Filter.next();
2551
2552 // Non-hidden declarations are never ignored.
2553 if (S.isVisible(D: Old))
2554 continue;
2555
2556 // Declarations of the same entity are not ignored, even if they have
2557 // different linkages.
2558 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2559 if (S.Context.hasSameType(T1: OldTD->getUnderlyingType(),
2560 T2: Decl->getUnderlyingType()))
2561 continue;
2562
2563 // If both declarations give a tag declaration a typedef name for linkage
2564 // purposes, then they declare the same entity.
2565 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2566 Decl->getAnonDeclWithTypedefName())
2567 continue;
2568 }
2569
2570 Filter.erase();
2571 }
2572
2573 Filter.done();
2574}
2575
2576bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) {
2577 QualType OldType;
2578 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Val: Old))
2579 OldType = OldTypedef->getUnderlyingType();
2580 else
2581 OldType = Context.getTypeDeclType(Decl: Old);
2582 QualType NewType = New->getUnderlyingType();
2583
2584 if (NewType->isVariablyModifiedType()) {
2585 // Must not redefine a typedef with a variably-modified type.
2586 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2587 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_variably_modified_typedef)
2588 << Kind << NewType;
2589 if (Old->getLocation().isValid())
2590 notePreviousDefinition(Old, New: New->getLocation());
2591 New->setInvalidDecl();
2592 return true;
2593 }
2594
2595 if (OldType != NewType &&
2596 !OldType->isDependentType() &&
2597 !NewType->isDependentType() &&
2598 !Context.hasSameType(T1: OldType, T2: NewType)) {
2599 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2600 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_typedef)
2601 << Kind << NewType << OldType;
2602 if (Old->getLocation().isValid())
2603 notePreviousDefinition(Old, New: New->getLocation());
2604 New->setInvalidDecl();
2605 return true;
2606 }
2607 return false;
2608}
2609
2610void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2611 LookupResult &OldDecls) {
2612 // If the new decl is known invalid already, don't bother doing any
2613 // merging checks.
2614 if (New->isInvalidDecl()) return;
2615
2616 // Allow multiple definitions for ObjC built-in typedefs.
2617 // FIXME: Verify the underlying types are equivalent!
2618 if (getLangOpts().ObjC) {
2619 const IdentifierInfo *TypeID = New->getIdentifier();
2620 switch (TypeID->getLength()) {
2621 default: break;
2622 case 2:
2623 {
2624 if (!TypeID->isStr(Str: "id"))
2625 break;
2626 QualType T = New->getUnderlyingType();
2627 if (!T->isPointerType())
2628 break;
2629 if (!T->isVoidPointerType()) {
2630 QualType PT = T->castAs<PointerType>()->getPointeeType();
2631 if (!PT->isStructureType())
2632 break;
2633 }
2634 Context.setObjCIdRedefinitionType(T);
2635 // Install the built-in type for 'id', ignoring the current definition.
2636 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2637 modedTy: Context.getObjCIdType());
2638 return;
2639 }
2640 case 5:
2641 if (!TypeID->isStr(Str: "Class"))
2642 break;
2643 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2644 // Install the built-in type for 'Class', ignoring the current definition.
2645 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2646 modedTy: Context.getObjCClassType());
2647 return;
2648 case 3:
2649 if (!TypeID->isStr(Str: "SEL"))
2650 break;
2651 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2652 // Install the built-in type for 'SEL', ignoring the current definition.
2653 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2654 modedTy: Context.getObjCSelType());
2655 return;
2656 }
2657 // Fall through - the typedef name was not a builtin type.
2658 }
2659
2660 // Verify the old decl was also a type.
2661 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2662 if (!Old) {
2663 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
2664 << New->getDeclName();
2665
2666 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2667 if (OldD->getLocation().isValid())
2668 notePreviousDefinition(Old: OldD, New: New->getLocation());
2669
2670 return New->setInvalidDecl();
2671 }
2672
2673 // If the old declaration is invalid, just give up here.
2674 if (Old->isInvalidDecl())
2675 return New->setInvalidDecl();
2676
2677 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2678 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2679 auto *NewTag = New->getAnonDeclWithTypedefName();
2680 NamedDecl *Hidden = nullptr;
2681 if (OldTag && NewTag &&
2682 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2683 !hasVisibleDefinition(D: OldTag, Suggested: &Hidden)) {
2684 // There is a definition of this tag, but it is not visible. Use it
2685 // instead of our tag.
2686 if (OldTD->isModed())
2687 New->setModedTypeSourceInfo(unmodedTSI: OldTD->getTypeSourceInfo(),
2688 modedTy: OldTD->getUnderlyingType());
2689 else
2690 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2691
2692 // An anonymous enum is recognized as a redeclaration only when its
2693 // typedef name gets merged, at which point the new enum and its
2694 // enumerators already have a distinct canonical type. Link the enum
2695 // declarations, but also retype the new enumerators because
2696 // setPreviousDecl() does not update QualTypes built before the merge;
2697 // otherwise the merged typedef and its enumerators disagree on the type
2698 // (GH213299).
2699 //
2700 // FIXME: The global module restriction only limits the impact of this
2701 // change; relax it if the issue shows up in other contexts.
2702 if (Module *M = OldTag->getOwningModule(); M && M->isGlobalModule()) {
2703 if (auto *NewEnum = dyn_cast<EnumDecl>(Val: NewTag)) {
2704 if (auto *OldEnum = dyn_cast<EnumDecl>(Val: OldTag)) {
2705 NewEnum->setPreviousDecl(OldEnum);
2706 QualType EnumType = Context.getCanonicalTagType(TD: OldEnum);
2707 for (auto *ECD : NewEnum->enumerators())
2708 ECD->setType(EnumType);
2709 }
2710 }
2711 }
2712
2713 // Make the old tag definition visible.
2714 makeMergedDefinitionVisible(ND: Hidden);
2715
2716 CleanupMergedEnum(S, New: NewTag);
2717 }
2718 }
2719
2720 // If the typedef types are not identical, reject them in all languages and
2721 // with any extensions enabled.
2722 if (isIncompatibleTypedef(Old, New))
2723 return;
2724
2725 // The types match. Link up the redeclaration chain and merge attributes if
2726 // the old declaration was a typedef.
2727 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Val: Old)) {
2728 New->setPreviousDecl(Typedef);
2729 mergeDeclAttributes(New, Old);
2730 }
2731
2732 if (getLangOpts().MicrosoftExt)
2733 return;
2734
2735 if (getLangOpts().CPlusPlus) {
2736 // C++ [dcl.typedef]p2:
2737 // In a given non-class scope, a typedef specifier can be used to
2738 // redefine the name of any type declared in that scope to refer
2739 // to the type to which it already refers.
2740 if (!isa<CXXRecordDecl>(Val: CurContext))
2741 return;
2742
2743 // C++0x [dcl.typedef]p4:
2744 // In a given class scope, a typedef specifier can be used to redefine
2745 // any class-name declared in that scope that is not also a typedef-name
2746 // to refer to the type to which it already refers.
2747 //
2748 // This wording came in via DR424, which was a correction to the
2749 // wording in DR56, which accidentally banned code like:
2750 //
2751 // struct S {
2752 // typedef struct A { } A;
2753 // };
2754 //
2755 // in the C++03 standard. We implement the C++0x semantics, which
2756 // allow the above but disallow
2757 //
2758 // struct S {
2759 // typedef int I;
2760 // typedef int I;
2761 // };
2762 //
2763 // since that was the intent of DR56.
2764 if (!isa<TypedefNameDecl>(Val: Old))
2765 return;
2766
2767 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition)
2768 << New->getDeclName();
2769 notePreviousDefinition(Old, New: New->getLocation());
2770 return New->setInvalidDecl();
2771 }
2772
2773 // Modules always permit redefinition of typedefs, as does C11.
2774 if (getLangOpts().Modules || getLangOpts().C11)
2775 return;
2776
2777 // If we have a redefinition of a typedef in C, emit a warning. This warning
2778 // is normally mapped to an error, but can be controlled with
2779 // -Wtypedef-redefinition. If either the original or the redefinition is
2780 // in a system header, don't emit this for compatibility with GCC.
2781 if (getDiagnostics().getSuppressSystemWarnings() &&
2782 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2783 (Old->isImplicit() ||
2784 Context.getSourceManager().isInSystemHeader(Loc: Old->getLocation()) ||
2785 Context.getSourceManager().isInSystemHeader(Loc: New->getLocation())))
2786 return;
2787
2788 Diag(Loc: New->getLocation(), DiagID: diag::ext_redefinition_of_typedef)
2789 << New->getDeclName();
2790 notePreviousDefinition(Old, New: New->getLocation());
2791}
2792
2793void Sema::CleanupMergedEnum(Scope *S, Decl *New) {
2794 // If this was an unscoped enumeration, yank all of its enumerators
2795 // out of the scope.
2796 if (auto *ED = dyn_cast<EnumDecl>(Val: New); ED && !ED->isScoped()) {
2797 Scope *EnumScope = getNonFieldDeclScope(S);
2798 for (auto *ECD : ED->enumerators()) {
2799 assert(EnumScope->isDeclScope(ECD));
2800 EnumScope->RemoveDecl(D: ECD);
2801 IdResolver.RemoveDecl(D: ECD);
2802 }
2803 }
2804}
2805
2806/// DeclhasAttr - returns true if decl Declaration already has the target
2807/// attribute.
2808static bool DeclHasAttr(const Decl *D, const Attr *A) {
2809 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(Val: A);
2810 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(Val: A);
2811 for (const auto *i : D->attrs())
2812 if (i->getKind() == A->getKind()) {
2813 if (Ann) {
2814 if (Ann->getAnnotation() == cast<AnnotateAttr>(Val: i)->getAnnotation())
2815 return true;
2816 continue;
2817 }
2818 // FIXME: Don't hardcode this check
2819 if (OA && isa<OwnershipAttr>(Val: i))
2820 return OA->getOwnKind() == cast<OwnershipAttr>(Val: i)->getOwnKind();
2821 return true;
2822 }
2823
2824 return false;
2825}
2826
2827static bool isAttributeTargetADefinition(Decl *D) {
2828 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D))
2829 return VD->isThisDeclarationADefinition();
2830 if (TagDecl *TD = dyn_cast<TagDecl>(Val: D))
2831 return TD->isCompleteDefinition() || TD->isBeingDefined();
2832 return true;
2833}
2834
2835/// Merge alignment attributes from \p Old to \p New, taking into account the
2836/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2837///
2838/// \return \c true if any attributes were added to \p New.
2839static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2840 // Look for alignas attributes on Old, and pick out whichever attribute
2841 // specifies the strictest alignment requirement.
2842 AlignedAttr *OldAlignasAttr = nullptr;
2843 AlignedAttr *OldStrictestAlignAttr = nullptr;
2844 unsigned OldAlign = 0;
2845 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2846 // FIXME: We have no way of representing inherited dependent alignments
2847 // in a case like:
2848 // template<int A, int B> struct alignas(A) X;
2849 // template<int A, int B> struct alignas(B) X {};
2850 // For now, we just ignore any alignas attributes which are not on the
2851 // definition in such a case.
2852 if (I->isAlignmentDependent())
2853 return false;
2854
2855 if (I->isAlignas())
2856 OldAlignasAttr = I;
2857
2858 unsigned Align = I->getAlignment(Ctx&: S.Context);
2859 if (Align > OldAlign) {
2860 OldAlign = Align;
2861 OldStrictestAlignAttr = I;
2862 }
2863 }
2864
2865 // Look for alignas attributes on New.
2866 AlignedAttr *NewAlignasAttr = nullptr;
2867 unsigned NewAlign = 0;
2868 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2869 if (I->isAlignmentDependent())
2870 return false;
2871
2872 if (I->isAlignas())
2873 NewAlignasAttr = I;
2874
2875 unsigned Align = I->getAlignment(Ctx&: S.Context);
2876 if (Align > NewAlign)
2877 NewAlign = Align;
2878 }
2879
2880 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2881 // Both declarations have 'alignas' attributes. We require them to match.
2882 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2883 // fall short. (If two declarations both have alignas, they must both match
2884 // every definition, and so must match each other if there is a definition.)
2885
2886 // If either declaration only contains 'alignas(0)' specifiers, then it
2887 // specifies the natural alignment for the type.
2888 if (OldAlign == 0 || NewAlign == 0) {
2889 QualType Ty;
2890 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: New))
2891 Ty = VD->getType();
2892 else
2893 Ty = S.Context.getCanonicalTagType(TD: cast<TagDecl>(Val: New));
2894
2895 if (OldAlign == 0)
2896 OldAlign = S.Context.getTypeAlign(T: Ty);
2897 if (NewAlign == 0)
2898 NewAlign = S.Context.getTypeAlign(T: Ty);
2899 }
2900
2901 if (OldAlign != NewAlign) {
2902 S.Diag(Loc: NewAlignasAttr->getLocation(), DiagID: diag::err_alignas_mismatch)
2903 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: OldAlign).getQuantity()
2904 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: NewAlign).getQuantity();
2905 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_previous_declaration);
2906 }
2907 }
2908
2909 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(D: New)) {
2910 // C++11 [dcl.align]p6:
2911 // if any declaration of an entity has an alignment-specifier,
2912 // every defining declaration of that entity shall specify an
2913 // equivalent alignment.
2914 // C11 6.7.5/7:
2915 // If the definition of an object does not have an alignment
2916 // specifier, any other declaration of that object shall also
2917 // have no alignment specifier.
2918 S.Diag(Loc: New->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
2919 << OldAlignasAttr;
2920 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_alignas_on_declaration)
2921 << OldAlignasAttr;
2922 }
2923
2924 bool AnyAdded = false;
2925
2926 // Ensure we have an attribute representing the strictest alignment.
2927 if (OldAlign > NewAlign) {
2928 AlignedAttr *Clone = OldStrictestAlignAttr->clone(C&: S.Context);
2929 Clone->setInherited(true);
2930 New->addAttr(A: Clone);
2931 AnyAdded = true;
2932 }
2933
2934 // Ensure we have an alignas attribute if the old declaration had one.
2935 if (OldAlignasAttr && !NewAlignasAttr &&
2936 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2937 AlignedAttr *Clone = OldAlignasAttr->clone(C&: S.Context);
2938 Clone->setInherited(true);
2939 New->addAttr(A: Clone);
2940 AnyAdded = true;
2941 }
2942
2943 return AnyAdded;
2944}
2945
2946#define WANT_DECL_MERGE_LOGIC
2947#include "clang/Sema/AttrParsedAttrImpl.inc"
2948#undef WANT_DECL_MERGE_LOGIC
2949
2950static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2951 const InheritableAttr *Attr,
2952 AvailabilityMergeKind AMK) {
2953 // Diagnose any mutual exclusions between the attribute that we want to add
2954 // and attributes that already exist on the declaration.
2955 if (!DiagnoseMutualExclusions(S, D, A: Attr))
2956 return false;
2957
2958 // This function copies an attribute Attr from a previous declaration to the
2959 // new declaration D if the new declaration doesn't itself have that attribute
2960 // yet or if that attribute allows duplicates.
2961 // If you're adding a new attribute that requires logic different from
2962 // "use explicit attribute on decl if present, else use attribute from
2963 // previous decl", for example if the attribute needs to be consistent
2964 // between redeclarations, you need to call a custom merge function here.
2965 InheritableAttr *NewAttr = nullptr;
2966 if (const auto *AA = dyn_cast<AvailabilityAttr>(Val: Attr)) {
2967 const IdentifierInfo *InferredPlatformII = nullptr;
2968 if (AvailabilityAttr *Inf = AA->getInferredAttrAs())
2969 InferredPlatformII = Inf->getPlatform();
2970 NewAttr = S.mergeAndInferAvailabilityAttr(
2971 D, CI: *AA, Platform: AA->getPlatform(), Implicit: AA->isImplicit(), Introduced: AA->getIntroduced(),
2972 Deprecated: AA->getDeprecated(), Obsoleted: AA->getObsoleted(), IsUnavailable: AA->getUnavailable(),
2973 Message: AA->getMessage(), IsStrict: AA->getStrict(), Replacement: AA->getReplacement(), AMK,
2974 Priority: AA->getPriority(), IIEnvironment: AA->getEnvironment(), InferredPlatformII);
2975 } else if (const auto *VA = dyn_cast<VisibilityAttr>(Val: Attr))
2976 NewAttr = S.mergeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2977 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Val: Attr))
2978 NewAttr = S.mergeTypeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2979 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Val: Attr))
2980 NewAttr = S.mergeDLLImportAttr(D, CI: *ImportA);
2981 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Val: Attr))
2982 NewAttr = S.mergeDLLExportAttr(D, CI: *ExportA);
2983 else if (const auto *EA = dyn_cast<ErrorAttr>(Val: Attr))
2984 NewAttr = S.mergeErrorAttr(D, CI: *EA, NewUserDiagnostic: EA->getUserDiagnostic());
2985 else if (const auto *FA = dyn_cast<FormatAttr>(Val: Attr))
2986 NewAttr = S.mergeFormatAttr(D, CI: *FA, Format: FA->getType(), FormatIdx: FA->getFormatIdx(),
2987 FirstArg: FA->getFirstArg());
2988 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Val: Attr))
2989 NewAttr = S.mergeFormatMatchesAttr(
2990 D, CI: *FMA, Format: FMA->getType(), FormatIdx: FMA->getFormatIdx(), FormatStr: FMA->getFormatString());
2991 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Val: Attr))
2992 NewAttr = S.mergeModularFormatAttr(
2993 D, CI: *MFA, ModularImplFn: MFA->getModularImplFn(), ImplName: MFA->getImplName(),
2994 Aspects: MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2995 else if (const auto *SA = dyn_cast<SectionAttr>(Val: Attr))
2996 NewAttr = S.mergeSectionAttr(D, CI: *SA, Name: SA->getName());
2997 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Val: Attr))
2998 NewAttr = S.mergeCodeSegAttr(D, CI: *CSA, Name: CSA->getName());
2999 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Val: Attr))
3000 NewAttr = S.mergeMSInheritanceAttr(D, CI: *IA, BestCase: IA->getBestCase(),
3001 Model: IA->getInheritanceModel());
3002 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Val: Attr))
3003 NewAttr = S.mergeAlwaysInlineAttr(D, CI: *AA,
3004 Ident: &S.Context.Idents.get(Name: AA->getSpelling()));
3005 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(Val: D) &&
3006 (isa<CUDAHostAttr>(Val: Attr) || isa<CUDADeviceAttr>(Val: Attr) ||
3007 isa<CUDAGlobalAttr>(Val: Attr))) {
3008 // CUDA target attributes are part of function signature for
3009 // overloading purposes and must not be merged.
3010 return false;
3011 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Val: Attr))
3012 NewAttr = S.mergeMinSizeAttr(D, CI: *MA);
3013 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Val: Attr))
3014 NewAttr = S.Swift().mergeNameAttr(D, SNA: *SNA, Name: SNA->getName());
3015 else if (const auto *SAA = dyn_cast<SwiftAttrAttr>(Val: Attr))
3016 NewAttr = S.Swift().mergeAttrAttr(D, SAA: *SAA);
3017 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Val: Attr))
3018 NewAttr = S.mergeOptimizeNoneAttr(D, CI: *OA);
3019 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Val: Attr))
3020 NewAttr = S.mergeInternalLinkageAttr(D, AL: *InternalLinkageA);
3021 else if (isa<AlignedAttr>(Val: Attr))
3022 // AlignedAttrs are handled separately, because we need to handle all
3023 // such attributes on a declaration at the same time.
3024 NewAttr = nullptr;
3025 else if ((isa<DeprecatedAttr>(Val: Attr) || isa<UnavailableAttr>(Val: Attr)) &&
3026 (AMK == AvailabilityMergeKind::Override ||
3027 AMK == AvailabilityMergeKind::ProtocolImplementation ||
3028 AMK == AvailabilityMergeKind::OptionalProtocolImplementation))
3029 NewAttr = nullptr;
3030 else if (const auto *UA = dyn_cast<UuidAttr>(Val: Attr))
3031 NewAttr = S.mergeUuidAttr(D, CI: *UA, UuidAsWritten: UA->getGuid(), GuidDecl: UA->getGuidDecl());
3032 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Val: Attr))
3033 NewAttr = S.Wasm().mergeImportModuleAttr(D, AL: *IMA);
3034 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Val: Attr))
3035 NewAttr = S.Wasm().mergeImportNameAttr(D, AL: *INA);
3036 else if (const auto *ENA = dyn_cast<WebAssemblyExportNameAttr>(Val: Attr))
3037 NewAttr = S.Wasm().mergeExportNameAttr(D, AL: *ENA);
3038 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Val: Attr))
3039 NewAttr = S.mergeEnforceTCBAttr(D, AL: *TCBA);
3040 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Val: Attr))
3041 NewAttr = S.mergeEnforceTCBLeafAttr(D, AL: *TCBLA);
3042 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Val: Attr))
3043 NewAttr = S.mergeBTFDeclTagAttr(D, AL: *BTFA);
3044 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Val: Attr))
3045 NewAttr = S.HLSL().mergeNumThreadsAttr(D, AL: *NT, X: NT->getX(), Y: NT->getY(),
3046 Z: NT->getZ());
3047 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Val: Attr))
3048 NewAttr = S.HLSL().mergeWaveSizeAttr(D, AL: *WS, Min: WS->getMin(), Max: WS->getMax(),
3049 Preferred: WS->getPreferred(),
3050 SpelledArgsCount: WS->getSpelledArgsCount());
3051 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Val: Attr))
3052 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, AL: *CI, Id: CI->getId());
3053 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Val: Attr))
3054 NewAttr = S.HLSL().mergeShaderAttr(D, AL: *SA, ShaderType: SA->getType());
3055 else if (isa<SuppressAttr>(Val: Attr))
3056 // Do nothing. Each redeclaration should be suppressed separately.
3057 NewAttr = nullptr;
3058 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Val: Attr))
3059 NewAttr = S.OpenACC().mergeRoutineDeclAttr(Old: *RD);
3060 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, A: Attr))
3061 NewAttr = cast<InheritableAttr>(Val: Attr->clone(C&: S.Context));
3062 else if (const auto *PA = dyn_cast<PersonalityAttr>(Val: Attr))
3063 NewAttr = S.mergePersonalityAttr(D, Routine: PA->getRoutine(), CI: *PA);
3064
3065 if (NewAttr) {
3066 NewAttr->setInherited(true);
3067 D->addAttr(A: NewAttr);
3068 if (isa<MSInheritanceAttr>(Val: NewAttr))
3069 S.Consumer.AssignInheritanceModel(RD: cast<CXXRecordDecl>(Val: D));
3070 return true;
3071 }
3072
3073 return false;
3074}
3075
3076static const NamedDecl *getDefinition(const Decl *D) {
3077 if (const TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
3078 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
3079 return Def;
3080 return nullptr;
3081 }
3082 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
3083 const VarDecl *Def = VD->getDefinition();
3084 if (Def)
3085 return Def;
3086 return VD->getActingDefinition();
3087 }
3088 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
3089 const FunctionDecl *Def = nullptr;
3090 if (FD->isDefined(Definition&: Def, CheckForPendingFriendDefinition: true))
3091 return Def;
3092 }
3093 return nullptr;
3094}
3095
3096static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3097 for (const auto *Attribute : D->attrs())
3098 if (Attribute->getKind() == Kind)
3099 return true;
3100 return false;
3101}
3102
3103/// checkNewAttributesAfterDef - If we already have a definition, check that
3104/// there are no new attributes in this declaration.
3105static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3106 if (!New->hasAttrs())
3107 return;
3108
3109 const NamedDecl *Def = getDefinition(D: Old);
3110 if (!Def || Def == New)
3111 return;
3112
3113 AttrVec &NewAttributes = New->getAttrs();
3114 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3115 Attr *NewAttribute = NewAttributes[I];
3116
3117 if (isa<AliasAttr>(Val: NewAttribute) || isa<IFuncAttr>(Val: NewAttribute)) {
3118 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: New)) {
3119 SkipBodyInfo SkipBody;
3120 S.CheckForFunctionRedefinition(FD, EffectiveDefinition: cast<FunctionDecl>(Val: Def), SkipBody: &SkipBody);
3121
3122 // If we're skipping this definition, drop the "alias" attribute.
3123 if (SkipBody.ShouldSkip) {
3124 NewAttributes.erase(CI: NewAttributes.begin() + I);
3125 --E;
3126 continue;
3127 }
3128 } else {
3129 VarDecl *VD = cast<VarDecl>(Val: New);
3130 unsigned Diag = cast<VarDecl>(Val: Def)->isThisDeclarationADefinition() ==
3131 VarDecl::TentativeDefinition
3132 ? diag::err_alias_after_tentative
3133 : diag::err_redefinition;
3134 S.Diag(Loc: VD->getLocation(), DiagID: Diag) << VD->getDeclName();
3135 if (Diag == diag::err_redefinition)
3136 S.notePreviousDefinition(Old: Def, New: VD->getLocation());
3137 else
3138 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3139 VD->setInvalidDecl();
3140 }
3141 ++I;
3142 continue;
3143 }
3144
3145 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: Def)) {
3146 // Tentative definitions are only interesting for the alias check above.
3147 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3148 ++I;
3149 continue;
3150 }
3151 }
3152
3153 if (hasAttribute(D: Def, Kind: NewAttribute->getKind())) {
3154 ++I;
3155 continue; // regular attr merging will take care of validating this.
3156 }
3157
3158 if (NewAttribute->getLocation().isInvalid()) {
3159 // An attribute with no source location was not written by the user. API
3160 // notes, in particular, are matched against whichever declaration the
3161 // compiler reaches, which can be a redeclaration that follows the
3162 // definition, possibly in a different module. There is nothing for the
3163 // user to correct, and erasing the attribute would silently change what
3164 // the annotated API means.
3165 ++I;
3166 continue;
3167 }
3168
3169 if (isa<C11NoReturnAttr>(Val: NewAttribute)) {
3170 // C's _Noreturn is allowed to be added to a function after it is defined.
3171 ++I;
3172 continue;
3173 } else if (isa<UuidAttr>(Val: NewAttribute)) {
3174 // msvc will allow a subsequent definition to add an uuid to a class
3175 ++I;
3176 continue;
3177 } else if (isa<DeprecatedAttr, WarnUnusedResultAttr, UnusedAttr>(
3178 Val: NewAttribute) &&
3179 NewAttribute->isStandardAttributeSyntax()) {
3180 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3181 // deprecated attribute can later be re-declared with the attribute and
3182 // vice-versa.
3183 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3184 // maybe_unused attribute can later be redeclared with the attribute and
3185 // vice versa.
3186 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3187 // nodiscard attribute can later be redeclared with the attribute and
3188 // vice-versa.
3189 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3190 ++I;
3191 continue;
3192 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(Val: NewAttribute)) {
3193 if (AA->isAlignas()) {
3194 // C++11 [dcl.align]p6:
3195 // if any declaration of an entity has an alignment-specifier,
3196 // every defining declaration of that entity shall specify an
3197 // equivalent alignment.
3198 // C11 6.7.5/7:
3199 // If the definition of an object does not have an alignment
3200 // specifier, any other declaration of that object shall also
3201 // have no alignment specifier.
3202 S.Diag(Loc: Def->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
3203 << AA;
3204 S.Diag(Loc: NewAttribute->getLocation(), DiagID: diag::note_alignas_on_declaration)
3205 << AA;
3206 NewAttributes.erase(CI: NewAttributes.begin() + I);
3207 --E;
3208 continue;
3209 }
3210 } else if (isa<LoaderUninitializedAttr>(Val: NewAttribute)) {
3211 // If there is a C definition followed by a redeclaration with this
3212 // attribute then there are two different definitions. In C++, prefer the
3213 // standard diagnostics.
3214 if (!S.getLangOpts().CPlusPlus) {
3215 S.Diag(Loc: NewAttribute->getLocation(),
3216 DiagID: diag::err_loader_uninitialized_redeclaration);
3217 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3218 NewAttributes.erase(CI: NewAttributes.begin() + I);
3219 --E;
3220 continue;
3221 }
3222 } else if (isa<SelectAnyAttr>(Val: NewAttribute) &&
3223 cast<VarDecl>(Val: New)->isInline() &&
3224 !cast<VarDecl>(Val: New)->isInlineSpecified()) {
3225 // Don't warn about applying selectany to implicitly inline variables.
3226 // Older compilers and language modes would require the use of selectany
3227 // to make such variables inline, and it would have no effect if we
3228 // honored it.
3229 ++I;
3230 continue;
3231 } else if (isa<OMPDeclareVariantAttr>(Val: NewAttribute)) {
3232 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3233 // declarations after definitions.
3234 ++I;
3235 continue;
3236 } else if (isa<SYCLKernelEntryPointAttr>(Val: NewAttribute)) {
3237 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3238 // error since the definition will have already been created without
3239 // the semantic effects of the attribute having been applied.
3240 S.Diag(Loc: NewAttribute->getLocation(),
3241 DiagID: diag::err_sycl_entry_point_after_definition)
3242 << NewAttribute;
3243 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3244 cast<SYCLKernelEntryPointAttr>(Val: NewAttribute)->setInvalidAttr();
3245 ++I;
3246 continue;
3247 } else if (isa<SYCLExternalAttr>(Val: NewAttribute)) {
3248 // SYCLExternalAttr may be added after a definition.
3249 ++I;
3250 continue;
3251 }
3252
3253 S.Diag(Loc: NewAttribute->getLocation(),
3254 DiagID: diag::warn_attribute_precede_definition);
3255 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3256 NewAttributes.erase(CI: NewAttributes.begin() + I);
3257 --E;
3258 }
3259}
3260
3261static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3262 const ConstInitAttr *CIAttr,
3263 bool AttrBeforeInit) {
3264 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3265
3266 // Figure out a good way to write this specifier on the old declaration.
3267 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3268 // enough of the attribute list spelling information to extract that without
3269 // heroics.
3270 std::string SuitableSpelling;
3271 if (S.getLangOpts().CPlusPlus20)
3272 SuitableSpelling = std::string(
3273 S.PP.getLastMacroWithSpelling(Loc: InsertLoc, Tokens: {tok::kw_constinit}));
3274 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3275 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3276 Loc: InsertLoc, Tokens: {tok::l_square, tok::l_square,
3277 S.PP.getIdentifierInfo(Name: "clang"), tok::coloncolon,
3278 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3279 tok::r_square, tok::r_square}));
3280 if (SuitableSpelling.empty())
3281 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3282 Loc: InsertLoc, Tokens: {tok::kw___attribute, tok::l_paren, tok::r_paren,
3283 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3284 tok::r_paren, tok::r_paren}));
3285 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3286 SuitableSpelling = "constinit";
3287 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3288 SuitableSpelling = "[[clang::require_constant_initialization]]";
3289 if (SuitableSpelling.empty())
3290 SuitableSpelling = "__attribute__((require_constant_initialization))";
3291 SuitableSpelling += " ";
3292
3293 if (AttrBeforeInit) {
3294 // extern constinit int a;
3295 // int a = 0; // error (missing 'constinit'), accepted as extension
3296 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3297 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::ext_constinit_missing)
3298 << InitDecl << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3299 S.Diag(Loc: CIAttr->getLocation(), DiagID: diag::note_constinit_specified_here);
3300 } else {
3301 // int a = 0;
3302 // constinit extern int a; // error (missing 'constinit')
3303 S.Diag(Loc: CIAttr->getLocation(),
3304 DiagID: CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3305 : diag::warn_require_const_init_added_too_late)
3306 << FixItHint::CreateRemoval(RemoveRange: SourceRange(CIAttr->getLocation()));
3307 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::note_constinit_missing_here)
3308 << CIAttr->isConstinit()
3309 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3310 }
3311}
3312
3313void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3314 AvailabilityMergeKind AMK) {
3315 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3316 UsedAttr *NewAttr = OldAttr->clone(C&: Context);
3317 NewAttr->setInherited(true);
3318 New->addAttr(A: NewAttr);
3319 }
3320 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3321 RetainAttr *NewAttr = OldAttr->clone(C&: Context);
3322 NewAttr->setInherited(true);
3323 New->addAttr(A: NewAttr);
3324 }
3325
3326 if (!Old->hasAttrs() && !New->hasAttrs())
3327 return;
3328
3329 // [dcl.constinit]p1:
3330 // If the [constinit] specifier is applied to any declaration of a
3331 // variable, it shall be applied to the initializing declaration.
3332 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3333 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3334 if (bool(OldConstInit) != bool(NewConstInit)) {
3335 const auto *OldVD = cast<VarDecl>(Val: Old);
3336 auto *NewVD = cast<VarDecl>(Val: New);
3337
3338 // Find the initializing declaration. Note that we might not have linked
3339 // the new declaration into the redeclaration chain yet.
3340 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3341 if (!InitDecl &&
3342 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3343 InitDecl = NewVD;
3344
3345 if (InitDecl == NewVD) {
3346 // This is the initializing declaration. If it would inherit 'constinit',
3347 // that's ill-formed. (Note that we do not apply this to the attribute
3348 // form).
3349 if (OldConstInit && OldConstInit->isConstinit())
3350 diagnoseMissingConstinit(S&: *this, InitDecl: NewVD, CIAttr: OldConstInit,
3351 /*AttrBeforeInit=*/true);
3352 } else if (NewConstInit) {
3353 // This is the first time we've been told that this declaration should
3354 // have a constant initializer. If we already saw the initializing
3355 // declaration, this is too late.
3356 if (InitDecl && InitDecl != NewVD) {
3357 diagnoseMissingConstinit(S&: *this, InitDecl, CIAttr: NewConstInit,
3358 /*AttrBeforeInit=*/false);
3359 NewVD->dropAttr<ConstInitAttr>();
3360 }
3361 }
3362 }
3363
3364 // Attributes declared post-definition are currently ignored.
3365 checkNewAttributesAfterDef(S&: *this, New, Old);
3366
3367 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3368 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3369 if (!OldA->isEquivalent(Other: NewA)) {
3370 // This redeclaration changes __asm__ label.
3371 Diag(Loc: New->getLocation(), DiagID: diag::err_different_asm_label);
3372 Diag(Loc: OldA->getLocation(), DiagID: diag::note_previous_declaration);
3373 }
3374 } else if (Old->isUsed()) {
3375 // This redeclaration adds an __asm__ label to a declaration that has
3376 // already been ODR-used.
3377 Diag(Loc: New->getLocation(), DiagID: diag::err_late_asm_label_name)
3378 << isa<FunctionDecl>(Val: Old) << New->getAttr<AsmLabelAttr>()->getRange();
3379 }
3380 }
3381
3382 // Re-declaration cannot add abi_tag's.
3383 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3384 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3385 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3386 if (!llvm::is_contained(Range: OldAbiTagAttr->tags(), Element: NewTag)) {
3387 Diag(Loc: NewAbiTagAttr->getLocation(),
3388 DiagID: diag::err_new_abi_tag_on_redeclaration)
3389 << NewTag;
3390 Diag(Loc: OldAbiTagAttr->getLocation(), DiagID: diag::note_previous_declaration);
3391 }
3392 }
3393 } else {
3394 Diag(Loc: NewAbiTagAttr->getLocation(), DiagID: diag::err_abi_tag_on_redeclaration);
3395 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3396 }
3397 }
3398
3399 // This redeclaration adds a section attribute.
3400 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3401 if (auto *VD = dyn_cast<VarDecl>(Val: New)) {
3402 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3403 Diag(Loc: New->getLocation(), DiagID: diag::warn_attribute_section_on_redeclaration);
3404 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3405 }
3406 }
3407 }
3408
3409 // Redeclaration adds code-seg attribute.
3410 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3411 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3412 !NewCSA->isImplicit() && isa<CXXMethodDecl>(Val: New)) {
3413 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_section)
3414 << 0 /*codeseg*/;
3415 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3416 }
3417
3418 if (!Old->hasAttrs())
3419 return;
3420
3421 bool foundAny = New->hasAttrs();
3422
3423 // Ensure that any moving of objects within the allocated map is done before
3424 // we process them.
3425 if (!foundAny) New->setAttrs(AttrVec());
3426
3427 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3428 // Ignore deprecated/unavailable/availability attributes if requested.
3429 AvailabilityMergeKind LocalAMK = AvailabilityMergeKind::None;
3430 if (isa<DeprecatedAttr>(Val: I) ||
3431 isa<UnavailableAttr>(Val: I) ||
3432 isa<AvailabilityAttr>(Val: I)) {
3433 switch (AMK) {
3434 case AvailabilityMergeKind::None:
3435 continue;
3436
3437 case AvailabilityMergeKind::Redeclaration:
3438 case AvailabilityMergeKind::Override:
3439 case AvailabilityMergeKind::ProtocolImplementation:
3440 case AvailabilityMergeKind::OptionalProtocolImplementation:
3441 LocalAMK = AMK;
3442 break;
3443 }
3444 }
3445
3446 // Already handled.
3447 if (isa<UsedAttr>(Val: I) || isa<RetainAttr>(Val: I))
3448 continue;
3449
3450 // Don't propagate inferred noreturn or conflicting inline attributes to
3451 // explicit specializations.
3452 if (isa<InferredNoReturnAttr>(Val: I) || isa<AlwaysInlineAttr>(Val: I) ||
3453 isa<NoInlineAttr>(Val: I)) {
3454 if (auto *FD = dyn_cast<FunctionDecl>(Val: New);
3455 FD &&
3456 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3457 continue;
3458 }
3459
3460 if (mergeDeclAttribute(S&: *this, D: New, Attr: I, AMK: LocalAMK))
3461 foundAny = true;
3462 }
3463
3464 if (mergeAlignedAttrs(S&: *this, New, Old))
3465 foundAny = true;
3466
3467 if (!foundAny) New->dropAttrs();
3468}
3469
3470void Sema::CheckAttributesOnDeducedType(Decl *D) {
3471 for (const Attr *A : D->attrs())
3472 checkAttrIsTypeDependent(D, A);
3473}
3474
3475// Returns the number of added attributes.
3476template <class T>
3477static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3478 Sema &S) {
3479 unsigned found = 0;
3480 for (const auto *I : From->specific_attrs<T>()) {
3481 if (!DeclHasAttr(To, I)) {
3482 T *newAttr = cast<T>(I->clone(S.Context));
3483 newAttr->setInherited(true);
3484 To->addAttr(A: newAttr);
3485 ++found;
3486 }
3487 }
3488 return found;
3489}
3490
3491template <class F>
3492static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3493 F &&propagator) {
3494 if (!From->hasAttrs()) {
3495 return;
3496 }
3497
3498 bool foundAny = To->hasAttrs();
3499
3500 // Ensure that any moving of objects within the allocated map is
3501 // done before we process them.
3502 if (!foundAny)
3503 To->setAttrs(AttrVec());
3504
3505 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3506
3507 if (!foundAny)
3508 To->dropAttrs();
3509}
3510
3511/// mergeParamDeclAttributes - Copy attributes from the old parameter
3512/// to the new one.
3513static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3514 const ParmVarDecl *oldDecl, Sema &S) {
3515 propagateAttributes(
3516 To: newDecl, From: oldDecl, propagator: [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3517 unsigned found = 0;
3518 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3519 // Propagate the lifetimebound attribute from parameters to the
3520 // most recent declaration. Note that this doesn't include the implicit
3521 // 'this' parameter, as the attribute is applied to the function type in
3522 // that case.
3523 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3524 return found;
3525 });
3526}
3527
3528static bool EquivalentArrayTypes(QualType Old, QualType New,
3529 const ASTContext &Ctx) {
3530
3531 auto NoSizeInfo = [&Ctx](QualType Ty) {
3532 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3533 return true;
3534 if (const auto *VAT = Ctx.getAsVariableArrayType(T: Ty))
3535 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3536 return false;
3537 };
3538
3539 // `type[]` is equivalent to `type *` and `type[*]`.
3540 if (NoSizeInfo(Old) && NoSizeInfo(New))
3541 return true;
3542
3543 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3544 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3545 const auto *OldVAT = Ctx.getAsVariableArrayType(T: Old);
3546 const auto *NewVAT = Ctx.getAsVariableArrayType(T: New);
3547 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3548 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3549 return false;
3550 return true;
3551 }
3552
3553 // Only compare size, ignore Size modifiers and CVR.
3554 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3555 return Ctx.getAsConstantArrayType(T: Old)->getSize() ==
3556 Ctx.getAsConstantArrayType(T: New)->getSize();
3557 }
3558
3559 // Don't try to compare dependent sized array
3560 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3561 return true;
3562 }
3563
3564 return Old == New;
3565}
3566
3567static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3568 const ParmVarDecl *OldParam,
3569 Sema &S) {
3570 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3571 if (auto Newnullability = NewParam->getType()->getNullability()) {
3572 if (*Oldnullability != *Newnullability) {
3573 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_mismatched_nullability_attr)
3574 << DiagNullabilityKind(
3575 *Newnullability,
3576 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3577 != 0))
3578 << DiagNullabilityKind(
3579 *Oldnullability,
3580 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3581 != 0));
3582 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration);
3583 }
3584 } else {
3585 QualType NewT = NewParam->getType();
3586 NewT = S.Context.getAttributedType(nullability: *Oldnullability, modifiedType: NewT, equivalentType: NewT);
3587 NewParam->setType(NewT);
3588 }
3589 }
3590 const auto *OldParamDT = dyn_cast<DecayedType>(Val: OldParam->getType());
3591 const auto *NewParamDT = dyn_cast<DecayedType>(Val: NewParam->getType());
3592 if (OldParamDT && NewParamDT &&
3593 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3594 QualType OldParamOT = OldParamDT->getOriginalType();
3595 QualType NewParamOT = NewParamDT->getOriginalType();
3596 if (!EquivalentArrayTypes(Old: OldParamOT, New: NewParamOT, Ctx: S.getASTContext())) {
3597 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_inconsistent_array_form)
3598 << NewParam << NewParamOT;
3599 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration_as)
3600 << OldParamOT;
3601 }
3602 }
3603}
3604
3605namespace {
3606
3607/// Used in MergeFunctionDecl to keep track of function parameters in
3608/// C.
3609struct GNUCompatibleParamWarning {
3610 ParmVarDecl *OldParm;
3611 ParmVarDecl *NewParm;
3612 QualType PromotedType;
3613};
3614
3615} // end anonymous namespace
3616
3617// Determine whether the previous declaration was a definition, implicit
3618// declaration, or a declaration.
3619template <typename T>
3620static std::pair<diag::kind, SourceLocation>
3621getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3622 diag::kind PrevDiag;
3623 SourceLocation OldLocation = Old->getLocation();
3624 if (Old->isThisDeclarationADefinition())
3625 PrevDiag = diag::note_previous_definition;
3626 else if (Old->isImplicit()) {
3627 PrevDiag = diag::note_previous_implicit_declaration;
3628 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3629 if (FD->getBuiltinID())
3630 PrevDiag = diag::note_previous_builtin_declaration;
3631 }
3632 if (OldLocation.isInvalid())
3633 OldLocation = New->getLocation();
3634 } else
3635 PrevDiag = diag::note_previous_declaration;
3636 return std::make_pair(x&: PrevDiag, y&: OldLocation);
3637}
3638
3639/// canRedefineFunction - checks if a function can be redefined. Currently,
3640/// only extern inline functions can be redefined, and even then only in
3641/// GNU89 mode.
3642static bool canRedefineFunction(const FunctionDecl *FD,
3643 const LangOptions& LangOpts) {
3644 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3645 !LangOpts.CPlusPlus &&
3646 FD->isInlineSpecified() &&
3647 FD->getStorageClass() == SC_Extern);
3648}
3649
3650const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3651 const AttributedType *AT = T->getAs<AttributedType>();
3652 while (AT && !AT->isCallingConv())
3653 AT = AT->getModifiedType()->getAs<AttributedType>();
3654 return AT;
3655}
3656
3657template <typename T>
3658static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3659 const DeclContext *DC = Old->getDeclContext();
3660 if (DC->isRecord())
3661 return false;
3662
3663 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3664 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3665 return true;
3666 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3667 return true;
3668 return false;
3669}
3670
3671template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3672static bool isExternC(VarTemplateDecl *) { return false; }
3673static bool isExternC(FunctionTemplateDecl *) { return false; }
3674
3675/// Check whether a redeclaration of an entity introduced by a
3676/// using-declaration is valid, given that we know it's not an overload
3677/// (nor a hidden tag declaration).
3678template<typename ExpectedDecl>
3679static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3680 ExpectedDecl *New) {
3681 // C++11 [basic.scope.declarative]p4:
3682 // Given a set of declarations in a single declarative region, each of
3683 // which specifies the same unqualified name,
3684 // -- they shall all refer to the same entity, or all refer to functions
3685 // and function templates; or
3686 // -- exactly one declaration shall declare a class name or enumeration
3687 // name that is not a typedef name and the other declarations shall all
3688 // refer to the same variable or enumerator, or all refer to functions
3689 // and function templates; in this case the class name or enumeration
3690 // name is hidden (3.3.10).
3691
3692 // C++11 [namespace.udecl]p14:
3693 // If a function declaration in namespace scope or block scope has the
3694 // same name and the same parameter-type-list as a function introduced
3695 // by a using-declaration, and the declarations do not declare the same
3696 // function, the program is ill-formed.
3697
3698 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3699 if (Old &&
3700 !Old->getDeclContext()->getRedeclContext()->Equals(
3701 New->getDeclContext()->getRedeclContext()) &&
3702 !(isExternC(Old) && isExternC(New)))
3703 Old = nullptr;
3704
3705 if (!Old) {
3706 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3707 S.Diag(Loc: OldS->getTargetDecl()->getLocation(), DiagID: diag::note_using_decl_target);
3708 S.Diag(Loc: OldS->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
3709 return true;
3710 }
3711 return false;
3712}
3713
3714static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3715 const FunctionDecl *B) {
3716 assert(A->getNumParams() == B->getNumParams());
3717
3718 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3719 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3720 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3721 if (AttrA == AttrB)
3722 return true;
3723 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3724 AttrA->isDynamic() == AttrB->isDynamic();
3725 };
3726
3727 return std::equal(first1: A->param_begin(), last1: A->param_end(), first2: B->param_begin(), binary_pred: AttrEq);
3728}
3729
3730/// If necessary, adjust the semantic declaration context for a qualified
3731/// declaration to name the correct inline namespace within the qualifier.
3732static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3733 DeclaratorDecl *OldD) {
3734 // The only case where we need to update the DeclContext is when
3735 // redeclaration lookup for a qualified name finds a declaration
3736 // in an inline namespace within the context named by the qualifier:
3737 //
3738 // inline namespace N { int f(); }
3739 // int ::f(); // Sema DC needs adjusting from :: to N::.
3740 //
3741 // For unqualified declarations, the semantic context *can* change
3742 // along the redeclaration chain (for local extern declarations,
3743 // extern "C" declarations, and friend declarations in particular).
3744 if (!NewD->getQualifier())
3745 return;
3746
3747 // NewD is probably already in the right context.
3748 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3749 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3750 if (NamedDC->Equals(DC: SemaDC))
3751 return;
3752
3753 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3754 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3755 "unexpected context for redeclaration");
3756
3757 auto *LexDC = NewD->getLexicalDeclContext();
3758 auto FixSemaDC = [=](NamedDecl *D) {
3759 if (!D)
3760 return;
3761 D->setDeclContext(SemaDC);
3762 D->setLexicalDeclContext(LexDC);
3763 };
3764
3765 FixSemaDC(NewD);
3766 if (auto *FD = dyn_cast<FunctionDecl>(Val: NewD))
3767 FixSemaDC(FD->getDescribedFunctionTemplate());
3768 else if (auto *VD = dyn_cast<VarDecl>(Val: NewD))
3769 FixSemaDC(VD->getDescribedVarTemplate());
3770}
3771
3772bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3773 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3774 // Verify the old decl was also a function.
3775 FunctionDecl *Old = OldD->getAsFunction();
3776 if (!Old) {
3777 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: OldD)) {
3778 // We don't need to check the using friend pattern from other module unit
3779 // since we should have diagnosed such cases in its unit already.
3780 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3781 Diag(Loc: New->getLocation(), DiagID: diag::err_using_decl_friend);
3782 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
3783 DiagID: diag::note_using_decl_target);
3784 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
3785 << 0;
3786 return true;
3787 }
3788
3789 // Check whether the two declarations might declare the same function or
3790 // function template.
3791 if (FunctionTemplateDecl *NewTemplate =
3792 New->getDescribedFunctionTemplate()) {
3793 if (checkUsingShadowRedecl<FunctionTemplateDecl>(S&: *this, OldS: Shadow,
3794 New: NewTemplate))
3795 return true;
3796 OldD = Old = cast<FunctionTemplateDecl>(Val: Shadow->getTargetDecl())
3797 ->getAsFunction();
3798 } else {
3799 if (checkUsingShadowRedecl<FunctionDecl>(S&: *this, OldS: Shadow, New))
3800 return true;
3801 OldD = Old = cast<FunctionDecl>(Val: Shadow->getTargetDecl());
3802 }
3803 } else {
3804 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
3805 << New->getDeclName();
3806 notePreviousDefinition(Old: OldD, New: New->getLocation());
3807 return true;
3808 }
3809 }
3810
3811 // If the old declaration was found in an inline namespace and the new
3812 // declaration was qualified, update the DeclContext to match.
3813 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
3814
3815 // If the old declaration is invalid, just give up here.
3816 if (Old->isInvalidDecl())
3817 return true;
3818
3819 // Disallow redeclaration of some builtins.
3820 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3821 Diag(Loc: New->getLocation(), DiagID: diag::err_builtin_redeclare) << Old->getDeclName();
3822 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_builtin_declaration)
3823 << Old << Old->getType();
3824 return true;
3825 }
3826
3827 diag::kind PrevDiag;
3828 SourceLocation OldLocation;
3829 std::tie(args&: PrevDiag, args&: OldLocation) =
3830 getNoteDiagForInvalidRedeclaration(Old, New);
3831
3832 // Don't complain about this if we're in GNU89 mode and the old function
3833 // is an extern inline function.
3834 // Don't complain about specializations. They are not supposed to have
3835 // storage classes.
3836 if (!isa<CXXMethodDecl>(Val: New) && !isa<CXXMethodDecl>(Val: Old) &&
3837 New->getStorageClass() == SC_Static &&
3838 Old->hasExternalFormalLinkage() &&
3839 !New->getTemplateSpecializationInfo() &&
3840 !canRedefineFunction(FD: Old, LangOpts: getLangOpts())) {
3841 if (getLangOpts().MicrosoftExt) {
3842 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static) << New;
3843 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3844 } else {
3845 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static)
3846 << New << /*MixedLinkageUB=*/false;
3847 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3848 return true;
3849 }
3850 }
3851
3852 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3853 if (!Old->hasAttr<InternalLinkageAttr>()) {
3854 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
3855 << ILA;
3856 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3857 New->dropAttr<InternalLinkageAttr>();
3858 }
3859
3860 if (auto *EA = New->getAttr<ErrorAttr>()) {
3861 if (!Old->hasAttr<ErrorAttr>()) {
3862 Diag(Loc: EA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl) << EA;
3863 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3864 New->dropAttr<ErrorAttr>();
3865 }
3866 }
3867
3868 if (CheckRedeclarationInModule(New, Old))
3869 return true;
3870
3871 if (!getLangOpts().CPlusPlus) {
3872 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3873 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3874 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_overloadable_mismatch)
3875 << New << OldOvl;
3876
3877 // Try our best to find a decl that actually has the overloadable
3878 // attribute for the note. In most cases (e.g. programs with only one
3879 // broken declaration/definition), this won't matter.
3880 //
3881 // FIXME: We could do this if we juggled some extra state in
3882 // OverloadableAttr, rather than just removing it.
3883 const Decl *DiagOld = Old;
3884 if (OldOvl) {
3885 auto OldIter = llvm::find_if(Range: Old->redecls(), P: [](const Decl *D) {
3886 const auto *A = D->getAttr<OverloadableAttr>();
3887 return A && !A->isImplicit();
3888 });
3889 // If we've implicitly added *all* of the overloadable attrs to this
3890 // chain, emitting a "previous redecl" note is pointless.
3891 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3892 }
3893
3894 if (DiagOld)
3895 Diag(Loc: DiagOld->getLocation(),
3896 DiagID: diag::note_attribute_overloadable_prev_overload)
3897 << OldOvl;
3898
3899 if (OldOvl)
3900 New->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
3901 else
3902 New->dropAttr<OverloadableAttr>();
3903 }
3904 }
3905
3906 // It is not permitted to redeclare an SME function with different SME
3907 // attributes.
3908 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
3909 Diag(Loc: New->getLocation(), DiagID: diag::err_sme_attr_mismatch)
3910 << New->getType() << Old->getType();
3911 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3912 return true;
3913 }
3914
3915 // If a function is first declared with a calling convention, but is later
3916 // declared or defined without one, all following decls assume the calling
3917 // convention of the first.
3918 //
3919 // It's OK if a function is first declared without a calling convention,
3920 // but is later declared or defined with the default calling convention.
3921 //
3922 // To test if either decl has an explicit calling convention, we look for
3923 // AttributedType sugar nodes on the type as written. If they are missing or
3924 // were canonicalized away, we assume the calling convention was implicit.
3925 //
3926 // Note also that we DO NOT return at this point, because we still have
3927 // other tests to run.
3928 QualType OldQType = Context.getCanonicalType(T: Old->getType());
3929 QualType NewQType = Context.getCanonicalType(T: New->getType());
3930 const FunctionType *OldType = cast<FunctionType>(Val&: OldQType);
3931 const FunctionType *NewType = cast<FunctionType>(Val&: NewQType);
3932 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3933 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3934 bool RequiresAdjustment = false;
3935
3936 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3937 FunctionDecl *First = Old->getFirstDecl();
3938 const FunctionType *FT =
3939 First->getType().getCanonicalType()->castAs<FunctionType>();
3940 FunctionType::ExtInfo FI = FT->getExtInfo();
3941 bool NewCCExplicit = getCallingConvAttributedType(T: New->getType());
3942 if (!NewCCExplicit) {
3943 // Inherit the CC from the previous declaration if it was specified
3944 // there but not here.
3945 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3946 RequiresAdjustment = true;
3947 } else if (Old->getBuiltinID()) {
3948 // Builtin attribute isn't propagated to the new one yet at this point,
3949 // so we check if the old one is a builtin.
3950
3951 // Calling Conventions on a Builtin aren't really useful and setting a
3952 // default calling convention and cdecl'ing some builtin redeclarations is
3953 // common, so warn and ignore the calling convention on the redeclaration.
3954 Diag(Loc: New->getLocation(), DiagID: diag::warn_cconv_unsupported)
3955 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3956 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3957 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3958 RequiresAdjustment = true;
3959 } else {
3960 // Calling conventions aren't compatible, so complain.
3961 bool FirstCCExplicit = getCallingConvAttributedType(T: First->getType());
3962 Diag(Loc: New->getLocation(), DiagID: diag::err_cconv_change)
3963 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3964 << !FirstCCExplicit
3965 << (!FirstCCExplicit ? "" :
3966 FunctionType::getNameForCallConv(CC: FI.getCC()));
3967
3968 // Put the note on the first decl, since it is the one that matters.
3969 Diag(Loc: First->getLocation(), DiagID: diag::note_previous_declaration);
3970 return true;
3971 }
3972 }
3973
3974 // FIXME: diagnose the other way around?
3975 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3976 NewTypeInfo = NewTypeInfo.withNoReturn(noReturn: true);
3977 RequiresAdjustment = true;
3978 }
3979
3980 // If the declaration is marked with cfi_unchecked_callee but the definition
3981 // isn't, the definition is also cfi_unchecked_callee.
3982 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3983 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3984 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3985 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3986
3987 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3988 EPI2.CFIUncheckedCallee = true;
3989 NewQType = Context.getFunctionType(ResultTy: FPT2->getReturnType(),
3990 Args: FPT2->getParamTypes(), EPI: EPI2);
3991 NewType = cast<FunctionType>(Val&: NewQType);
3992 New->setType(NewQType);
3993 }
3994 }
3995 }
3996
3997 // Merge regparm attribute.
3998 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3999 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
4000 if (NewTypeInfo.getHasRegParm()) {
4001 Diag(Loc: New->getLocation(), DiagID: diag::err_regparm_mismatch)
4002 << NewType->getRegParmType()
4003 << OldType->getRegParmType();
4004 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
4005 return true;
4006 }
4007
4008 NewTypeInfo = NewTypeInfo.withRegParm(RegParm: OldTypeInfo.getRegParm());
4009 RequiresAdjustment = true;
4010 }
4011
4012 // Merge ns_returns_retained attribute.
4013 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
4014 if (NewTypeInfo.getProducesResult()) {
4015 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch)
4016 << "'ns_returns_retained'";
4017 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
4018 return true;
4019 }
4020
4021 NewTypeInfo = NewTypeInfo.withProducesResult(producesResult: true);
4022 RequiresAdjustment = true;
4023 }
4024
4025 if (OldTypeInfo.getNoCallerSavedRegs() !=
4026 NewTypeInfo.getNoCallerSavedRegs()) {
4027 if (NewTypeInfo.getNoCallerSavedRegs()) {
4028 AnyX86NoCallerSavedRegistersAttr *Attr =
4029 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
4030 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch) << Attr;
4031 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
4032 return true;
4033 }
4034
4035 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(noCallerSavedRegs: true);
4036 RequiresAdjustment = true;
4037 }
4038
4039 if (RequiresAdjustment) {
4040 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
4041 AdjustedType = Context.adjustFunctionType(Fn: AdjustedType, EInfo: NewTypeInfo);
4042 New->setType(QualType(AdjustedType, 0));
4043 NewQType = Context.getCanonicalType(T: New->getType());
4044 }
4045
4046 // If this redeclaration makes the function inline, we may need to add it to
4047 // UndefinedButUsed.
4048 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
4049 !getLangOpts().GNUInline && Old->isUsed(CheckUsedAttr: false) && !Old->isDefined() &&
4050 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
4051 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4052 y: SourceLocation()));
4053
4054 // If this redeclaration makes it newly gnu_inline, we don't want to warn
4055 // about it.
4056 if (New->hasAttr<GNUInlineAttr>() &&
4057 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
4058 UndefinedButUsed.erase(Key: Old->getCanonicalDecl());
4059 }
4060
4061 // If pass_object_size params don't match up perfectly, this isn't a valid
4062 // redeclaration.
4063 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
4064 !hasIdenticalPassObjectSizeAttrs(A: Old, B: New)) {
4065 Diag(Loc: New->getLocation(), DiagID: diag::err_different_pass_object_size_params)
4066 << New->getDeclName();
4067 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4068 return true;
4069 }
4070
4071 QualType OldQTypeForComparison = OldQType;
4072 if (Context.hasAnyFunctionEffects()) {
4073 const auto OldFX = Old->getFunctionEffects();
4074 const auto NewFX = New->getFunctionEffects();
4075 if (OldFX != NewFX) {
4076 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
4077 for (const auto &Diff : Diffs) {
4078 if (Diff.shouldDiagnoseRedeclaration(OldFunction: *Old, OldFX, NewFunction: *New, NewFX)) {
4079 Diag(Loc: New->getLocation(),
4080 DiagID: diag::warn_mismatched_func_effect_redeclaration)
4081 << Diff.effectName();
4082 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4083 }
4084 }
4085 // Following a warning, we could skip merging effects from the previous
4086 // declaration, but that would trigger an additional "conflicting types"
4087 // error.
4088 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4089 FunctionEffectSet::Conflicts MergeErrs;
4090 FunctionEffectSet MergedFX =
4091 FunctionEffectSet::getUnion(LHS: OldFX, RHS: NewFX, Errs&: MergeErrs);
4092 if (!MergeErrs.empty())
4093 diagnoseFunctionEffectMergeConflicts(Errs: MergeErrs, NewLoc: New->getLocation(),
4094 OldLoc: Old->getLocation());
4095
4096 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4097 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4098 QualType ModQT = Context.getFunctionType(ResultTy: NewFPT->getReturnType(),
4099 Args: NewFPT->getParamTypes(), EPI);
4100
4101 New->setType(ModQT);
4102 NewQType = New->getType();
4103
4104 // Revise OldQTForComparison to include the merged effects,
4105 // so as not to fail due to differences later.
4106 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4107 EPI = OldFPT->getExtProtoInfo();
4108 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4109 OldQTypeForComparison = Context.getFunctionType(
4110 ResultTy: OldFPT->getReturnType(), Args: OldFPT->getParamTypes(), EPI);
4111 }
4112 if (OldFX.empty()) {
4113 // A redeclaration may add the attribute to a previously seen function
4114 // body which needs to be verified.
4115 maybeAddDeclWithEffects(D: Old, FX: MergedFX);
4116 }
4117 }
4118 }
4119 }
4120
4121 if (getLangOpts().CPlusPlus) {
4122 OldQType = Context.getCanonicalType(T: Old->getType());
4123 NewQType = Context.getCanonicalType(T: New->getType());
4124
4125 // Go back to the type source info to compare the declared return types,
4126 // per C++1y [dcl.type.auto]p13:
4127 // Redeclarations or specializations of a function or function template
4128 // with a declared return type that uses a placeholder type shall also
4129 // use that placeholder, not a deduced type.
4130 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4131 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4132 if (!Context.hasSameType(T1: OldDeclaredReturnType, T2: NewDeclaredReturnType) &&
4133 canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewDeclaredReturnType,
4134 OldT: OldDeclaredReturnType)) {
4135 QualType ResQT;
4136 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4137 OldDeclaredReturnType->isObjCObjectPointerType())
4138 // FIXME: This does the wrong thing for a deduced return type.
4139 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4140 if (ResQT.isNull()) {
4141 if (New->isCXXClassMember() && New->isOutOfLine())
4142 Diag(Loc: New->getLocation(), DiagID: diag::err_member_def_does_not_match_ret_type)
4143 << New << New->getReturnTypeSourceRange();
4144 else if (Old->isExternC() && New->isExternC() &&
4145 !Old->hasAttr<OverloadableAttr>() &&
4146 !New->hasAttr<OverloadableAttr>())
4147 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4148 else
4149 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_diff_return_type)
4150 << New->getReturnTypeSourceRange();
4151 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType()
4152 << Old->getReturnTypeSourceRange();
4153 return true;
4154 }
4155 else
4156 NewQType = ResQT;
4157 }
4158
4159 QualType OldReturnType = OldType->getReturnType();
4160 QualType NewReturnType = cast<FunctionType>(Val&: NewQType)->getReturnType();
4161 if (OldReturnType != NewReturnType) {
4162 // If this function has a deduced return type and has already been
4163 // defined, copy the deduced value from the old declaration.
4164 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4165 if (OldAT && OldAT->isDeduced()) {
4166 QualType DT = OldAT->getDeducedType();
4167 if (DT.isNull()) {
4168 New->setType(SubstAutoTypeDependent(TypeWithAuto: New->getType()));
4169 NewQType = Context.getCanonicalType(T: SubstAutoTypeDependent(TypeWithAuto: NewQType));
4170 } else {
4171 New->setType(SubstAutoType(TypeWithAuto: New->getType(), Replacement: DT));
4172 NewQType = Context.getCanonicalType(T: SubstAutoType(TypeWithAuto: NewQType, Replacement: DT));
4173 }
4174 }
4175 }
4176
4177 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
4178 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
4179 if (OldMethod && NewMethod) {
4180 // Preserve triviality.
4181 NewMethod->setTrivial(OldMethod->isTrivial());
4182
4183 // MSVC allows explicit template specialization at class scope:
4184 // 2 CXXMethodDecls referring to the same function will be injected.
4185 // We don't want a redeclaration error.
4186 bool IsClassScopeExplicitSpecialization =
4187 OldMethod->isFunctionTemplateSpecialization() &&
4188 NewMethod->isFunctionTemplateSpecialization();
4189 bool isFriend = NewMethod->getFriendObjectKind();
4190
4191 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4192 !IsClassScopeExplicitSpecialization) {
4193 // -- Member function declarations with the same name and the
4194 // same parameter types cannot be overloaded if any of them
4195 // is a static member function declaration.
4196 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4197 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_static_nonstatic_member);
4198 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4199 return true;
4200 }
4201
4202 // C++ [class.mem]p1:
4203 // [...] A member shall not be declared twice in the
4204 // member-specification, except that a nested class or member
4205 // class template can be declared and then later defined.
4206 if (!inTemplateInstantiation()) {
4207 unsigned NewDiag;
4208 if (isa<CXXConstructorDecl>(Val: OldMethod))
4209 NewDiag = diag::err_constructor_redeclared;
4210 else if (isa<CXXDestructorDecl>(Val: NewMethod))
4211 NewDiag = diag::err_destructor_redeclared;
4212 else if (isa<CXXConversionDecl>(Val: NewMethod))
4213 NewDiag = diag::err_conv_function_redeclared;
4214 else
4215 NewDiag = diag::err_member_redeclared;
4216
4217 Diag(Loc: New->getLocation(), DiagID: NewDiag);
4218 } else {
4219 Diag(Loc: New->getLocation(), DiagID: diag::err_member_redeclared_in_instantiation)
4220 << New << New->getType();
4221 }
4222 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4223 return true;
4224
4225 // Complain if this is an explicit declaration of a special
4226 // member that was initially declared implicitly.
4227 //
4228 // As an exception, it's okay to befriend such methods in order
4229 // to permit the implicit constructor/destructor/operator calls.
4230 } else if (OldMethod->isImplicit()) {
4231 if (isFriend) {
4232 NewMethod->setImplicit();
4233 } else {
4234 Diag(Loc: NewMethod->getLocation(),
4235 DiagID: diag::err_definition_of_implicitly_declared_member)
4236 << New << OldMethod->getSpecialMemberKind();
4237 return true;
4238 }
4239 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4240 Diag(Loc: NewMethod->getLocation(),
4241 DiagID: diag::err_definition_of_explicitly_defaulted_member)
4242 << OldMethod->getSpecialMemberKind();
4243 return true;
4244 }
4245 }
4246
4247 // C++1z [over.load]p2
4248 // Certain function declarations cannot be overloaded:
4249 // -- Function declarations that differ only in the return type,
4250 // the exception specification, or both cannot be overloaded.
4251
4252 // Check the exception specifications match. This may recompute the type of
4253 // both Old and New if it resolved exception specifications, so grab the
4254 // types again after this. Because this updates the type, we do this before
4255 // any of the other checks below, which may update the "de facto" NewQType
4256 // but do not necessarily update the type of New.
4257 if (CheckEquivalentExceptionSpec(Old, New))
4258 return true;
4259
4260 // C++11 [dcl.attr.noreturn]p1:
4261 // The first declaration of a function shall specify the noreturn
4262 // attribute if any declaration of that function specifies the noreturn
4263 // attribute.
4264 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4265 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4266 Diag(Loc: NRA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4267 << NRA;
4268 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4269 }
4270
4271 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4272 // When a function is declared with SYCL_EXTERNAL, that macro must be
4273 // used on the first declaration of that function in the translation unit.
4274 // Redeclarations of the function in the same translation unit may
4275 // optionally use SYCL_EXTERNAL, but this is not required.
4276 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4277 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4278 Diag(Loc: SEA->getLocation(), DiagID: diag::warn_sycl_external_missing_on_first_decl)
4279 << SEA;
4280 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4281 }
4282
4283 // (C++98 8.3.5p3):
4284 // All declarations for a function shall agree exactly in both the
4285 // return type and the parameter-type-list.
4286 // We also want to respect all the extended bits except noreturn.
4287
4288 // noreturn should now match unless the old type info didn't have it.
4289 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4290 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4291 const FunctionType *OldTypeForComparison
4292 = Context.adjustFunctionType(Fn: OldType, EInfo: OldTypeInfo.withNoReturn(noReturn: true));
4293 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4294 assert(OldQTypeForComparison.isCanonical());
4295 }
4296
4297 if (haveIncompatibleLanguageLinkages(Old, New)) {
4298 // As a special case, retain the language linkage from previous
4299 // declarations of a friend function as an extension.
4300 //
4301 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4302 // and is useful because there's otherwise no way to specify language
4303 // linkage within class scope.
4304 //
4305 // Check cautiously as the friend object kind isn't yet complete.
4306 if (New->getFriendObjectKind() != Decl::FOK_None) {
4307 Diag(Loc: New->getLocation(), DiagID: diag::ext_retained_language_linkage) << New;
4308 Diag(Loc: OldLocation, DiagID: PrevDiag);
4309 } else {
4310 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4311 Diag(Loc: OldLocation, DiagID: PrevDiag);
4312 return true;
4313 }
4314 }
4315
4316 // HLSL check parameters for matching ABI specifications.
4317 if (getLangOpts().HLSL) {
4318 if (HLSL().CheckCompatibleParameterABI(New, Old))
4319 return true;
4320
4321 // If no errors are generated when checking parameter ABIs we can check if
4322 // the two declarations have the same type ignoring the ABIs and if so,
4323 // the declarations can be merged. This case for merging is only valid in
4324 // HLSL because there are no valid cases of merging mismatched parameter
4325 // ABIs except the HLSL implicit in and explicit in.
4326 if (Context.hasSameFunctionTypeIgnoringParamABI(T: OldQTypeForComparison,
4327 U: NewQType))
4328 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4329 // Fall through for conflicting redeclarations and redefinitions.
4330 }
4331
4332 // If the function types are compatible, merge the declarations. Ignore the
4333 // exception specifier because it was already checked above in
4334 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4335 // about incompatible types under -fms-compatibility.
4336 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(T: OldQTypeForComparison,
4337 U: NewQType))
4338 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4339
4340 // If the types are imprecise (due to dependent constructs in friends or
4341 // local extern declarations), it's OK if they differ. We'll check again
4342 // during instantiation.
4343 if (!canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewQType, OldT: OldQType))
4344 return false;
4345
4346 // Fall through for conflicting redeclarations and redefinitions.
4347 }
4348
4349 // C: Function types need to be compatible, not identical. This handles
4350 // duplicate function decls like "void f(int); void f(enum X);" properly.
4351 if (!getLangOpts().CPlusPlus) {
4352 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4353 // type is specified by a function definition that contains a (possibly
4354 // empty) identifier list, both shall agree in the number of parameters
4355 // and the type of each parameter shall be compatible with the type that
4356 // results from the application of default argument promotions to the
4357 // type of the corresponding identifier. ...
4358 // This cannot be handled by ASTContext::typesAreCompatible() because that
4359 // doesn't know whether the function type is for a definition or not when
4360 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4361 // we need to cover here is that the number of arguments agree as the
4362 // default argument promotion rules were already checked by
4363 // ASTContext::typesAreCompatible().
4364 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4365 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4366 if (Old->hasInheritedPrototype())
4367 Old = Old->getCanonicalDecl();
4368 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4369 Diag(Loc: Old->getLocation(), DiagID: PrevDiag) << Old << Old->getType();
4370 return true;
4371 }
4372
4373 // If we are merging two functions where only one of them has a prototype,
4374 // we may have enough information to decide to issue a diagnostic that the
4375 // function without a prototype will change behavior in C23. This handles
4376 // cases like:
4377 // void i(); void i(int j);
4378 // void i(int j); void i();
4379 // void i(); void i(int j) {}
4380 // See ActOnFinishFunctionBody() for other cases of the behavior change
4381 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4382 // type without a prototype.
4383 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4384 !New->isImplicit() && !Old->isImplicit()) {
4385 const FunctionDecl *WithProto, *WithoutProto;
4386 if (New->hasWrittenPrototype()) {
4387 WithProto = New;
4388 WithoutProto = Old;
4389 } else {
4390 WithProto = Old;
4391 WithoutProto = New;
4392 }
4393
4394 if (WithProto->getNumParams() != 0) {
4395 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4396 // The one without the prototype will be changing behavior in C23, so
4397 // warn about that one so long as it's a user-visible declaration.
4398 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4399 if (WithoutProto == New)
4400 IsWithoutProtoADef = NewDeclIsDefn;
4401 else
4402 IsWithProtoADef = NewDeclIsDefn;
4403 Diag(Loc: WithoutProto->getLocation(),
4404 DiagID: diag::warn_non_prototype_changes_behavior)
4405 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4406 << (WithoutProto == Old) << IsWithProtoADef;
4407
4408 // The reason the one without the prototype will be changing behavior
4409 // is because of the one with the prototype, so note that so long as
4410 // it's a user-visible declaration. There is one exception to this:
4411 // when the new declaration is a definition without a prototype, the
4412 // old declaration with a prototype is not the cause of the issue,
4413 // and that does not need to be noted because the one with a
4414 // prototype will not change behavior in C23.
4415 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4416 !IsWithoutProtoADef)
4417 Diag(Loc: WithProto->getLocation(), DiagID: diag::note_conflicting_prototype);
4418 }
4419 }
4420 }
4421
4422 if (Context.typesAreCompatible(T1: OldQType, T2: NewQType)) {
4423 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4424 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4425 const FunctionProtoType *OldProto = nullptr;
4426 if (MergeTypeWithOld && isa<FunctionNoProtoType>(Val: NewFuncType) &&
4427 (OldProto = dyn_cast<FunctionProtoType>(Val: OldFuncType))) {
4428 // The old declaration provided a function prototype, but the
4429 // new declaration does not. Merge in the prototype.
4430 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4431 NewQType = Context.getFunctionType(ResultTy: NewFuncType->getReturnType(),
4432 Args: OldProto->getParamTypes(),
4433 EPI: OldProto->getExtProtoInfo());
4434 New->setType(NewQType);
4435 New->setHasInheritedPrototype();
4436
4437 // Synthesize parameters with the same types.
4438 SmallVector<ParmVarDecl *, 16> Params;
4439 for (const auto &ParamType : OldProto->param_types()) {
4440 ParmVarDecl *Param = ParmVarDecl::Create(
4441 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
4442 T: ParamType, /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
4443 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
4444 Param->setImplicit();
4445 Params.push_back(Elt: Param);
4446 }
4447
4448 New->setParams(Params);
4449 }
4450
4451 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4452 }
4453 }
4454
4455 // Check if the function types are compatible when pointer size address
4456 // spaces are ignored.
4457 if (Context.hasSameFunctionTypeIgnoringPtrSizes(T: OldQType, U: NewQType))
4458 return false;
4459
4460 // GNU C permits a K&R definition to follow a prototype declaration
4461 // if the declared types of the parameters in the K&R definition
4462 // match the types in the prototype declaration, even when the
4463 // promoted types of the parameters from the K&R definition differ
4464 // from the types in the prototype. GCC then keeps the types from
4465 // the prototype.
4466 //
4467 // If a variadic prototype is followed by a non-variadic K&R definition,
4468 // the K&R definition becomes variadic. This is sort of an edge case, but
4469 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4470 // C99 6.9.1p8.
4471 if (!getLangOpts().CPlusPlus &&
4472 Old->hasPrototype() && !New->hasPrototype() &&
4473 New->getType()->getAs<FunctionProtoType>() &&
4474 Old->getNumParams() == New->getNumParams()) {
4475 SmallVector<QualType, 16> ArgTypes;
4476 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4477 const FunctionProtoType *OldProto
4478 = Old->getType()->getAs<FunctionProtoType>();
4479 const FunctionProtoType *NewProto
4480 = New->getType()->getAs<FunctionProtoType>();
4481
4482 // Determine whether this is the GNU C extension.
4483 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4484 NewProto->getReturnType());
4485 bool LooseCompatible = !MergedReturn.isNull();
4486 for (unsigned Idx = 0, End = Old->getNumParams();
4487 LooseCompatible && Idx != End; ++Idx) {
4488 ParmVarDecl *OldParm = Old->getParamDecl(i: Idx);
4489 ParmVarDecl *NewParm = New->getParamDecl(i: Idx);
4490 if (Context.typesAreCompatible(T1: OldParm->getType(),
4491 T2: NewProto->getParamType(i: Idx))) {
4492 ArgTypes.push_back(Elt: NewParm->getType());
4493 } else if (Context.typesAreCompatible(T1: OldParm->getType(),
4494 T2: NewParm->getType(),
4495 /*CompareUnqualified=*/true)) {
4496 GNUCompatibleParamWarning Warn = { .OldParm: OldParm, .NewParm: NewParm,
4497 .PromotedType: NewProto->getParamType(i: Idx) };
4498 Warnings.push_back(Elt: Warn);
4499 ArgTypes.push_back(Elt: NewParm->getType());
4500 } else
4501 LooseCompatible = false;
4502 }
4503
4504 if (LooseCompatible) {
4505 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4506 Diag(Loc: Warnings[Warn].NewParm->getLocation(),
4507 DiagID: diag::ext_param_promoted_not_compatible_with_prototype)
4508 << Warnings[Warn].PromotedType
4509 << Warnings[Warn].OldParm->getType();
4510 if (Warnings[Warn].OldParm->getLocation().isValid())
4511 Diag(Loc: Warnings[Warn].OldParm->getLocation(),
4512 DiagID: diag::note_previous_declaration);
4513 }
4514
4515 if (MergeTypeWithOld)
4516 New->setType(Context.getFunctionType(ResultTy: MergedReturn, Args: ArgTypes,
4517 EPI: OldProto->getExtProtoInfo()));
4518 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4519 }
4520
4521 // Fall through to diagnose conflicting types.
4522 }
4523
4524 // A function that has already been declared has been redeclared or
4525 // defined with a different type; show an appropriate diagnostic.
4526
4527 // If the previous declaration was an implicitly-generated builtin
4528 // declaration, then at the very least we should use a specialized note.
4529 unsigned BuiltinID;
4530 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4531 // If it's actually a library-defined builtin function like 'malloc'
4532 // or 'printf', just warn about the incompatible redeclaration.
4533 if (Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) {
4534 Diag(Loc: New->getLocation(), DiagID: diag::warn_redecl_library_builtin) << New;
4535 Diag(Loc: OldLocation, DiagID: diag::note_previous_builtin_declaration)
4536 << Old << Old->getType();
4537 return false;
4538 }
4539
4540 PrevDiag = diag::note_previous_builtin_declaration;
4541 }
4542
4543 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New->getDeclName();
4544 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4545 return true;
4546}
4547
4548bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4549 Scope *S, bool MergeTypeWithOld) {
4550 // Merge the attributes
4551 mergeDeclAttributes(New, Old);
4552
4553 // Merge "pure" flag.
4554 if (Old->isPureVirtual())
4555 New->setIsPureVirtual();
4556
4557 // Merge "used" flag.
4558 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4559 New->setIsUsed();
4560
4561 // Merge attributes from the parameters. These can mismatch with K&R
4562 // declarations.
4563 if (New->getNumParams() == Old->getNumParams())
4564 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4565 ParmVarDecl *NewParam = New->getParamDecl(i);
4566 ParmVarDecl *OldParam = Old->getParamDecl(i);
4567 mergeParamDeclAttributes(newDecl: NewParam, oldDecl: OldParam, S&: *this);
4568 mergeParamDeclTypes(NewParam, OldParam, S&: *this);
4569 }
4570
4571 if (getLangOpts().CPlusPlus)
4572 return MergeCXXFunctionDecl(New, Old, S);
4573
4574 // Merge the function types so the we get the composite types for the return
4575 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4576 // was visible.
4577 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4578 if (!Merged.isNull() && MergeTypeWithOld)
4579 New->setType(Merged);
4580
4581 return false;
4582}
4583
4584void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4585 ObjCMethodDecl *oldMethod) {
4586 // Merge the attributes, including deprecated/unavailable
4587 AvailabilityMergeKind MergeKind =
4588 isa<ObjCProtocolDecl>(Val: oldMethod->getDeclContext())
4589 ? (oldMethod->isOptional()
4590 ? AvailabilityMergeKind::OptionalProtocolImplementation
4591 : AvailabilityMergeKind::ProtocolImplementation)
4592 : isa<ObjCImplDecl>(Val: newMethod->getDeclContext())
4593 ? AvailabilityMergeKind::Redeclaration
4594 : AvailabilityMergeKind::Override;
4595
4596 mergeDeclAttributes(New: newMethod, Old: oldMethod, AMK: MergeKind);
4597
4598 // Merge attributes from the parameters.
4599 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4600 oe = oldMethod->param_end();
4601 for (ObjCMethodDecl::param_iterator
4602 ni = newMethod->param_begin(), ne = newMethod->param_end();
4603 ni != ne && oi != oe; ++ni, ++oi)
4604 mergeParamDeclAttributes(newDecl: *ni, oldDecl: *oi, S&: *this);
4605
4606 ObjC().CheckObjCMethodOverride(NewMethod: newMethod, Overridden: oldMethod);
4607}
4608
4609static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4610 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4611
4612 S.Diag(Loc: New->getLocation(), DiagID: New->isThisDeclarationADefinition()
4613 ? diag::err_redefinition_different_type
4614 : diag::err_redeclaration_different_type)
4615 << New->getDeclName() << New->getType() << Old->getType();
4616
4617 diag::kind PrevDiag;
4618 SourceLocation OldLocation;
4619 std::tie(args&: PrevDiag, args&: OldLocation)
4620 = getNoteDiagForInvalidRedeclaration(Old, New);
4621 S.Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4622 New->setInvalidDecl();
4623}
4624
4625void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4626 bool MergeTypeWithOld) {
4627 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4628 return;
4629
4630 QualType MergedT;
4631 if (getLangOpts().CPlusPlus) {
4632 if (New->getType()->isUndeducedType()) {
4633 // We don't know what the new type is until the initializer is attached.
4634 return;
4635 } else if (Context.hasSameType(T1: New->getType(), T2: Old->getType())) {
4636 // These could still be something that needs exception specs checked.
4637 return MergeVarDeclExceptionSpecs(New, Old);
4638 }
4639 // C++ [basic.link]p10:
4640 // [...] the types specified by all declarations referring to a given
4641 // object or function shall be identical, except that declarations for an
4642 // array object can specify array types that differ by the presence or
4643 // absence of a major array bound (8.3.4).
4644 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4645 const ArrayType *OldArray = Context.getAsArrayType(T: Old->getType());
4646 const ArrayType *NewArray = Context.getAsArrayType(T: New->getType());
4647
4648 // We are merging a variable declaration New into Old. If it has an array
4649 // bound, and that bound differs from Old's bound, we should diagnose the
4650 // mismatch.
4651 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4652 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4653 PrevVD = PrevVD->getPreviousDecl()) {
4654 QualType PrevVDTy = PrevVD->getType();
4655 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4656 continue;
4657
4658 if (!Context.hasSameType(T1: New->getType(), T2: PrevVDTy))
4659 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old: PrevVD);
4660 }
4661 }
4662
4663 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4664 if (Context.hasSameType(T1: OldArray->getElementType(),
4665 T2: NewArray->getElementType()))
4666 MergedT = New->getType();
4667 }
4668 // FIXME: Check visibility. New is hidden but has a complete type. If New
4669 // has no array bound, it should not inherit one from Old, if Old is not
4670 // visible.
4671 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4672 if (Context.hasSameType(T1: OldArray->getElementType(),
4673 T2: NewArray->getElementType()))
4674 MergedT = Old->getType();
4675 }
4676 }
4677 else if (New->getType()->isObjCObjectPointerType() &&
4678 Old->getType()->isObjCObjectPointerType()) {
4679 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4680 Old->getType());
4681 }
4682 } else {
4683 // C 6.2.7p2:
4684 // All declarations that refer to the same object or function shall have
4685 // compatible type.
4686 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4687 }
4688 if (MergedT.isNull()) {
4689 // It's OK if we couldn't merge types if either type is dependent, for a
4690 // block-scope variable. In other cases (static data members of class
4691 // templates, variable templates, ...), we require the types to be
4692 // equivalent.
4693 // FIXME: The C++ standard doesn't say anything about this.
4694 if ((New->getType()->isDependentType() ||
4695 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4696 // If the old type was dependent, we can't merge with it, so the new type
4697 // becomes dependent for now. We'll reproduce the original type when we
4698 // instantiate the TypeSourceInfo for the variable.
4699 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4700 New->setType(Context.DependentTy);
4701 return;
4702 }
4703 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old);
4704 }
4705
4706 // Don't actually update the type on the new declaration if the old
4707 // declaration was an extern declaration in a different scope.
4708 if (MergeTypeWithOld)
4709 New->setType(MergedT);
4710}
4711
4712static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4713 LookupResult &Previous) {
4714 // C11 6.2.7p4:
4715 // For an identifier with internal or external linkage declared
4716 // in a scope in which a prior declaration of that identifier is
4717 // visible, if the prior declaration specifies internal or
4718 // external linkage, the type of the identifier at the later
4719 // declaration becomes the composite type.
4720 //
4721 // If the variable isn't visible, we do not merge with its type.
4722 if (Previous.isShadowed())
4723 return false;
4724
4725 if (S.getLangOpts().CPlusPlus) {
4726 // C++11 [dcl.array]p3:
4727 // If there is a preceding declaration of the entity in the same
4728 // scope in which the bound was specified, an omitted array bound
4729 // is taken to be the same as in that earlier declaration.
4730 return NewVD->isPreviousDeclInSameBlockScope() ||
4731 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4732 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4733 } else {
4734 // If the old declaration was function-local, don't merge with its
4735 // type unless we're in the same function.
4736 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4737 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4738 }
4739}
4740
4741void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4742 // If the new decl is already invalid, don't do any other checking.
4743 if (New->isInvalidDecl())
4744 return;
4745
4746 if (!shouldLinkPossiblyHiddenDecl(Old&: Previous, New))
4747 return;
4748
4749 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4750
4751 // Verify the old decl was also a variable or variable template.
4752 VarDecl *Old = nullptr;
4753 VarTemplateDecl *OldTemplate = nullptr;
4754 if (Previous.isSingleResult()) {
4755 if (NewTemplate) {
4756 OldTemplate = dyn_cast<VarTemplateDecl>(Val: Previous.getFoundDecl());
4757 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4758
4759 if (auto *Shadow =
4760 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4761 if (checkUsingShadowRedecl<VarTemplateDecl>(S&: *this, OldS: Shadow, New: NewTemplate))
4762 return New->setInvalidDecl();
4763 } else {
4764 Old = dyn_cast<VarDecl>(Val: Previous.getFoundDecl());
4765
4766 if (auto *Shadow =
4767 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4768 if (checkUsingShadowRedecl<VarDecl>(S&: *this, OldS: Shadow, New))
4769 return New->setInvalidDecl();
4770 }
4771 }
4772 if (!Old) {
4773 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
4774 << New->getDeclName();
4775 notePreviousDefinition(Old: Previous.getRepresentativeDecl(),
4776 New: New->getLocation());
4777 return New->setInvalidDecl();
4778 }
4779
4780 // If the old declaration was found in an inline namespace and the new
4781 // declaration was qualified, update the DeclContext to match.
4782 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
4783
4784 // Ensure the template parameters are compatible.
4785 if (NewTemplate &&
4786 !TemplateParameterListsAreEqual(New: NewTemplate->getTemplateParameters(),
4787 Old: OldTemplate->getTemplateParameters(),
4788 /*Complain=*/true, Kind: TPL_TemplateMatch))
4789 return New->setInvalidDecl();
4790
4791 // C++ [class.mem]p1:
4792 // A member shall not be declared twice in the member-specification [...]
4793 //
4794 // Here, we need only consider static data members.
4795 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4796 Diag(Loc: New->getLocation(), DiagID: diag::err_duplicate_member)
4797 << New->getIdentifier();
4798 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4799 New->setInvalidDecl();
4800 }
4801
4802 if (NewTemplate && OldTemplate)
4803 mergeDeclAttributes(New: NewTemplate, Old: OldTemplate);
4804
4805 mergeDeclAttributes(New, Old);
4806
4807 // Warn if an already-defined variable is made a weak_import in a subsequent
4808 // declaration
4809 if (New->hasAttr<WeakImportAttr>())
4810 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4811 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4812 Diag(Loc: New->getLocation(), DiagID: diag::warn_weak_import) << New->getDeclName();
4813 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
4814 // Remove weak_import attribute on new declaration.
4815 New->dropAttr<WeakImportAttr>();
4816 break;
4817 }
4818 }
4819
4820 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4821 if (!Old->hasAttr<InternalLinkageAttr>()) {
4822 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4823 << ILA;
4824 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4825 New->dropAttr<InternalLinkageAttr>();
4826 }
4827
4828 // Merge the types.
4829 VarDecl *MostRecent = Old->getMostRecentDecl();
4830 if (MostRecent != Old) {
4831 MergeVarDeclTypes(New, Old: MostRecent,
4832 MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: MostRecent, Previous));
4833 if (New->isInvalidDecl())
4834 return;
4835 }
4836
4837 MergeVarDeclTypes(New, Old, MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: Old, Previous));
4838 if (New->isInvalidDecl())
4839 return;
4840
4841 diag::kind PrevDiag;
4842 SourceLocation OldLocation;
4843 std::tie(args&: PrevDiag, args&: OldLocation) =
4844 getNoteDiagForInvalidRedeclaration(Old, New);
4845
4846 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4847 if (New->getStorageClass() == SC_Static &&
4848 !New->isStaticDataMember() &&
4849 Old->hasExternalFormalLinkage()) {
4850 if (getLangOpts().MicrosoftExt) {
4851 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static)
4852 << New->getDeclName();
4853 Diag(Loc: OldLocation, DiagID: PrevDiag);
4854 } else {
4855 // This is the same internal/external linkage conflict as C2y 6.7.1p7;
4856 // before C2y it was undefined behavior (C11 6.2.2p7), so note that in
4857 // the older C language modes.
4858 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static)
4859 << New->getDeclName()
4860 << (!getLangOpts().CPlusPlus && !getLangOpts().C2y);
4861 Diag(Loc: OldLocation, DiagID: PrevDiag);
4862 return New->setInvalidDecl();
4863 }
4864 }
4865
4866 // C2y 6.7.1p7: an identifier shall not appear with both internal and
4867 // external linkage within a translation unit. Before C2y this was UB
4868 // (C11 6.2.2p7).
4869 //
4870 // In C, a local shadow prevents a block-scope extern from inheriting the
4871 // file-scope static's internal linkage (C2y 6.2.2p6), so it defaults to
4872 // external linkage, creating the conflict.
4873 //
4874 // In C++, block-scope extern declarations target the enclosing namespace
4875 // scope ([dcl.meaning.general]/3.5), bypassing local shadows entirely, so
4876 // the extern always inherits internal linkage. No conflict arises.
4877 if (!getLangOpts().CPlusPlus && New->isLocalVarDecl() &&
4878 New->hasExternalStorage() && Previous.isShadowed() &&
4879 Old->getFormalLinkage() == Linkage::Internal) {
4880 Diag(Loc: New->getLocation(), DiagID: diag::err_internal_extern_mismatch)
4881 << New->getDeclName() << getLangOpts().C2y;
4882 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
4883 return New->setInvalidDecl();
4884 }
4885
4886 // C99 6.2.2p4:
4887 // For an identifier declared with the storage-class specifier
4888 // extern in a scope in which a prior declaration of that
4889 // identifier is visible,23) if the prior declaration specifies
4890 // internal or external linkage, the linkage of the identifier at
4891 // the later declaration is the same as the linkage specified at
4892 // the prior declaration. If no prior declaration is visible, or
4893 // if the prior declaration specifies no linkage, then the
4894 // identifier has external linkage.
4895 if (New->hasExternalStorage() && Old->hasLinkage())
4896 /* Okay */;
4897 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4898 !New->isStaticDataMember() &&
4899 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4900 Diag(Loc: New->getLocation(), DiagID: diag::err_non_static_static) << New->getDeclName();
4901 Diag(Loc: OldLocation, DiagID: PrevDiag);
4902 return New->setInvalidDecl();
4903 }
4904
4905 // Check if extern is followed by non-extern and vice-versa.
4906 if (New->hasExternalStorage() &&
4907 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4908 Diag(Loc: New->getLocation(), DiagID: diag::err_extern_non_extern) << New->getDeclName();
4909 Diag(Loc: OldLocation, DiagID: PrevDiag);
4910 return New->setInvalidDecl();
4911 }
4912 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4913 !New->hasExternalStorage()) {
4914 Diag(Loc: New->getLocation(), DiagID: diag::err_non_extern_extern) << New->getDeclName();
4915 Diag(Loc: OldLocation, DiagID: PrevDiag);
4916 return New->setInvalidDecl();
4917 }
4918
4919 if (CheckRedeclarationInModule(New, Old))
4920 return;
4921
4922 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4923
4924 // FIXME: The test for external storage here seems wrong? We still
4925 // need to check for mismatches.
4926 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4927 // Don't complain about out-of-line definitions of static members.
4928 !(Old->getLexicalDeclContext()->isRecord() &&
4929 !New->getLexicalDeclContext()->isRecord())) {
4930 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New->getDeclName();
4931 Diag(Loc: OldLocation, DiagID: PrevDiag);
4932 return New->setInvalidDecl();
4933 }
4934
4935 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4936 if (VarDecl *Def = Old->getDefinition()) {
4937 // C++1z [dcl.fcn.spec]p4:
4938 // If the definition of a variable appears in a translation unit before
4939 // its first declaration as inline, the program is ill-formed.
4940 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
4941 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
4942 }
4943 }
4944
4945 // If this redeclaration makes the variable inline, we may need to add it to
4946 // UndefinedButUsed.
4947 if (!Old->isInline() && New->isInline() && Old->isUsed(CheckUsedAttr: false) &&
4948 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4949 !Old->isInAnotherModuleUnit())
4950 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4951 y: SourceLocation()));
4952
4953 if (New->getTLSKind() != Old->getTLSKind()) {
4954 if (!Old->getTLSKind()) {
4955 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_non_thread) << New->getDeclName();
4956 Diag(Loc: OldLocation, DiagID: PrevDiag);
4957 } else if (!New->getTLSKind()) {
4958 Diag(Loc: New->getLocation(), DiagID: diag::err_non_thread_thread) << New->getDeclName();
4959 Diag(Loc: OldLocation, DiagID: PrevDiag);
4960 } else {
4961 // Do not allow redeclaration to change the variable between requiring
4962 // static and dynamic initialization.
4963 // FIXME: GCC allows this, but uses the TLS keyword on the first
4964 // declaration to determine the kind. Do we need to be compatible here?
4965 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_thread_different_kind)
4966 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4967 Diag(Loc: OldLocation, DiagID: PrevDiag);
4968 }
4969 }
4970
4971 // C++ doesn't have tentative definitions, so go right ahead and check here.
4972 if (getLangOpts().CPlusPlus) {
4973 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4974 Old->getCanonicalDecl()->isConstexpr()) {
4975 // This definition won't be a definition any more once it's been merged.
4976 Diag(Loc: New->getLocation(),
4977 DiagID: diag::warn_deprecated_redundant_constexpr_static_def);
4978 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4979 VarDecl *Def = Old->getDefinition();
4980 if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New))
4981 return;
4982 if (Old->isInvalidDecl())
4983 New->setInvalidDecl();
4984 }
4985 } else {
4986 // C++ may not have a tentative definition rule, but it has a different
4987 // rule about what constitutes a definition in the first place. See
4988 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4989 // contains the extern specifier and doesn't have an initializer, it's fine
4990 // in C++.
4991 if (New->getTLSKind() != VarDecl::TLS_None &&
4992 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4993 VarDecl *Def = Old->getDefinition();
4994 if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New)) {
4995 return;
4996 }
4997 } else if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4998 Diag(Loc: New->getLocation(), DiagID: diag::warn_cxx_compat_tentative_definition)
4999 << New;
5000 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
5001 }
5002 }
5003
5004 if (haveIncompatibleLanguageLinkages(Old, New)) {
5005 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
5006 Diag(Loc: OldLocation, DiagID: PrevDiag);
5007 New->setInvalidDecl();
5008 return;
5009 }
5010
5011 // Merge "used" flag.
5012 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
5013 New->setIsUsed();
5014
5015 // Keep a chain of previous declarations.
5016 New->setPreviousDecl(Old);
5017 if (NewTemplate)
5018 NewTemplate->setPreviousDecl(OldTemplate);
5019
5020 // Inherit access appropriately.
5021 New->setAccess(Old->getAccess());
5022 if (NewTemplate)
5023 NewTemplate->setAccess(New->getAccess());
5024
5025 if (Old->isInline())
5026 New->setImplicitlyInline();
5027}
5028
5029void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
5030 SourceManager &SrcMgr = getSourceManager();
5031 auto FNewDecLoc = SrcMgr.getDecomposedLoc(Loc: New);
5032 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Loc: Old->getLocation());
5033 auto *FNew = SrcMgr.getFileEntryForID(FID: FNewDecLoc.first);
5034 auto FOld = SrcMgr.getFileEntryRefForID(FID: FOldDecLoc.first);
5035 auto &HSI = PP.getHeaderSearchInfo();
5036 StringRef HdrFilename =
5037 SrcMgr.getFilename(SpellingLoc: SrcMgr.getSpellingLoc(Loc: Old->getLocation()));
5038
5039 auto noteFromModuleOrInclude = [&](Module *Mod,
5040 SourceLocation IncLoc) -> bool {
5041 // Redefinition errors with modules are common with non modular mapped
5042 // headers, example: a non-modular header H in module A that also gets
5043 // included directly in a TU. Pointing twice to the same header/definition
5044 // is confusing, try to get better diagnostics when modules is on.
5045 if (IncLoc.isValid()) {
5046 if (Mod) {
5047 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_modules_same_file)
5048 << HdrFilename.str() << Mod->getFullModuleName();
5049 if (!Mod->DefinitionLoc.isInvalid())
5050 Diag(Loc: Mod->DefinitionLoc, DiagID: diag::note_defined_here)
5051 << Mod->getFullModuleName();
5052 } else {
5053 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_include_same_file)
5054 << HdrFilename.str();
5055 }
5056 return true;
5057 }
5058
5059 return false;
5060 };
5061
5062 // Is it the same file and same offset? Provide more information on why
5063 // this leads to a redefinition error.
5064 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
5065 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FID: FOldDecLoc.first);
5066 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FID: FNewDecLoc.first);
5067 bool EmittedDiag =
5068 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
5069 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
5070
5071 // If the header has no guards, emit a note suggesting one.
5072 if (FOld && !HSI.isFileMultipleIncludeGuarded(File: *FOld))
5073 Diag(Loc: Old->getLocation(), DiagID: diag::note_use_ifdef_guards);
5074
5075 if (EmittedDiag)
5076 return;
5077 }
5078
5079 // Redefinition coming from different files or couldn't do better above.
5080 if (Old->getLocation().isValid())
5081 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
5082}
5083
5084bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
5085 if ((!hasVisibleDefinition(D: Old) ||
5086 isFromSameSingleIncludeHeader(PrevD: Old, NewLoc: New->getLocation())) &&
5087 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
5088 isa<VarTemplateSpecializationDecl>(Val: New) ||
5089 New->getDescribedVarTemplate() ||
5090 !New->getTemplateParameterLists().empty() ||
5091 New->getDeclContext()->isDependentContext() ||
5092 New->hasAttr<SelectAnyAttr>())) {
5093 // The previous definition is hidden, and multiple definitions are
5094 // permitted (in separate TUs). Demote this to a declaration.
5095 New->demoteThisDefinitionToDeclaration();
5096
5097 // Make the canonical definition visible.
5098 if (auto *OldTD = Old->getDescribedVarTemplate())
5099 makeMergedDefinitionVisible(ND: OldTD);
5100 makeMergedDefinitionVisible(ND: Old);
5101 return false;
5102 } else {
5103 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New;
5104 notePreviousDefinition(Old, New: New->getLocation());
5105 New->setInvalidDecl();
5106 return true;
5107 }
5108}
5109
5110Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5111 DeclSpec &DS,
5112 const ParsedAttributesView &DeclAttrs,
5113 RecordDecl *&AnonRecord) {
5114 return ParsedFreeStandingDeclSpec(
5115 S, AS, DS, DeclAttrs, TemplateParams: MultiTemplateParamsArg(), IsExplicitInstantiation: false, AnonRecord);
5116}
5117
5118// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5119// disambiguate entities defined in different scopes.
5120// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5121// compatibility.
5122// We will pick our mangling number depending on which version of MSVC is being
5123// targeted.
5124static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5125 return LO.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015)
5126 ? S->getMSCurManglingNumber()
5127 : S->getMSLastManglingNumber();
5128}
5129
5130void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5131 if (!Context.getLangOpts().CPlusPlus)
5132 return;
5133
5134 if (isa<CXXRecordDecl>(Val: Tag->getParent())) {
5135 // If this tag is the direct child of a class, number it if
5136 // it is anonymous.
5137 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5138 return;
5139 MangleNumberingContext &MCtx =
5140 Context.getManglingNumberContext(DC: Tag->getParent());
5141 Context.setManglingNumber(
5142 ND: Tag, Number: MCtx.getManglingNumber(
5143 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5144 return;
5145 }
5146
5147 // If this tag isn't a direct child of a class, number it if it is local.
5148 MangleNumberingContext *MCtx;
5149 Decl *ManglingContextDecl;
5150 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5151 getCurrentMangleNumberContext(DC: Tag->getDeclContext());
5152 if (MCtx) {
5153 Context.setManglingNumber(
5154 ND: Tag, Number: MCtx->getManglingNumber(
5155 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5156 }
5157}
5158
5159namespace {
5160struct NonCLikeKind {
5161 enum {
5162 None,
5163 BaseClass,
5164 DefaultMemberInit,
5165 Lambda,
5166 Friend,
5167 OtherMember,
5168 Invalid,
5169 } Kind = None;
5170 SourceRange Range;
5171
5172 explicit operator bool() { return Kind != None; }
5173};
5174}
5175
5176/// Determine whether a class is C-like, according to the rules of C++
5177/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5178static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5179 if (RD->isInvalidDecl())
5180 return {.Kind: NonCLikeKind::Invalid, .Range: {}};
5181
5182 // C++ [dcl.typedef]p9: [P1766R1]
5183 // An unnamed class with a typedef name for linkage purposes shall not
5184 //
5185 // -- have any base classes
5186 if (RD->getNumBases())
5187 return {.Kind: NonCLikeKind::BaseClass,
5188 .Range: SourceRange(RD->bases_begin()->getBeginLoc(),
5189 RD->bases_end()[-1].getEndLoc())};
5190 bool Invalid = false;
5191 for (Decl *D : RD->decls()) {
5192 // Don't complain about things we already diagnosed.
5193 if (D->isInvalidDecl()) {
5194 Invalid = true;
5195 continue;
5196 }
5197
5198 // -- have any [...] default member initializers
5199 if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
5200 if (FD->hasInClassInitializer()) {
5201 auto *Init = FD->getInClassInitializer();
5202 return {.Kind: NonCLikeKind::DefaultMemberInit,
5203 .Range: Init ? Init->getSourceRange() : D->getSourceRange()};
5204 }
5205 continue;
5206 }
5207
5208 // FIXME: We don't allow friend declarations. This violates the wording of
5209 // P1766, but not the intent.
5210 if (isa<FriendDecl>(Val: D))
5211 return {.Kind: NonCLikeKind::Friend, .Range: D->getSourceRange()};
5212
5213 // -- declare any members other than non-static data members, member
5214 // enumerations, or member classes,
5215 if (isa<StaticAssertDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D) ||
5216 isa<EnumDecl>(Val: D))
5217 continue;
5218 auto *MemberRD = dyn_cast<CXXRecordDecl>(Val: D);
5219 if (!MemberRD) {
5220 if (D->isImplicit())
5221 continue;
5222 return {.Kind: NonCLikeKind::OtherMember, .Range: D->getSourceRange()};
5223 }
5224
5225 // -- contain a lambda-expression,
5226 if (MemberRD->isLambda())
5227 return {.Kind: NonCLikeKind::Lambda, .Range: MemberRD->getSourceRange()};
5228
5229 // and all member classes shall also satisfy these requirements
5230 // (recursively).
5231 if (MemberRD->isThisDeclarationADefinition()) {
5232 if (auto Kind = getNonCLikeKindForAnonymousStruct(RD: MemberRD))
5233 return Kind;
5234 }
5235 }
5236
5237 return {.Kind: Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, .Range: {}};
5238}
5239
5240void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5241 TypedefNameDecl *NewTD) {
5242 if (TagFromDeclSpec->isInvalidDecl())
5243 return;
5244
5245 // Do nothing if the tag already has a name for linkage purposes.
5246 if (TagFromDeclSpec->hasNameForLinkage())
5247 return;
5248
5249 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5250 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5251
5252 // The type must match the tag exactly; no qualifiers allowed.
5253 if (!Context.hasSameType(T1: NewTD->getUnderlyingType(),
5254 T2: Context.getCanonicalTagType(TD: TagFromDeclSpec))) {
5255 if (getLangOpts().CPlusPlus)
5256 Context.addTypedefNameForUnnamedTagDecl(TD: TagFromDeclSpec, TND: NewTD);
5257 return;
5258 }
5259
5260 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5261 // An unnamed class with a typedef name for linkage purposes shall [be
5262 // C-like].
5263 //
5264 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5265 // shouldn't happen, but there are constructs that the language rule doesn't
5266 // disallow for which we can't reasonably avoid computing linkage early.
5267 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TagFromDeclSpec);
5268 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5269 : NonCLikeKind();
5270 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5271 if (NonCLike || ChangesLinkage) {
5272 if (NonCLike.Kind == NonCLikeKind::Invalid)
5273 return;
5274
5275 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5276 if (ChangesLinkage) {
5277 // If the linkage changes, we can't accept this as an extension.
5278 if (NonCLike.Kind == NonCLikeKind::None)
5279 DiagID = diag::err_typedef_changes_linkage;
5280 else
5281 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5282 }
5283
5284 SourceLocation FixitLoc =
5285 getLocForEndOfToken(Loc: TagFromDeclSpec->getInnerLocStart());
5286 llvm::SmallString<40> TextToInsert;
5287 TextToInsert += ' ';
5288 TextToInsert += NewTD->getIdentifier()->getName();
5289
5290 Diag(Loc: FixitLoc, DiagID)
5291 << isa<TypeAliasDecl>(Val: NewTD)
5292 << FixItHint::CreateInsertion(InsertionLoc: FixitLoc, Code: TextToInsert);
5293 if (NonCLike.Kind != NonCLikeKind::None) {
5294 Diag(Loc: NonCLike.Range.getBegin(), DiagID: diag::note_non_c_like_anon_struct)
5295 << NonCLike.Kind - 1 << NonCLike.Range;
5296 }
5297 Diag(Loc: NewTD->getLocation(), DiagID: diag::note_typedef_for_linkage_here)
5298 << NewTD << isa<TypeAliasDecl>(Val: NewTD);
5299
5300 if (ChangesLinkage)
5301 return;
5302 }
5303
5304 // Otherwise, set this as the anon-decl typedef for the tag.
5305 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5306
5307 // Now that we have a name for the tag, process API notes again.
5308 ProcessAPINotes(D: TagFromDeclSpec);
5309}
5310
5311static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5312 DeclSpec::TST T = DS.getTypeSpecType();
5313 switch (T) {
5314 case DeclSpec::TST_class:
5315 return 0;
5316 case DeclSpec::TST_struct:
5317 return 1;
5318 case DeclSpec::TST_interface:
5319 return 2;
5320 case DeclSpec::TST_union:
5321 return 3;
5322 case DeclSpec::TST_enum:
5323 if (const auto *ED = dyn_cast<EnumDecl>(Val: DS.getRepAsDecl())) {
5324 if (ED->isScopedUsingClassTag())
5325 return 5;
5326 if (ED->isScoped())
5327 return 6;
5328 }
5329 return 4;
5330 default:
5331 llvm_unreachable("unexpected type specifier");
5332 }
5333}
5334
5335Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5336 DeclSpec &DS,
5337 const ParsedAttributesView &DeclAttrs,
5338 MultiTemplateParamsArg TemplateParams,
5339 bool IsExplicitInstantiation,
5340 RecordDecl *&AnonRecord,
5341 SourceLocation EllipsisLoc) {
5342 Decl *TagD = nullptr;
5343 TagDecl *Tag = nullptr;
5344 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5345 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5346 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5347 DS.getTypeSpecType() == DeclSpec::TST_union ||
5348 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5349 TagD = DS.getRepAsDecl();
5350
5351 if (!TagD) // We probably had an error
5352 return nullptr;
5353
5354 // Note that the above type specs guarantee that the
5355 // type rep is a Decl, whereas in many of the others
5356 // it's a Type.
5357 if (isa<TagDecl>(Val: TagD))
5358 Tag = cast<TagDecl>(Val: TagD);
5359 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: TagD))
5360 Tag = CTD->getTemplatedDecl();
5361 }
5362
5363 if (Tag) {
5364 handleTagNumbering(Tag, TagScope: S);
5365 Tag->setFreeStanding();
5366 if (Tag->isInvalidDecl())
5367 return Tag;
5368 }
5369
5370 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5371 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5372 // or incomplete types shall not be restrict-qualified."
5373 if (TypeQuals & DeclSpec::TQ_restrict)
5374 Diag(Loc: DS.getRestrictSpecLoc(),
5375 DiagID: diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5376 << DS.getSourceRange();
5377 }
5378
5379 if (DS.isInlineSpecified())
5380 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
5381 << getLangOpts().CPlusPlus17;
5382
5383 if (DS.hasConstexprSpecifier()) {
5384 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5385 // and definitions of functions and variables.
5386 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5387 // the declaration of a function or function template
5388 if (Tag)
5389 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_tag)
5390 << GetDiagnosticTypeSpecifierID(DS)
5391 << static_cast<int>(DS.getConstexprSpecifier());
5392 else if (getLangOpts().C23)
5393 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_c23_constexpr_not_variable);
5394 else
5395 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_wrong_decl_kind)
5396 << static_cast<int>(DS.getConstexprSpecifier());
5397 // Don't emit warnings after this error.
5398 return TagD;
5399 }
5400
5401 DiagnoseFunctionSpecifiers(DS);
5402
5403 if (DS.isFriendSpecified()) {
5404 // If we're dealing with a decl but not a TagDecl, assume that
5405 // whatever routines created it handled the friendship aspect.
5406 if (TagD && !Tag)
5407 return nullptr;
5408 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5409 }
5410
5411 assert(EllipsisLoc.isInvalid() &&
5412 "Friend ellipsis but not friend-specified?");
5413
5414 // Track whether this decl-specifier declares anything.
5415 bool DeclaresAnything = true;
5416
5417 // Handle anonymous struct definitions.
5418 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Val: Tag)) {
5419 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5420 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5421 if (getLangOpts().CPlusPlus ||
5422 Record->getDeclContext()->isRecord()) {
5423 // If CurContext is a DeclContext that can contain statements,
5424 // RecursiveASTVisitor won't visit the decls that
5425 // BuildAnonymousStructOrUnion() will put into CurContext.
5426 // Also store them here so that they can be part of the
5427 // DeclStmt that gets created in this case.
5428 // FIXME: Also return the IndirectFieldDecls created by
5429 // BuildAnonymousStructOr union, for the same reason?
5430 if (CurContext->isFunctionOrMethod())
5431 AnonRecord = Record;
5432 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5433 Policy: Context.getPrintingPolicy());
5434 }
5435
5436 DeclaresAnything = false;
5437 }
5438 }
5439
5440 // C11 6.7.2.1p2:
5441 // A struct-declaration that does not declare an anonymous structure or
5442 // anonymous union shall contain a struct-declarator-list.
5443 //
5444 // This rule also existed in C89 and C99; the grammar for struct-declaration
5445 // did not permit a struct-declaration without a struct-declarator-list.
5446 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5447 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5448 // Check for Microsoft C extension: anonymous struct/union member.
5449 // Handle 2 kinds of anonymous struct/union:
5450 // struct STRUCT;
5451 // union UNION;
5452 // and
5453 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5454 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5455 if ((Tag && Tag->getDeclName()) ||
5456 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5457 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Val: Tag)
5458 : DS.getRepAsType().get()->getAsRecordDecl();
5459 if (Record && getLangOpts().MSAnonymousStructs) {
5460 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_ms_anonymous_record)
5461 << Record->isUnion() << DS.getSourceRange();
5462 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5463 }
5464
5465 DeclaresAnything = false;
5466 }
5467 }
5468
5469 // Skip all the checks below if we have a type error.
5470 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5471 (TagD && TagD->isInvalidDecl()))
5472 return TagD;
5473
5474 if (getLangOpts().CPlusPlus &&
5475 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5476 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Val: Tag))
5477 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5478 !Enum->isInvalidDecl())
5479 DeclaresAnything = false;
5480
5481 if (!DS.isMissingDeclaratorOk()) {
5482 // Customize diagnostic for a typedef missing a name.
5483 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5484 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_typedef_without_a_name)
5485 << DS.getSourceRange();
5486 else
5487 DeclaresAnything = false;
5488 }
5489
5490 if (DS.isModulePrivateSpecified() &&
5491 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5492 Diag(Loc: DS.getModulePrivateSpecLoc(), DiagID: diag::err_module_private_local_class)
5493 << Tag->getTagKind()
5494 << FixItHint::CreateRemoval(RemoveRange: DS.getModulePrivateSpecLoc());
5495
5496 ActOnDocumentableDecl(D: TagD);
5497
5498 // C 6.7/2:
5499 // A declaration [...] shall declare at least a declarator [...], a tag,
5500 // or the members of an enumeration.
5501 // C++ [dcl.dcl]p3:
5502 // [If there are no declarators], and except for the declaration of an
5503 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5504 // names into the program, or shall redeclare a name introduced by a
5505 // previous declaration.
5506 if (!DeclaresAnything) {
5507 // In C, we allow this as a (popular) extension / bug. Don't bother
5508 // producing further diagnostics for redundant qualifiers after this.
5509 Diag(Loc: DS.getBeginLoc(), DiagID: (IsExplicitInstantiation || !TemplateParams.empty())
5510 ? diag::err_no_declarators
5511 : diag::ext_no_declarators)
5512 << DS.getSourceRange();
5513 return TagD;
5514 }
5515
5516 // C++ [dcl.stc]p1:
5517 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5518 // init-declarator-list of the declaration shall not be empty.
5519 // C++ [dcl.fct.spec]p1:
5520 // If a cv-qualifier appears in a decl-specifier-seq, the
5521 // init-declarator-list of the declaration shall not be empty.
5522 //
5523 // Spurious qualifiers here appear to be valid in C.
5524 unsigned DiagID = diag::warn_standalone_specifier;
5525 if (getLangOpts().CPlusPlus)
5526 DiagID = diag::ext_standalone_specifier;
5527
5528 // Note that a linkage-specification sets a storage class, but
5529 // 'extern "C" struct foo;' is actually valid and not theoretically
5530 // useless.
5531 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5532 if (SCS == DeclSpec::SCS_mutable)
5533 // Since mutable is not a viable storage class specifier in C, there is
5534 // no reason to treat it as an extension. Instead, diagnose as an error.
5535 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_nonmember);
5536 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5537 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID)
5538 << DeclSpec::getSpecifierName(S: SCS);
5539 }
5540
5541 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5542 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID)
5543 << DeclSpec::getSpecifierName(S: TSCS);
5544 if (DS.getTypeQualifiers()) {
5545 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5546 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "const";
5547 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5548 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "volatile";
5549 // Restrict is covered above.
5550 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5551 Diag(Loc: DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5552 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5553 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5554 }
5555
5556 // Warn about ignored type attributes, for example:
5557 // __attribute__((aligned)) struct A;
5558 // Attributes should be placed after tag to apply to type declaration.
5559 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5560 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5561 if (TypeSpecType == DeclSpec::TST_class ||
5562 TypeSpecType == DeclSpec::TST_struct ||
5563 TypeSpecType == DeclSpec::TST_interface ||
5564 TypeSpecType == DeclSpec::TST_union ||
5565 TypeSpecType == DeclSpec::TST_enum) {
5566
5567 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5568 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5569 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5570 DiagnosticId = diag::warn_attribute_ignored;
5571 else if (AL.isRegularKeywordAttribute())
5572 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5573 else
5574 DiagnosticId = diag::warn_declspec_attribute_ignored;
5575 Diag(Loc: AL.getLoc(), DiagID: DiagnosticId)
5576 << AL << GetDiagnosticTypeSpecifierID(DS);
5577 };
5578
5579 llvm::for_each(Range&: DS.getAttributes(), F: EmitAttributeDiagnostic);
5580 llvm::for_each(Range: DeclAttrs, F: EmitAttributeDiagnostic);
5581 }
5582 }
5583
5584 return TagD;
5585}
5586
5587/// We are trying to inject an anonymous member into the given scope;
5588/// check if there's an existing declaration that can't be overloaded.
5589///
5590/// \return true if this is a forbidden redeclaration
5591static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5592 DeclContext *Owner,
5593 DeclarationName Name,
5594 SourceLocation NameLoc, bool IsUnion,
5595 StorageClass SC) {
5596 LookupResult R(SemaRef, Name, NameLoc,
5597 Owner->isRecord() ? Sema::LookupMemberName
5598 : Sema::LookupOrdinaryName,
5599 RedeclarationKind::ForVisibleRedeclaration);
5600 if (!SemaRef.LookupName(R, S)) return false;
5601
5602 // Pick a representative declaration.
5603 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5604 assert(PrevDecl && "Expected a non-null Decl");
5605
5606 if (!SemaRef.isDeclInScope(D: PrevDecl, Ctx: Owner, S))
5607 return false;
5608
5609 if (SC == StorageClass::SC_None &&
5610 PrevDecl->isPlaceholderVar(LangOpts: SemaRef.getLangOpts()) &&
5611 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5612 if (!Owner->isRecord())
5613 SemaRef.DiagPlaceholderVariableDefinition(Loc: NameLoc);
5614 return false;
5615 }
5616
5617 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_anonymous_record_member_redecl)
5618 << IsUnion << Name;
5619 SemaRef.Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
5620
5621 return true;
5622}
5623
5624void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5625 if (auto *RD = dyn_cast_if_present<RecordDecl>(Val: D))
5626 DiagPlaceholderFieldDeclDefinitions(Record: RD);
5627}
5628
5629void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5630 if (!getLangOpts().CPlusPlus)
5631 return;
5632
5633 // This function can be parsed before we have validated the
5634 // structure as an anonymous struct
5635 if (Record->isAnonymousStructOrUnion())
5636 return;
5637
5638 const NamedDecl *First = 0;
5639 for (const Decl *D : Record->decls()) {
5640 const NamedDecl *ND = dyn_cast<NamedDecl>(Val: D);
5641 if (!ND || !ND->isPlaceholderVar(LangOpts: getLangOpts()))
5642 continue;
5643 if (!First)
5644 First = ND;
5645 else
5646 DiagPlaceholderVariableDefinition(Loc: ND->getLocation());
5647 }
5648}
5649
5650/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5651/// anonymous struct or union AnonRecord into the owning context Owner
5652/// and scope S. This routine will be invoked just after we realize
5653/// that an unnamed union or struct is actually an anonymous union or
5654/// struct, e.g.,
5655///
5656/// @code
5657/// union {
5658/// int i;
5659/// float f;
5660/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5661/// // f into the surrounding scope.x
5662/// @endcode
5663///
5664/// This routine is recursive, injecting the names of nested anonymous
5665/// structs/unions into the owning context and scope as well.
5666static bool
5667InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5668 RecordDecl *AnonRecord, AccessSpecifier AS,
5669 StorageClass SC,
5670 SmallVectorImpl<NamedDecl *> &Chaining) {
5671 bool Invalid = false;
5672
5673 // Look every FieldDecl and IndirectFieldDecl with a name.
5674 for (auto *D : AnonRecord->decls()) {
5675 if ((isa<FieldDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D)) &&
5676 cast<NamedDecl>(Val: D)->getDeclName()) {
5677 ValueDecl *VD = cast<ValueDecl>(Val: D);
5678 // C++ [class.union]p2:
5679 // The names of the members of an anonymous union shall be
5680 // distinct from the names of any other entity in the
5681 // scope in which the anonymous union is declared.
5682
5683 bool FieldInvalid = CheckAnonMemberRedeclaration(
5684 SemaRef, S, Owner, Name: VD->getDeclName(), NameLoc: VD->getLocation(),
5685 IsUnion: AnonRecord->isUnion(), SC);
5686 if (FieldInvalid)
5687 Invalid = true;
5688
5689 // Inject the IndirectFieldDecl even if invalid, because later
5690 // diagnostics may depend on it being present, see findDefaultInitializer.
5691
5692 // C++ [class.union]p2:
5693 // For the purpose of name lookup, after the anonymous union
5694 // definition, the members of the anonymous union are
5695 // considered to have been defined in the scope in which the
5696 // anonymous union is declared.
5697 unsigned OldChainingSize = Chaining.size();
5698 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(Val: VD))
5699 Chaining.append(in_start: IF->chain_begin(), in_end: IF->chain_end());
5700 else
5701 Chaining.push_back(Elt: VD);
5702
5703 assert(Chaining.size() >= 2);
5704 NamedDecl **NamedChain =
5705 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5706 for (unsigned i = 0; i < Chaining.size(); i++)
5707 NamedChain[i] = Chaining[i];
5708
5709 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5710 C&: SemaRef.Context, DC: Owner, L: VD->getLocation(), Id: VD->getIdentifier(),
5711 T: VD->getType(), CH: {NamedChain, Chaining.size()});
5712
5713 for (const auto *Attr : VD->attrs())
5714 IndirectField->addAttr(A: Attr->clone(C&: SemaRef.Context));
5715
5716 IndirectField->setAccess(AS);
5717 IndirectField->setImplicit();
5718 IndirectField->setInvalidDecl(FieldInvalid);
5719 SemaRef.PushOnScopeChains(D: IndirectField, S);
5720
5721 // That includes picking up the appropriate access specifier.
5722 if (AS != AS_none)
5723 IndirectField->setAccess(AS);
5724
5725 Chaining.resize(N: OldChainingSize);
5726 }
5727 }
5728
5729 return Invalid;
5730}
5731
5732/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5733/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5734/// illegal input values are mapped to SC_None.
5735static StorageClass
5736StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5737 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5738 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5739 "Parser allowed 'typedef' as storage class VarDecl.");
5740 switch (StorageClassSpec) {
5741 case DeclSpec::SCS_unspecified: return SC_None;
5742 case DeclSpec::SCS_extern:
5743 if (DS.isExternInLinkageSpec())
5744 return SC_None;
5745 return SC_Extern;
5746 case DeclSpec::SCS_static: return SC_Static;
5747 case DeclSpec::SCS_auto: return SC_Auto;
5748 case DeclSpec::SCS_register: return SC_Register;
5749 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5750 // Illegal SCSs map to None: error reporting is up to the caller.
5751 case DeclSpec::SCS_mutable: // Fall through.
5752 case DeclSpec::SCS_typedef: return SC_None;
5753 }
5754 llvm_unreachable("unknown storage class specifier");
5755}
5756
5757static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5758 assert(Record->hasInClassInitializer());
5759
5760 for (const auto *I : Record->decls()) {
5761 const auto *FD = dyn_cast<FieldDecl>(Val: I);
5762 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
5763 FD = IFD->getAnonField();
5764 if (FD && FD->hasInClassInitializer())
5765 return FD->getLocation();
5766 }
5767
5768 llvm_unreachable("couldn't find in-class initializer");
5769}
5770
5771static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5772 SourceLocation DefaultInitLoc) {
5773 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5774 return;
5775
5776 S.Diag(Loc: DefaultInitLoc, DiagID: diag::err_multiple_mem_union_initialization);
5777 S.Diag(Loc: findDefaultInitializer(Record: Parent), DiagID: diag::note_previous_initializer) << 0;
5778}
5779
5780static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5781 CXXRecordDecl *AnonUnion) {
5782 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5783 return;
5784
5785 checkDuplicateDefaultInit(S, Parent, DefaultInitLoc: findDefaultInitializer(Record: AnonUnion));
5786}
5787
5788Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5789 AccessSpecifier AS,
5790 RecordDecl *Record,
5791 const PrintingPolicy &Policy) {
5792 DeclContext *Owner = Record->getDeclContext();
5793
5794 // Diagnose whether this anonymous struct/union is an extension.
5795 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5796 Diag(Loc: Record->getLocation(), DiagID: diag::ext_anonymous_union);
5797 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5798 Diag(Loc: Record->getLocation(), DiagID: diag::ext_gnu_anonymous_struct);
5799 else if (!Record->isUnion() && !getLangOpts().C11)
5800 Diag(Loc: Record->getLocation(), DiagID: diag::ext_c11_anonymous_struct);
5801
5802 // C and C++ require different kinds of checks for anonymous
5803 // structs/unions.
5804 bool Invalid = false;
5805 if (getLangOpts().CPlusPlus) {
5806 const char *PrevSpec = nullptr;
5807 if (Record->isUnion()) {
5808 // C++ [class.union]p6:
5809 // C++17 [class.union.anon]p2:
5810 // Anonymous unions declared in a named namespace or in the
5811 // global namespace shall be declared static.
5812 unsigned DiagID;
5813 DeclContext *OwnerScope = Owner->getRedeclContext();
5814 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5815 (OwnerScope->isTranslationUnit() ||
5816 (OwnerScope->isNamespace() &&
5817 !cast<NamespaceDecl>(Val: OwnerScope)->isAnonymousNamespace()))) {
5818 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_union_not_static)
5819 << FixItHint::CreateInsertion(InsertionLoc: Record->getLocation(), Code: "static ");
5820
5821 // Recover by adding 'static'.
5822 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_static, Loc: SourceLocation(),
5823 PrevSpec, DiagID, Policy);
5824 }
5825 // C++ [class.union]p6:
5826 // A storage class is not allowed in a declaration of an
5827 // anonymous union in a class scope.
5828 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5829 isa<RecordDecl>(Val: Owner)) {
5830 Diag(Loc: DS.getStorageClassSpecLoc(),
5831 DiagID: diag::err_anonymous_union_with_storage_spec)
5832 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
5833
5834 // Recover by removing the storage specifier.
5835 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_unspecified,
5836 Loc: SourceLocation(),
5837 PrevSpec, DiagID, Policy: Context.getPrintingPolicy());
5838 }
5839 }
5840
5841 // Ignore const/volatile/restrict qualifiers.
5842 if (DS.getTypeQualifiers()) {
5843 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5844 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::ext_anonymous_struct_union_qualified)
5845 << Record->isUnion() << "const"
5846 << FixItHint::CreateRemoval(RemoveRange: DS.getConstSpecLoc());
5847 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5848 Diag(Loc: DS.getVolatileSpecLoc(),
5849 DiagID: diag::ext_anonymous_struct_union_qualified)
5850 << Record->isUnion() << "volatile"
5851 << FixItHint::CreateRemoval(RemoveRange: DS.getVolatileSpecLoc());
5852 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5853 Diag(Loc: DS.getRestrictSpecLoc(),
5854 DiagID: diag::ext_anonymous_struct_union_qualified)
5855 << Record->isUnion() << "restrict"
5856 << FixItHint::CreateRemoval(RemoveRange: DS.getRestrictSpecLoc());
5857 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5858 Diag(Loc: DS.getAtomicSpecLoc(),
5859 DiagID: diag::ext_anonymous_struct_union_qualified)
5860 << Record->isUnion() << "_Atomic"
5861 << FixItHint::CreateRemoval(RemoveRange: DS.getAtomicSpecLoc());
5862 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5863 Diag(Loc: DS.getUnalignedSpecLoc(),
5864 DiagID: diag::ext_anonymous_struct_union_qualified)
5865 << Record->isUnion() << "__unaligned"
5866 << FixItHint::CreateRemoval(RemoveRange: DS.getUnalignedSpecLoc());
5867
5868 DS.ClearTypeQualifiers();
5869 }
5870
5871 // C++ [class.union]p2:
5872 // The member-specification of an anonymous union shall only
5873 // define non-static data members. [Note: nested types and
5874 // functions cannot be declared within an anonymous union. ]
5875 for (auto *Mem : Record->decls()) {
5876 // Ignore invalid declarations; we already diagnosed them.
5877 if (Mem->isInvalidDecl())
5878 continue;
5879
5880 if (auto *FD = dyn_cast<FieldDecl>(Val: Mem)) {
5881 // C++ [class.union]p3:
5882 // An anonymous union shall not have private or protected
5883 // members (clause 11).
5884 assert(FD->getAccess() != AS_none);
5885 if (FD->getAccess() != AS_public) {
5886 Diag(Loc: FD->getLocation(), DiagID: diag::err_anonymous_record_nonpublic_member)
5887 << Record->isUnion() << (FD->getAccess() == AS_protected);
5888 Invalid = true;
5889 }
5890
5891 // C++ [class.union]p1
5892 // An object of a class with a non-trivial constructor, a non-trivial
5893 // copy constructor, a non-trivial destructor, or a non-trivial copy
5894 // assignment operator cannot be a member of a union, nor can an
5895 // array of such objects.
5896 if (CheckNontrivialField(FD))
5897 Invalid = true;
5898 } else if (Mem->isImplicit()) {
5899 // Any implicit members are fine.
5900 } else if (isa<TagDecl>(Val: Mem) && Mem->getDeclContext() != Record) {
5901 // This is a type that showed up in an
5902 // elaborated-type-specifier inside the anonymous struct or
5903 // union, but which actually declares a type outside of the
5904 // anonymous struct or union. It's okay.
5905 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Val: Mem)) {
5906 if (!MemRecord->isAnonymousStructOrUnion() &&
5907 MemRecord->getDeclName()) {
5908 // Visual C++ allows type definition in anonymous struct or union.
5909 if (getLangOpts().MicrosoftExt)
5910 Diag(Loc: MemRecord->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5911 << Record->isUnion();
5912 else {
5913 // This is a nested type declaration.
5914 Diag(Loc: MemRecord->getLocation(), DiagID: diag::err_anonymous_record_with_type)
5915 << Record->isUnion();
5916 Invalid = true;
5917 }
5918 } else {
5919 // This is an anonymous type definition within another anonymous type.
5920 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5921 // not part of standard C++.
5922 Diag(Loc: MemRecord->getLocation(),
5923 DiagID: diag::ext_anonymous_record_with_anonymous_type)
5924 << Record->isUnion();
5925 }
5926 } else if (isa<AccessSpecDecl>(Val: Mem)) {
5927 // Any access specifier is fine.
5928 } else if (isa<StaticAssertDecl>(Val: Mem)) {
5929 // In C++1z, static_assert declarations are also fine.
5930 } else {
5931 // We have something that isn't a non-static data
5932 // member. Complain about it.
5933 unsigned DK = diag::err_anonymous_record_bad_member;
5934 if (isa<TypeDecl>(Val: Mem))
5935 DK = diag::err_anonymous_record_with_type;
5936 else if (isa<FunctionDecl>(Val: Mem))
5937 DK = diag::err_anonymous_record_with_function;
5938 else if (isa<VarDecl>(Val: Mem))
5939 DK = diag::err_anonymous_record_with_static;
5940
5941 // Visual C++ allows type definition in anonymous struct or union.
5942 if (getLangOpts().MicrosoftExt &&
5943 DK == diag::err_anonymous_record_with_type)
5944 Diag(Loc: Mem->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5945 << Record->isUnion();
5946 else {
5947 Diag(Loc: Mem->getLocation(), DiagID: DK) << Record->isUnion();
5948 Invalid = true;
5949 }
5950 }
5951 }
5952
5953 // C++11 [class.union]p8 (DR1460):
5954 // At most one variant member of a union may have a
5955 // brace-or-equal-initializer.
5956 if (cast<CXXRecordDecl>(Val: Record)->hasInClassInitializer() &&
5957 Owner->isRecord())
5958 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Owner),
5959 AnonUnion: cast<CXXRecordDecl>(Val: Record));
5960 }
5961
5962 if (!Record->isUnion() && !Owner->isRecord()) {
5963 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_struct_not_member)
5964 << getLangOpts().CPlusPlus;
5965 Invalid = true;
5966 }
5967
5968 // C++ [dcl.dcl]p3:
5969 // [If there are no declarators], and except for the declaration of an
5970 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5971 // names into the program
5972 // C++ [class.mem]p2:
5973 // each such member-declaration shall either declare at least one member
5974 // name of the class or declare at least one unnamed bit-field
5975 //
5976 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5977 if (getLangOpts().CPlusPlus && Record->field_empty())
5978 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_no_declarators) << DS.getSourceRange();
5979
5980 // Mock up a declarator.
5981 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5982 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5983 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5984 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5985
5986 // Create a declaration for this anonymous struct/union.
5987 NamedDecl *Anon = nullptr;
5988 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Val: Owner)) {
5989 Anon = FieldDecl::Create(
5990 C: Context, DC: OwningClass, StartLoc: DS.getBeginLoc(), IdLoc: Record->getLocation(),
5991 /*IdentifierInfo=*/Id: nullptr, T: Context.getCanonicalTagType(TD: Record), TInfo,
5992 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5993 /*InitStyle=*/ICIS_NoInit);
5994 Anon->setAccess(AS);
5995 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5996
5997 if (getLangOpts().CPlusPlus)
5998 FieldCollector->Add(D: cast<FieldDecl>(Val: Anon));
5999 } else {
6000 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
6001 if (SCSpec == DeclSpec::SCS_mutable) {
6002 // mutable can only appear on non-static class members, so it's always
6003 // an error here
6004 Diag(Loc: Record->getLocation(), DiagID: diag::err_mutable_nonmember);
6005 Invalid = true;
6006 SC = SC_None;
6007 }
6008
6009 Anon = VarDecl::Create(C&: Context, DC: Owner, StartLoc: DS.getBeginLoc(),
6010 IdLoc: Record->getLocation(), /*IdentifierInfo=*/Id: nullptr,
6011 T: Context.getCanonicalTagType(TD: Record), TInfo, S: SC);
6012 if (Invalid)
6013 Anon->setInvalidDecl();
6014
6015 ProcessDeclAttributes(S, D: Anon, PD: Dc);
6016
6017 // Default-initialize the implicit variable. This initialization will be
6018 // trivial in almost all cases, except if a union member has an in-class
6019 // initializer:
6020 // union { int n = 0; };
6021 ActOnUninitializedDecl(dcl: Anon);
6022 }
6023 Anon->setImplicit();
6024
6025 // Mark this as an anonymous struct/union type.
6026 Record->setAnonymousStructOrUnion(true);
6027
6028 // Add the anonymous struct/union object to the current
6029 // context. We'll be referencing this object when we refer to one of
6030 // its members.
6031 Owner->addDecl(D: Anon);
6032
6033 // Inject the members of the anonymous struct/union into the owning
6034 // context and into the identifier resolver chain for name lookup
6035 // purposes.
6036 SmallVector<NamedDecl*, 2> Chain;
6037 Chain.push_back(Elt: Anon);
6038
6039 if (InjectAnonymousStructOrUnionMembers(SemaRef&: *this, S, Owner, AnonRecord: Record, AS, SC,
6040 Chaining&: Chain))
6041 Invalid = true;
6042
6043 if (VarDecl *NewVD = dyn_cast<VarDecl>(Val: Anon)) {
6044 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6045 MangleNumberingContext *MCtx;
6046 Decl *ManglingContextDecl;
6047 std::tie(args&: MCtx, args&: ManglingContextDecl) =
6048 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
6049 if (MCtx) {
6050 Context.setManglingNumber(
6051 ND: NewVD, Number: MCtx->getManglingNumber(
6052 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
6053 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
6054 }
6055 }
6056 }
6057
6058 if (Invalid)
6059 Anon->setInvalidDecl();
6060
6061 return Anon;
6062}
6063
6064Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
6065 RecordDecl *Record) {
6066 assert(Record && "expected a record!");
6067
6068 // Mock up a declarator.
6069 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
6070 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
6071 assert(TInfo && "couldn't build declarator info for anonymous struct");
6072
6073 auto *ParentDecl = cast<RecordDecl>(Val: CurContext);
6074 CanQualType RecTy = Context.getCanonicalTagType(TD: Record);
6075
6076 // Create a declaration for this anonymous struct.
6077 NamedDecl *Anon =
6078 FieldDecl::Create(C: Context, DC: ParentDecl, StartLoc: DS.getBeginLoc(), IdLoc: DS.getBeginLoc(),
6079 /*IdentifierInfo=*/Id: nullptr, T: RecTy, TInfo,
6080 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
6081 /*InitStyle=*/ICIS_NoInit);
6082 Anon->setImplicit();
6083
6084 // Add the anonymous struct object to the current context.
6085 CurContext->addDecl(D: Anon);
6086
6087 // Inject the members of the anonymous struct into the current
6088 // context and into the identifier resolver chain for name lookup
6089 // purposes.
6090 SmallVector<NamedDecl*, 2> Chain;
6091 Chain.push_back(Elt: Anon);
6092
6093 RecordDecl *RecordDef = Record->getDefinition();
6094 if (RequireCompleteSizedType(Loc: Anon->getLocation(), T: RecTy,
6095 DiagID: diag::err_field_incomplete_or_sizeless) ||
6096 InjectAnonymousStructOrUnionMembers(
6097 SemaRef&: *this, S, Owner: CurContext, AnonRecord: RecordDef, AS: AS_none,
6098 SC: StorageClassSpecToVarDeclStorageClass(DS), Chaining&: Chain)) {
6099 Anon->setInvalidDecl();
6100 ParentDecl->setInvalidDecl();
6101 }
6102
6103 return Anon;
6104}
6105
6106DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
6107 return GetNameFromUnqualifiedId(Name: D.getName());
6108}
6109
6110DeclarationNameInfo
6111Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
6112 DeclarationNameInfo NameInfo;
6113 NameInfo.setLoc(Name.StartLocation);
6114
6115 switch (Name.getKind()) {
6116
6117 case UnqualifiedIdKind::IK_ImplicitSelfParam:
6118 case UnqualifiedIdKind::IK_Identifier:
6119 NameInfo.setName(Name.Identifier);
6120 return NameInfo;
6121
6122 case UnqualifiedIdKind::IK_DeductionGuideName: {
6123 // C++ [temp.deduct.guide]p3:
6124 // The simple-template-id shall name a class template specialization.
6125 // The template-name shall be the same identifier as the template-name
6126 // of the simple-template-id.
6127 // These together intend to imply that the template-name shall name a
6128 // class template.
6129 // FIXME: template<typename T> struct X {};
6130 // template<typename T> using Y = X<T>;
6131 // Y(int) -> Y<int>;
6132 // satisfies these rules but does not name a class template.
6133 TemplateName TN = Name.TemplateName.get().get();
6134 auto *Template = TN.getAsTemplateDecl();
6135 if (!Template || !isa<ClassTemplateDecl>(Val: Template)) {
6136 Diag(Loc: Name.StartLocation,
6137 DiagID: diag::err_deduction_guide_name_not_class_template)
6138 << (int)getTemplateNameKindForDiagnostics(Name: TN) << TN;
6139 if (Template)
6140 NoteTemplateLocation(Decl: *Template);
6141 return DeclarationNameInfo();
6142 }
6143
6144 NameInfo.setName(
6145 Context.DeclarationNames.getCXXDeductionGuideName(TD: Template));
6146 return NameInfo;
6147 }
6148
6149 case UnqualifiedIdKind::IK_OperatorFunctionId:
6150 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6151 Op: Name.OperatorFunctionId.Operator));
6152 NameInfo.setCXXOperatorNameRange(SourceRange(
6153 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
6154 return NameInfo;
6155
6156 case UnqualifiedIdKind::IK_LiteralOperatorId:
6157 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6158 II: Name.Identifier));
6159 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
6160 return NameInfo;
6161
6162 case UnqualifiedIdKind::IK_ConversionFunctionId: {
6163 TypeSourceInfo *TInfo;
6164 QualType Ty = GetTypeFromParser(Ty: Name.ConversionFunctionId, TInfo: &TInfo);
6165 if (Ty.isNull())
6166 return DeclarationNameInfo();
6167 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6168 Ty: Context.getCanonicalType(T: Ty)));
6169 NameInfo.setNamedTypeInfo(TInfo);
6170 return NameInfo;
6171 }
6172
6173 case UnqualifiedIdKind::IK_ConstructorName: {
6174 TypeSourceInfo *TInfo;
6175 QualType Ty = GetTypeFromParser(Ty: Name.ConstructorName, TInfo: &TInfo);
6176 if (Ty.isNull())
6177 return DeclarationNameInfo();
6178 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6179 Ty: Context.getCanonicalType(T: Ty)));
6180 NameInfo.setNamedTypeInfo(TInfo);
6181 return NameInfo;
6182 }
6183
6184 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
6185 // In well-formed code, we can only have a constructor
6186 // template-id that refers to the current context, so go there
6187 // to find the actual type being constructed.
6188 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(Val: CurContext);
6189 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6190 return DeclarationNameInfo();
6191
6192 // Determine the type of the class being constructed.
6193 CanQualType CurClassType = Context.getCanonicalTagType(TD: CurClass);
6194
6195 // FIXME: Check two things: that the template-id names the same type as
6196 // CurClassType, and that the template-id does not occur when the name
6197 // was qualified.
6198
6199 NameInfo.setName(
6200 Context.DeclarationNames.getCXXConstructorName(Ty: CurClassType));
6201 // FIXME: should we retrieve TypeSourceInfo?
6202 NameInfo.setNamedTypeInfo(nullptr);
6203 return NameInfo;
6204 }
6205
6206 case UnqualifiedIdKind::IK_DestructorName: {
6207 TypeSourceInfo *TInfo;
6208 QualType Ty = GetTypeFromParser(Ty: Name.DestructorName, TInfo: &TInfo);
6209 if (Ty.isNull())
6210 return DeclarationNameInfo();
6211 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6212 Ty: Context.getCanonicalType(T: Ty)));
6213 NameInfo.setNamedTypeInfo(TInfo);
6214 return NameInfo;
6215 }
6216
6217 case UnqualifiedIdKind::IK_TemplateId: {
6218 TemplateName TName = Name.TemplateId->Template.get();
6219 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6220 return Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
6221 }
6222
6223 } // switch (Name.getKind())
6224
6225 llvm_unreachable("Unknown name kind");
6226}
6227
6228static QualType getCoreType(QualType Ty) {
6229 do {
6230 if (Ty->isPointerOrReferenceType())
6231 Ty = Ty->getPointeeType();
6232 else if (Ty->isArrayType())
6233 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6234 else
6235 return Ty.withoutLocalFastQualifiers();
6236 } while (true);
6237}
6238
6239/// hasSimilarParameters - Determine whether the C++ functions Declaration
6240/// and Definition have "nearly" matching parameters. This heuristic is
6241/// used to improve diagnostics in the case where an out-of-line function
6242/// definition doesn't match any declaration within the class or namespace.
6243/// Also sets Params to the list of indices to the parameters that differ
6244/// between the declaration and the definition. If hasSimilarParameters
6245/// returns true and Params is empty, then all of the parameters match.
6246static bool hasSimilarParameters(ASTContext &Context,
6247 FunctionDecl *Declaration,
6248 FunctionDecl *Definition,
6249 SmallVectorImpl<unsigned> &Params) {
6250 Params.clear();
6251 if (Declaration->param_size() != Definition->param_size())
6252 return false;
6253 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6254 QualType DeclParamTy = Declaration->getParamDecl(i: Idx)->getType();
6255 QualType DefParamTy = Definition->getParamDecl(i: Idx)->getType();
6256
6257 // The parameter types are identical
6258 if (Context.hasSameUnqualifiedType(T1: DefParamTy, T2: DeclParamTy))
6259 continue;
6260
6261 QualType DeclParamBaseTy = getCoreType(Ty: DeclParamTy);
6262 QualType DefParamBaseTy = getCoreType(Ty: DefParamTy);
6263 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6264 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6265
6266 if (Context.hasSameUnqualifiedType(T1: DeclParamBaseTy, T2: DefParamBaseTy) ||
6267 (DeclTyName && DeclTyName == DefTyName))
6268 Params.push_back(Elt: Idx);
6269 else // The two parameters aren't even close
6270 return false;
6271 }
6272
6273 return true;
6274}
6275
6276/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6277/// declarator needs to be rebuilt in the current instantiation.
6278/// Any bits of declarator which appear before the name are valid for
6279/// consideration here. That's specifically the type in the decl spec
6280/// and the base type in any member-pointer chunks.
6281static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6282 DeclarationName Name) {
6283 // The types we specifically need to rebuild are:
6284 // - typenames, typeofs, and decltypes
6285 // - types which will become injected class names
6286 // Of course, we also need to rebuild any type referencing such a
6287 // type. It's safest to just say "dependent", but we call out a
6288 // few cases here.
6289
6290 DeclSpec &DS = D.getMutableDeclSpec();
6291 switch (DS.getTypeSpecType()) {
6292 case DeclSpec::TST_typename:
6293 case DeclSpec::TST_typeofType:
6294 case DeclSpec::TST_typeof_unqualType:
6295#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6296#include "clang/Basic/BuiltinTraits.inc"
6297 case DeclSpec::TST_atomic: {
6298 // Grab the type from the parser.
6299 TypeSourceInfo *TSI = nullptr;
6300 QualType T = S.GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TSI);
6301 if (T.isNull() || !T->isInstantiationDependentType()) break;
6302
6303 // Make sure there's a type source info. This isn't really much
6304 // of a waste; most dependent types should have type source info
6305 // attached already.
6306 if (!TSI)
6307 TSI = S.Context.getTrivialTypeSourceInfo(T, Loc: DS.getTypeSpecTypeLoc());
6308
6309 // Rebuild the type in the current instantiation.
6310 TSI = S.RebuildTypeInCurrentInstantiation(T: TSI, Loc: D.getIdentifierLoc(), Name);
6311 if (!TSI) return true;
6312
6313 // Store the new type back in the decl spec.
6314 ParsedType LocType = S.CreateParsedType(T: TSI->getType(), TInfo: TSI);
6315 DS.UpdateTypeRep(Rep: LocType);
6316 break;
6317 }
6318
6319 case DeclSpec::TST_decltype:
6320 case DeclSpec::TST_typeof_unqualExpr:
6321 case DeclSpec::TST_typeofExpr: {
6322 Expr *E = DS.getRepAsExpr();
6323 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6324 if (Result.isInvalid()) return true;
6325 DS.UpdateExprRep(Rep: Result.get());
6326 break;
6327 }
6328
6329 default:
6330 // Nothing to do for these decl specs.
6331 break;
6332 }
6333
6334 // It doesn't matter what order we do this in.
6335 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6336 DeclaratorChunk &Chunk = D.getTypeObject(i: I);
6337
6338 // The only type information in the declarator which can come
6339 // before the declaration name is the base type of a member
6340 // pointer.
6341 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6342 continue;
6343
6344 // Rebuild the scope specifier in-place.
6345 CXXScopeSpec &SS = Chunk.Mem.Scope();
6346 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6347 return true;
6348 }
6349
6350 return false;
6351}
6352
6353/// Returns true if the declaration is declared in a system header or from a
6354/// system macro.
6355static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6356 return SM.isInSystemHeader(Loc: D->getLocation()) ||
6357 SM.isInSystemMacro(loc: D->getLocation());
6358}
6359
6360void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6361 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6362 // of system decl.
6363 if (D->getPreviousDecl() || D->isImplicit())
6364 return;
6365 ReservedIdentifierStatus Status = D->isReserved(LangOpts: getLangOpts());
6366 if (Status != ReservedIdentifierStatus::NotReserved &&
6367 !isFromSystemHeader(SM&: Context.getSourceManager(), D)) {
6368 Diag(Loc: D->getLocation(), DiagID: diag::warn_reserved_extern_symbol)
6369 << D << static_cast<int>(Status);
6370 }
6371}
6372
6373Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6374 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6375
6376 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6377 // declaration only if the `bind_to_declaration` extension is set.
6378 SmallVector<FunctionDecl *, 4> Bases;
6379 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6380 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6381 TP: llvm::omp::TraitProperty::
6382 implementation_extension_bind_to_declaration))
6383 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6384 S, D, TemplateParameterLists: MultiTemplateParamsArg(), Bases);
6385
6386 Decl *Dcl = HandleDeclarator(S, D, TemplateParameterLists: MultiTemplateParamsArg());
6387
6388 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6389 Dcl && Dcl->getDeclContext()->isFileContext())
6390 Dcl->setTopLevelDeclInObjCContainer();
6391
6392 if (!Bases.empty())
6393 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
6394 Bases);
6395
6396 return Dcl;
6397}
6398
6399bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6400 DeclarationNameInfo NameInfo) {
6401 DeclarationName Name = NameInfo.getName();
6402
6403 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC);
6404 while (Record && Record->isAnonymousStructOrUnion())
6405 Record = dyn_cast<CXXRecordDecl>(Val: Record->getParent());
6406 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6407 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_member_name_of_class) << Name;
6408 return true;
6409 }
6410
6411 return false;
6412}
6413
6414bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6415 DeclarationName Name,
6416 SourceLocation Loc,
6417 TemplateIdAnnotation *TemplateId,
6418 bool IsMemberSpecialization) {
6419 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6420 "without nested-name-specifier");
6421 DeclContext *Cur = CurContext;
6422 while (isa<LinkageSpecDecl>(Val: Cur) || isa<CapturedDecl>(Val: Cur))
6423 Cur = Cur->getParent();
6424
6425 // If the user provided a superfluous scope specifier that refers back to the
6426 // class in which the entity is already declared, diagnose and ignore it.
6427 //
6428 // class X {
6429 // void X::f();
6430 // };
6431 //
6432 // Note, it was once ill-formed to give redundant qualification in all
6433 // contexts, but that rule was removed by DR482.
6434 if (Cur->Equals(DC)) {
6435 if (Cur->isRecord()) {
6436 Diag(Loc, DiagID: LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6437 : diag::err_member_extra_qualification)
6438 << Name << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
6439 SS.clear();
6440 } else {
6441 Diag(Loc, DiagID: diag::warn_namespace_member_extra_qualification) << Name;
6442 }
6443 return false;
6444 }
6445
6446 // Check whether the qualifying scope encloses the scope of the original
6447 // declaration. For a template-id, we perform the checks in
6448 // CheckTemplateSpecializationScope.
6449 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6450 Cur = Cur->getEnclosingNonExpansionStatementContext();
6451 if (Cur->isRecord())
6452 Diag(Loc, DiagID: diag::err_member_qualification)
6453 << Name << SS.getRange();
6454 else if (isa<TranslationUnitDecl>(Val: DC))
6455 Diag(Loc, DiagID: diag::err_invalid_declarator_global_scope)
6456 << Name << SS.getRange();
6457 else if (isa<FunctionDecl>(Val: Cur))
6458 Diag(Loc, DiagID: diag::err_invalid_declarator_in_function)
6459 << Name << SS.getRange();
6460 else if (isa<BlockDecl>(Val: Cur))
6461 Diag(Loc, DiagID: diag::err_invalid_declarator_in_block)
6462 << Name << SS.getRange();
6463 else if (isa<ExportDecl>(Val: Cur)) {
6464 if (!isa<NamespaceDecl>(Val: DC))
6465 Diag(Loc, DiagID: diag::err_export_non_namespace_scope_name)
6466 << Name << SS.getRange();
6467 else
6468 // The cases that DC is not NamespaceDecl should be handled in
6469 // CheckRedeclarationExported.
6470 return false;
6471 } else
6472 Diag(Loc, DiagID: diag::err_invalid_declarator_scope)
6473 << Name << cast<NamedDecl>(Val: Cur) << cast<NamedDecl>(Val: DC) << SS.getRange();
6474
6475 return true;
6476 }
6477
6478 if (Cur->isRecord()) {
6479 // C++26 [temp.expl.spec]p3 (Adopted as a DR in CWG727):
6480 // An explicit specialization may be declared in any scope in which the
6481 // corresponding primary template may be defined.
6482 if (IsMemberSpecialization)
6483 return false;
6484
6485 // Cannot qualify members within a class.
6486 Diag(Loc, DiagID: diag::err_member_qualification)
6487 << Name << SS.getRange();
6488 SS.clear();
6489
6490 // C++ constructors and destructors with incorrect scopes can break
6491 // our AST invariants by having the wrong underlying types. If
6492 // that's the case, then drop this declaration entirely.
6493 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6494 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6495 !Context.hasSameType(
6496 T1: Name.getCXXNameType(),
6497 T2: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: Cur))))
6498 return true;
6499
6500 return false;
6501 }
6502
6503 // C++23 [temp.names]p5:
6504 // The keyword template shall not appear immediately after a declarative
6505 // nested-name-specifier.
6506 //
6507 // First check the template-id (if any), and then check each component of the
6508 // nested-name-specifier in reverse order.
6509 //
6510 // FIXME: nested-name-specifiers in friend declarations are declarative,
6511 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6512 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6513 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6514 << FixItHint::CreateRemoval(RemoveRange: TemplateId->TemplateKWLoc);
6515
6516 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6517 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6518 TL = std::exchange(obj&: NextTL, new_val: TypeLoc())) {
6519 SourceLocation TemplateKeywordLoc;
6520 switch (TL.getTypeLocClass()) {
6521 case TypeLoc::TemplateSpecialization: {
6522 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6523 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6524 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6525 Diag(Loc, DiagID: diag::ext_alias_template_in_declarative_nns)
6526 << TST.getLocalSourceRange();
6527 break;
6528 }
6529 case TypeLoc::Decltype:
6530 case TypeLoc::PackIndexing: {
6531 const Type *T = TL.getTypePtr();
6532 // C++23 [expr.prim.id.qual]p2:
6533 // [...] A declarative nested-name-specifier shall not have a
6534 // computed-type-specifier.
6535 //
6536 // CWG2858 changed this from 'decltype-specifier' to
6537 // 'computed-type-specifier'.
6538 Diag(Loc, DiagID: diag::err_computed_type_in_declarative_nns)
6539 << T->isDecltypeType() << TL.getSourceRange();
6540 break;
6541 }
6542 case TypeLoc::DependentName:
6543 NextTL =
6544 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6545 break;
6546 default:
6547 break;
6548 }
6549 if (TemplateKeywordLoc.isValid())
6550 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6551 << FixItHint::CreateRemoval(RemoveRange: TemplateKeywordLoc);
6552 }
6553
6554 return false;
6555}
6556
6557NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6558 MultiTemplateParamsArg TemplateParamLists) {
6559 // TODO: consider using NameInfo for diagnostic.
6560 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6561 DeclarationName Name = NameInfo.getName();
6562
6563 // All of these full declarators require an identifier. If it doesn't have
6564 // one, the ParsedFreeStandingDeclSpec action should be used.
6565 if (D.isDecompositionDeclarator()) {
6566 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6567 } else if (!Name) {
6568 if (!D.isInvalidType()) // Reject this if we think it is valid.
6569 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_declarator_need_ident)
6570 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6571 return nullptr;
6572 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_DeclarationType))
6573 return nullptr;
6574
6575 DeclContext *DC = CurContext;
6576 if (D.getCXXScopeSpec().isInvalid())
6577 D.setInvalidType();
6578 else if (D.getCXXScopeSpec().isSet()) {
6579 if (DiagnoseUnexpandedParameterPack(SS: D.getCXXScopeSpec(),
6580 UPPC: UPPC_DeclarationQualifier))
6581 return nullptr;
6582
6583 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6584 DC = computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext);
6585 if (!DC || isa<EnumDecl>(Val: DC)) {
6586 // If we could not compute the declaration context, it's because the
6587 // declaration context is dependent but does not refer to a class,
6588 // class template, or class template partial specialization. Complain
6589 // and return early, to avoid the coming semantic disaster.
6590 Diag(Loc: D.getIdentifierLoc(),
6591 DiagID: diag::err_template_qualified_declarator_no_match)
6592 << D.getCXXScopeSpec().getScopeRep()
6593 << D.getCXXScopeSpec().getRange();
6594 return nullptr;
6595 }
6596 bool IsDependentContext = DC->isDependentContext();
6597
6598 if (!IsDependentContext &&
6599 RequireCompleteDeclContext(SS&: D.getCXXScopeSpec(), DC))
6600 return nullptr;
6601
6602 // If a class is incomplete, do not parse entities inside it.
6603 if (isa<CXXRecordDecl>(Val: DC) && !cast<CXXRecordDecl>(Val: DC)->hasDefinition()) {
6604 Diag(Loc: D.getIdentifierLoc(),
6605 DiagID: diag::err_member_def_undefined_record)
6606 << Name << DC << D.getCXXScopeSpec().getRange();
6607 return nullptr;
6608 }
6609 if (!D.getDeclSpec().isFriendSpecified()) {
6610 TemplateIdAnnotation *TemplateId =
6611 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6612 ? D.getName().TemplateId
6613 : nullptr;
6614 if (diagnoseQualifiedDeclaration(SS&: D.getCXXScopeSpec(), DC, Name,
6615 Loc: D.getIdentifierLoc(), TemplateId,
6616 /*IsMemberSpecialization=*/false)) {
6617 if (DC->isRecord())
6618 return nullptr;
6619
6620 D.setInvalidType();
6621 } else if (CurContext->isRecord() && !CurContext->Equals(DC)) {
6622 D.setInvalidType();
6623 }
6624 }
6625
6626 // Check whether we need to rebuild the type of the given
6627 // declaration in the current instantiation.
6628 if (EnteringContext && IsDependentContext &&
6629 TemplateParamLists.size() != 0) {
6630 ContextRAII SavedContext(*this, DC);
6631 if (RebuildDeclaratorInCurrentInstantiation(S&: *this, D, Name))
6632 D.setInvalidType();
6633 }
6634 }
6635
6636 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6637 QualType R = TInfo->getType();
6638
6639 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
6640 UPPC: UPPC_DeclarationType))
6641 D.setInvalidType();
6642
6643 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6644 forRedeclarationInCurContext());
6645
6646 // See if this is a redefinition of a variable in the same scope.
6647 if (!D.getCXXScopeSpec().isSet()) {
6648 bool IsLinkageLookup = false;
6649 bool CreateBuiltins = false;
6650
6651 // If the declaration we're planning to build will be a function
6652 // or object with linkage, then look for another declaration with
6653 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6654 //
6655 // If the declaration we're planning to build will be declared with
6656 // external linkage in the translation unit, create any builtin with
6657 // the same name.
6658 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6659 /* Do nothing*/;
6660 else if (CurContext->isFunctionOrMethod() &&
6661 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6662 R->isFunctionType())) {
6663 IsLinkageLookup = true;
6664 CreateBuiltins =
6665 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6666 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6667 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6668 CreateBuiltins = true;
6669
6670 if (IsLinkageLookup) {
6671 Previous.clear(Kind: LookupRedeclarationWithLinkage);
6672 Previous.setRedeclarationKind(
6673 RedeclarationKind::ForExternalRedeclaration);
6674 }
6675
6676 LookupName(R&: Previous, S, AllowBuiltinCreation: CreateBuiltins);
6677 } else { // Something like "int foo::x;"
6678 LookupQualifiedName(R&: Previous, LookupCtx: DC);
6679
6680 // C++ [dcl.meaning]p1:
6681 // When the declarator-id is qualified, the declaration shall refer to a
6682 // previously declared member of the class or namespace to which the
6683 // qualifier refers (or, in the case of a namespace, of an element of the
6684 // inline namespace set of that namespace (7.3.1)) or to a specialization
6685 // thereof; [...]
6686 //
6687 // Note that we already checked the context above, and that we do not have
6688 // enough information to make sure that Previous contains the declaration
6689 // we want to match. For example, given:
6690 //
6691 // class X {
6692 // void f();
6693 // void f(float);
6694 // };
6695 //
6696 // void X::f(int) { } // ill-formed
6697 //
6698 // In this case, Previous will point to the overload set
6699 // containing the two f's declared in X, but neither of them
6700 // matches.
6701
6702 RemoveUsingDecls(R&: Previous);
6703 }
6704
6705 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6706 TPD && TPD->isTemplateParameter()) {
6707 // Older versions of clang allowed the names of function/variable templates
6708 // to shadow the names of their template parameters. For the compatibility
6709 // purposes we detect such cases and issue a default-to-error warning that
6710 // can be disabled with -Wno-strict-primary-template-shadow.
6711 if (!D.isInvalidType()) {
6712 bool AllowForCompatibility = false;
6713 if (Scope *DeclParent = S->getDeclParent();
6714 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6715 AllowForCompatibility = DeclParent->Contains(rhs: *TemplateParamParent) &&
6716 TemplateParamParent->isDeclScope(D: TPD);
6717 }
6718 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl: TPD,
6719 SupportedForCompatibility: AllowForCompatibility);
6720 }
6721
6722 // Just pretend that we didn't see the previous declaration.
6723 Previous.clear();
6724 }
6725
6726 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6727 // Forget that the previous declaration is the injected-class-name.
6728 Previous.clear();
6729
6730 // In C++, the previous declaration we find might be a tag type
6731 // (class or enum). In this case, the new declaration will hide the
6732 // tag type. Note that this applies to functions, function templates, and
6733 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6734 if (Previous.isSingleTagDecl() &&
6735 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6736 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6737 Previous.clear();
6738
6739 // Check that there are no default arguments other than in the parameters
6740 // of a function declaration (C++ only).
6741 if (getLangOpts().CPlusPlus)
6742 CheckExtraCXXDefaultArguments(D);
6743
6744 /// Get the innermost enclosing declaration scope.
6745 S = S->getDeclParent();
6746
6747 NamedDecl *New;
6748
6749 bool AddToScope = true;
6750 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6751 if (TemplateParamLists.size()) {
6752 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_typedef);
6753 return nullptr;
6754 }
6755
6756 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6757 } else if (R->isFunctionType()) {
6758 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6759 TemplateParamLists,
6760 AddToScope);
6761 } else {
6762 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6763 AddToScope);
6764 }
6765
6766 if (!New)
6767 return nullptr;
6768
6769 warnOnCTypeHiddenInCPlusPlus(D: New);
6770
6771 // If this has an identifier and is not a function template specialization,
6772 // add it to the scope stack.
6773 if (New->getDeclName() && AddToScope)
6774 PushOnScopeChains(D: New, S);
6775
6776 if (OpenMP().isInOpenMPDeclareTargetContext())
6777 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
6778
6779 return New;
6780}
6781
6782/// Helper method to turn variable array types into constant array
6783/// types in certain situations which would otherwise be errors (for
6784/// GCC compatibility).
6785static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6786 ASTContext &Context,
6787 bool &SizeIsNegative,
6788 llvm::APSInt &Oversized) {
6789 // This method tries to turn a variable array into a constant
6790 // array even when the size isn't an ICE. This is necessary
6791 // for compatibility with code that depends on gcc's buggy
6792 // constant expression folding, like struct {char x[(int)(char*)2];}
6793 SizeIsNegative = false;
6794 Oversized = 0;
6795
6796 if (T->isDependentType())
6797 return QualType();
6798
6799 QualifierCollector Qs;
6800 const Type *Ty = Qs.strip(type: T);
6801
6802 if (const PointerType* PTy = dyn_cast<PointerType>(Val: Ty)) {
6803 QualType Pointee = PTy->getPointeeType();
6804 QualType FixedType =
6805 TryToFixInvalidVariablyModifiedType(T: Pointee, Context, SizeIsNegative,
6806 Oversized);
6807 if (FixedType.isNull()) return FixedType;
6808 FixedType = Context.getPointerType(T: FixedType);
6809 return Qs.apply(Context, QT: FixedType);
6810 }
6811 if (const ParenType* PTy = dyn_cast<ParenType>(Val: Ty)) {
6812 QualType Inner = PTy->getInnerType();
6813 QualType FixedType =
6814 TryToFixInvalidVariablyModifiedType(T: Inner, Context, SizeIsNegative,
6815 Oversized);
6816 if (FixedType.isNull()) return FixedType;
6817 FixedType = Context.getParenType(NamedType: FixedType);
6818 return Qs.apply(Context, QT: FixedType);
6819 }
6820
6821 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(Val&: T);
6822 if (!VLATy)
6823 return QualType();
6824
6825 QualType ElemTy = VLATy->getElementType();
6826 if (ElemTy->isVariablyModifiedType()) {
6827 ElemTy = TryToFixInvalidVariablyModifiedType(T: ElemTy, Context,
6828 SizeIsNegative, Oversized);
6829 if (ElemTy.isNull())
6830 return QualType();
6831 }
6832
6833 Expr::EvalResult Result;
6834 if (!VLATy->getSizeExpr() ||
6835 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Ctx: Context))
6836 return QualType();
6837
6838 llvm::APSInt Res = Result.Val.getInt();
6839
6840 // Check whether the array size is negative.
6841 if (Res.isSigned() && Res.isNegative()) {
6842 SizeIsNegative = true;
6843 return QualType();
6844 }
6845
6846 // Check whether the array is too large to be addressed.
6847 unsigned ActiveSizeBits =
6848 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6849 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6850 ? ConstantArrayType::getNumAddressingBits(Context, ElementType: ElemTy, NumElements: Res)
6851 : Res.getActiveBits();
6852 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6853 Oversized = std::move(Res);
6854 return QualType();
6855 }
6856
6857 QualType FoldedArrayType = Context.getConstantArrayType(
6858 EltTy: ElemTy, ArySize: Res, SizeExpr: VLATy->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6859 return Qs.apply(Context, QT: FoldedArrayType);
6860}
6861
6862static void
6863FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6864 SrcTL = SrcTL.getUnqualifiedLoc();
6865 DstTL = DstTL.getUnqualifiedLoc();
6866 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6867 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6868 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getPointeeLoc(),
6869 DstTL: DstPTL.getPointeeLoc());
6870 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6871 return;
6872 }
6873 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6874 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6875 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getInnerLoc(),
6876 DstTL: DstPTL.getInnerLoc());
6877 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6878 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6879 return;
6880 }
6881 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6882 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6883 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6884 TypeLoc DstElemTL = DstATL.getElementLoc();
6885 if (VariableArrayTypeLoc SrcElemATL =
6886 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6887 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6888 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcElemATL, DstTL: DstElemATL);
6889 } else {
6890 DstElemTL.initializeFullCopy(Other: SrcElemTL);
6891 }
6892 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6893 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6894 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6895}
6896
6897/// Helper method to turn variable array types into constant array
6898/// types in certain situations which would otherwise be errors (for
6899/// GCC compatibility).
6900static TypeSourceInfo*
6901TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6902 ASTContext &Context,
6903 bool &SizeIsNegative,
6904 llvm::APSInt &Oversized) {
6905 QualType FixedTy
6906 = TryToFixInvalidVariablyModifiedType(T: TInfo->getType(), Context,
6907 SizeIsNegative, Oversized);
6908 if (FixedTy.isNull())
6909 return nullptr;
6910 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(T: FixedTy);
6911 FixInvalidVariablyModifiedTypeLoc(SrcTL: TInfo->getTypeLoc(),
6912 DstTL: FixedTInfo->getTypeLoc());
6913 return FixedTInfo;
6914}
6915
6916bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6917 QualType &T, SourceLocation Loc,
6918 unsigned FailedFoldDiagID) {
6919 bool SizeIsNegative;
6920 llvm::APSInt Oversized;
6921 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6922 TInfo, Context, SizeIsNegative, Oversized);
6923 if (FixedTInfo) {
6924 Diag(Loc, DiagID: diag::ext_vla_folded_to_constant);
6925 TInfo = FixedTInfo;
6926 T = FixedTInfo->getType();
6927 return true;
6928 }
6929
6930 if (SizeIsNegative)
6931 Diag(Loc, DiagID: diag::err_typecheck_negative_array_size);
6932 else if (Oversized.getBoolValue())
6933 Diag(Loc, DiagID: diag::err_array_too_large) << toString(
6934 I: Oversized, Radix: 10, Signed: Oversized.isSigned(), /*formatAsCLiteral=*/false,
6935 /*UpperCase=*/false, /*InsertSeparators=*/true);
6936 else if (FailedFoldDiagID)
6937 Diag(Loc, DiagID: FailedFoldDiagID);
6938 return false;
6939}
6940
6941void
6942Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6943 if (!getLangOpts().CPlusPlus &&
6944 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6945 // Don't need to track declarations in the TU in C.
6946 return;
6947
6948 // Note that we have a locally-scoped external with this name.
6949 Context.getExternCContextDecl()->makeDeclVisibleInContext(D: ND);
6950}
6951
6952NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6953 // FIXME: We can have multiple results via __attribute__((overloadable)).
6954 auto Result = Context.getExternCContextDecl()->lookup(Name);
6955 return Result.empty() ? nullptr : *Result.begin();
6956}
6957
6958void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6959 // FIXME: We should probably indicate the identifier in question to avoid
6960 // confusion for constructs like "virtual int a(), b;"
6961 if (DS.isVirtualSpecified())
6962 Diag(Loc: DS.getVirtualSpecLoc(),
6963 DiagID: diag::err_virtual_non_function);
6964
6965 if (DS.hasExplicitSpecifier())
6966 Diag(Loc: DS.getExplicitSpecLoc(),
6967 DiagID: diag::err_explicit_non_function);
6968
6969 if (DS.isNoreturnSpecified())
6970 Diag(Loc: DS.getNoreturnSpecLoc(),
6971 DiagID: diag::err_noreturn_non_function);
6972}
6973
6974NamedDecl*
6975Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6976 TypeSourceInfo *TInfo, LookupResult &Previous) {
6977 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6978 if (D.getCXXScopeSpec().isSet()) {
6979 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_typedef_declarator)
6980 << D.getCXXScopeSpec().getRange();
6981 D.setInvalidType();
6982 // Pretend we didn't see the scope specifier.
6983 DC = CurContext;
6984 Previous.clear();
6985 }
6986
6987 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
6988
6989 if (D.getDeclSpec().isInlineSpecified())
6990 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
6991 DiagID: (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6992 ? diag::warn_ms_inline_non_function
6993 : diag::err_inline_non_function)
6994 << getLangOpts().CPlusPlus17;
6995 if (D.getDeclSpec().hasConstexprSpecifier())
6996 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
6997 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6998
6999 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
7000 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
7001 Diag(Loc: D.getName().StartLocation,
7002 DiagID: diag::err_deduction_guide_invalid_specifier)
7003 << "typedef";
7004 else
7005 Diag(Loc: D.getName().StartLocation, DiagID: diag::err_typedef_not_identifier)
7006 << D.getName().getSourceRange();
7007 return nullptr;
7008 }
7009
7010 TypedefDecl *NewTD = ParseTypedefDecl(S, D, T: TInfo->getType(), TInfo);
7011 if (!NewTD) return nullptr;
7012
7013 // Handle attributes prior to checking for duplicates in MergeVarDecl
7014 ProcessDeclAttributes(S, D: NewTD, PD: D);
7015
7016 CheckTypedefForVariablyModifiedType(S, D: NewTD);
7017
7018 bool Redeclaration = D.isRedeclaration();
7019 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, D: NewTD, Previous, Redeclaration);
7020 D.setRedeclaration(Redeclaration);
7021 return ND;
7022}
7023
7024void
7025Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
7026 // C99 6.7.7p2: If a typedef name specifies a variably modified type
7027 // then it shall have block scope.
7028 // Note that variably modified types must be fixed before merging the decl so
7029 // that redeclarations will match.
7030 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
7031 QualType T = TInfo->getType();
7032 if (T->isVariablyModifiedType()) {
7033 setFunctionHasBranchProtectedScope();
7034
7035 if (S->getFnParent() == nullptr) {
7036 bool SizeIsNegative;
7037 llvm::APSInt Oversized;
7038 TypeSourceInfo *FixedTInfo =
7039 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7040 SizeIsNegative,
7041 Oversized);
7042 if (FixedTInfo) {
7043 Diag(Loc: NewTD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
7044 NewTD->setTypeSourceInfo(FixedTInfo);
7045 } else {
7046 if (SizeIsNegative)
7047 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_typecheck_negative_array_size);
7048 else if (T->isVariableArrayType())
7049 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope);
7050 else if (Oversized.getBoolValue())
7051 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_array_too_large)
7052 << toString(I: Oversized, Radix: 10);
7053 else
7054 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
7055 NewTD->setInvalidDecl();
7056 }
7057 }
7058 }
7059}
7060
7061NamedDecl*
7062Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
7063 LookupResult &Previous, bool &Redeclaration) {
7064
7065 // Find the shadowed declaration before filtering for scope.
7066 NamedDecl *ShadowedDecl = getShadowedDeclaration(D: NewTD, R: Previous);
7067
7068 // Merge the decl with the existing one if appropriate. If the decl is
7069 // in an outer scope, it isn't the same thing.
7070 FilterLookupForScope(R&: Previous, Ctx: DC, S, /*ConsiderLinkage*/false,
7071 /*AllowInlineNamespace*/false);
7072 filterNonConflictingPreviousTypedefDecls(S&: *this, Decl: NewTD, Previous);
7073 if (!Previous.empty()) {
7074 Redeclaration = true;
7075 MergeTypedefNameDecl(S, New: NewTD, OldDecls&: Previous);
7076 } else {
7077 inferGslPointerAttribute(TD: NewTD);
7078 }
7079
7080 if (ShadowedDecl && !Redeclaration)
7081 CheckShadow(D: NewTD, ShadowedDecl, R: Previous);
7082
7083 // If this is the C FILE type, notify the AST context.
7084 if (IdentifierInfo *II = NewTD->getIdentifier())
7085 if (!NewTD->isInvalidDecl() &&
7086 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7087 switch (II->getNotableIdentifierID()) {
7088 case tok::NotableIdentifierKind::FILE:
7089 Context.setFILEDecl(NewTD);
7090 break;
7091 case tok::NotableIdentifierKind::jmp_buf:
7092 Context.setjmp_bufDecl(NewTD);
7093 break;
7094 case tok::NotableIdentifierKind::sigjmp_buf:
7095 Context.setsigjmp_bufDecl(NewTD);
7096 break;
7097 case tok::NotableIdentifierKind::ucontext_t:
7098 Context.setucontext_tDecl(NewTD);
7099 break;
7100 case tok::NotableIdentifierKind::float_t:
7101 case tok::NotableIdentifierKind::double_t:
7102 NewTD->addAttr(A: AvailableOnlyInDefaultEvalMethodAttr::Create(Ctx&: Context));
7103 break;
7104 default:
7105 break;
7106 }
7107 }
7108
7109 return NewTD;
7110}
7111
7112/// Determines whether the given declaration is an out-of-scope
7113/// previous declaration.
7114///
7115/// This routine should be invoked when name lookup has found a
7116/// previous declaration (PrevDecl) that is not in the scope where a
7117/// new declaration by the same name is being introduced. If the new
7118/// declaration occurs in a local scope, previous declarations with
7119/// linkage may still be considered previous declarations (C99
7120/// 6.2.2p4-5, C++ [basic.link]p6).
7121///
7122/// \param PrevDecl the previous declaration found by name
7123/// lookup
7124///
7125/// \param DC the context in which the new declaration is being
7126/// declared.
7127///
7128/// \returns true if PrevDecl is an out-of-scope previous declaration
7129/// for a new delcaration with the same name.
7130static bool
7131isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
7132 ASTContext &Context) {
7133 if (!PrevDecl)
7134 return false;
7135
7136 if (!PrevDecl->hasLinkage())
7137 return false;
7138
7139 if (Context.getLangOpts().CPlusPlus) {
7140 // C++ [basic.link]p6:
7141 // If there is a visible declaration of an entity with linkage
7142 // having the same name and type, ignoring entities declared
7143 // outside the innermost enclosing namespace scope, the block
7144 // scope declaration declares that same entity and receives the
7145 // linkage of the previous declaration.
7146 DeclContext *OuterContext = DC->getRedeclContext();
7147 if (!OuterContext->isFunctionOrMethod())
7148 // This rule only applies to block-scope declarations.
7149 return false;
7150
7151 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7152 if (PrevOuterContext->isRecord())
7153 // We found a member function: ignore it.
7154 return false;
7155
7156 // Find the innermost enclosing namespace for the new and
7157 // previous declarations.
7158 OuterContext = OuterContext->getEnclosingNamespaceContext();
7159 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7160
7161 // The previous declaration is in a different namespace, so it
7162 // isn't the same function.
7163 if (!OuterContext->Equals(DC: PrevOuterContext))
7164 return false;
7165 }
7166
7167 return true;
7168}
7169
7170static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
7171 CXXScopeSpec &SS = D.getCXXScopeSpec();
7172 if (!SS.isSet()) return;
7173 DD->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
7174}
7175
7176void Sema::deduceOpenCLAddressSpace(VarDecl *Var) {
7177 LangAS ImplAS = LangAS::opencl_private;
7178 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7179 // __opencl_c_program_scope_global_variables feature, the address space
7180 // for a variable at program scope or a static or extern variable inside
7181 // a function are inferred to be __global.
7182 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()) &&
7183 Var->hasGlobalStorage())
7184 ImplAS = LangAS::opencl_global;
7185 Var->assignAddressSpace(Ctxt: Context, AS: ImplAS);
7186}
7187
7188static bool checkWeakAttrCompatibility(Sema &S, const NamedDecl &ND,
7189 const WeakAttr &Attr) {
7190 const NamedDecl *D = &ND;
7191 // IFuncAttr is not inherited, so a redeclaration may need to check the
7192 // attributes on the definition instead.
7193 if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND))
7194 if (const FunctionDecl *Def = FD->getDefinition())
7195 D = Def;
7196 return DiagnoseMutualExclusions(S, D, A: &Attr);
7197}
7198
7199static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7200 // 'weak' only applies to declarations with external linkage.
7201 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7202 if (!ND.isExternallyVisible()) {
7203 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weak_static);
7204 ND.dropAttr<WeakAttr>();
7205 } else if (!checkWeakAttrCompatibility(S, ND, Attr: *Attr)) {
7206 // A forward #pragma weak adds the attribute without checking mutual
7207 // exclusions during attribute processing.
7208 ND.dropAttr<WeakAttr>();
7209 }
7210 }
7211}
7212
7213static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7214 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7215 if (ND.isExternallyVisible()) {
7216 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weakref_not_static);
7217 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7218 }
7219 }
7220}
7221
7222static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7223 if (auto *VD = dyn_cast<VarDecl>(Val: &ND)) {
7224 if (VD->hasInit()) {
7225 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7226 assert(VD->isThisDeclarationADefinition() &&
7227 "Broken AliasAttr handled late!");
7228 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << VD << 0;
7229 VD->dropAttr<AliasAttr>();
7230 }
7231 }
7232 }
7233}
7234
7235static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7236 // 'selectany' only applies to externally visible variable declarations.
7237 // It does not apply to functions.
7238 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7239 if (isa<FunctionDecl>(Val: ND) || !ND.isExternallyVisible()) {
7240 S.Diag(Loc: Attr->getLocation(),
7241 DiagID: diag::err_attribute_selectany_non_extern_data);
7242 ND.dropAttr<SelectAnyAttr>();
7243 }
7244 }
7245}
7246
7247static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND) {
7248 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7249 if (!ND.isExternallyVisible())
7250 S.Diag(Loc: Attr->getLocation(),
7251 DiagID: diag::warn_attribute_hybrid_patchable_non_extern);
7252 }
7253}
7254
7255static void checkInheritableAttr(Sema &S, NamedDecl &ND) {
7256 if (const InheritableAttr *Attr = getDLLAttr(D: &ND)) {
7257 auto *VD = dyn_cast<VarDecl>(Val: &ND);
7258 bool IsAnonymousNS = false;
7259 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7260 if (VD) {
7261 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: VD->getDeclContext());
7262 while (NS && !IsAnonymousNS) {
7263 IsAnonymousNS = NS->isAnonymousNamespace();
7264 NS = dyn_cast<NamespaceDecl>(Val: NS->getParent());
7265 }
7266 }
7267 // dll attributes require external linkage. Static locals may have external
7268 // linkage but still cannot be explicitly imported or exported.
7269 // In Microsoft mode, a variable defined in anonymous namespace must have
7270 // external linkage in order to be exported.
7271 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7272 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7273 (!AnonNSInMicrosoftMode &&
7274 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7275 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_attribute_dll_not_extern)
7276 << &ND << Attr;
7277 ND.setInvalidDecl();
7278 }
7279 }
7280}
7281
7282static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND) {
7283 // Check the attributes on the function type and function params, if any.
7284 if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND)) {
7285 FD = FD->getMostRecentDecl();
7286 // Don't declare this variable in the second operand of the for-statement;
7287 // GCC miscompiles that by ending its lifetime before evaluating the
7288 // third operand. See gcc.gnu.org/PR86769.
7289 AttributedTypeLoc ATL;
7290 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7291 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7292 TL = ATL.getModifiedLoc()) {
7293 // The [[lifetimebound]] attribute can be applied to the implicit object
7294 // parameter of a non-static member function (other than a ctor or dtor)
7295 // by applying it to the function type.
7296 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7297 const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
7298 int NoImplicitObjectError = -1;
7299 if (!MD)
7300 NoImplicitObjectError = 0;
7301 else if (MD->isStatic())
7302 NoImplicitObjectError = 1;
7303 else if (MD->isExplicitObjectMemberFunction())
7304 NoImplicitObjectError = 2;
7305 if (NoImplicitObjectError != -1) {
7306 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_no_object_param)
7307 << NoImplicitObjectError << A->getRange();
7308 } else if (isa<CXXConstructorDecl>(Val: MD) || isa<CXXDestructorDecl>(Val: MD)) {
7309 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_ctor_dtor)
7310 << isa<CXXDestructorDecl>(Val: MD) << A->getRange();
7311 } else if (MD->getReturnType()->isVoidType()) {
7312 S.Diag(
7313 Loc: MD->getLocation(),
7314 DiagID: diag::
7315 err_lifetimebound_implicit_object_parameter_void_return_type);
7316 }
7317 }
7318 }
7319
7320 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7321 const ParmVarDecl *P = FD->getParamDecl(i: I);
7322
7323 // The [[lifetimebound]] attribute can be applied to a function parameter
7324 // only if the function returns a value.
7325 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7326 if (!isa<CXXConstructorDecl>(Val: FD) && FD->getReturnType()->isVoidType()) {
7327 S.Diag(Loc: A->getLocation(),
7328 DiagID: diag::err_lifetimebound_parameter_void_return_type);
7329 }
7330 }
7331 }
7332 }
7333}
7334
7335static void checkModularFormatAttr(Sema &S, NamedDecl &ND) {
7336 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7337 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_modular_format_attribute_no_format);
7338}
7339
7340static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7341 // Ensure that an auto decl is deduced otherwise the checks below might cache
7342 // the wrong linkage.
7343 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7344
7345 checkWeakAttr(S, ND);
7346 checkWeakRefAttr(S, ND);
7347 checkAliasAttr(S, ND);
7348 checkSelectAnyAttr(S, ND);
7349 checkHybridPatchableAttr(S, ND);
7350 checkInheritableAttr(S, ND);
7351 checkLifetimeBoundAttr(S, ND);
7352}
7353
7354static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7355 NamedDecl *NewDecl,
7356 bool IsSpecialization,
7357 bool IsDefinition) {
7358 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7359 return;
7360
7361 bool IsTemplate = false;
7362 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(Val: OldDecl)) {
7363 OldDecl = OldTD->getTemplatedDecl();
7364 IsTemplate = true;
7365 if (!IsSpecialization)
7366 IsDefinition = false;
7367 }
7368 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(Val: NewDecl)) {
7369 NewDecl = NewTD->getTemplatedDecl();
7370 IsTemplate = true;
7371 }
7372
7373 if (!OldDecl || !NewDecl)
7374 return;
7375
7376 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7377 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7378 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7379 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7380
7381 // dllimport and dllexport are inheritable attributes so we have to exclude
7382 // inherited attribute instances.
7383 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7384 (NewExportAttr && !NewExportAttr->isInherited());
7385
7386 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7387 // the only exception being explicit specializations.
7388 // Implicitly generated declarations are also excluded for now because there
7389 // is no other way to switch these to use dllimport or dllexport.
7390 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7391
7392 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7393 // Allow with a warning for free functions and global variables.
7394 bool JustWarn = false;
7395 if (!OldDecl->isCXXClassMember()) {
7396 auto *VD = dyn_cast<VarDecl>(Val: OldDecl);
7397 if (VD && !VD->getDescribedVarTemplate())
7398 JustWarn = true;
7399 auto *FD = dyn_cast<FunctionDecl>(Val: OldDecl);
7400 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7401 JustWarn = true;
7402 }
7403
7404 // We cannot change a declaration that's been used because IR has already
7405 // been emitted. Dllimported functions will still work though (modulo
7406 // address equality) as they can use the thunk.
7407 if (OldDecl->isUsed())
7408 if (!isa<FunctionDecl>(Val: OldDecl) || !NewImportAttr)
7409 JustWarn = false;
7410
7411 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7412 : diag::err_attribute_dll_redeclaration;
7413 S.Diag(Loc: NewDecl->getLocation(), DiagID)
7414 << NewDecl
7415 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7416 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7417 if (!JustWarn) {
7418 NewDecl->setInvalidDecl();
7419 return;
7420 }
7421 }
7422
7423 // A redeclaration is not allowed to drop a dllimport attribute, the only
7424 // exceptions being inline function definitions (except for function
7425 // templates), local extern declarations, qualified friend declarations or
7426 // special MSVC extension: in the last case, the declaration is treated as if
7427 // it were marked dllexport.
7428 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7429 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7430 if (const auto *VD = dyn_cast<VarDecl>(Val: NewDecl)) {
7431 // Ignore static data because out-of-line definitions are diagnosed
7432 // separately.
7433 IsStaticDataMember = VD->isStaticDataMember();
7434 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7435 VarDecl::DeclarationOnly;
7436 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: NewDecl)) {
7437 IsInline = FD->isInlined();
7438 IsQualifiedFriend = FD->getQualifier() &&
7439 FD->getFriendObjectKind() == Decl::FOK_Declared;
7440 }
7441
7442 if (OldImportAttr && !HasNewAttr &&
7443 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7444 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7445 if (IsMicrosoftABI && IsDefinition) {
7446 if (IsSpecialization) {
7447 S.Diag(
7448 Loc: NewDecl->getLocation(),
7449 DiagID: diag::err_attribute_dllimport_function_specialization_definition);
7450 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_attribute);
7451 NewDecl->dropAttr<DLLImportAttr>();
7452 } else {
7453 S.Diag(Loc: NewDecl->getLocation(),
7454 DiagID: diag::warn_redeclaration_without_import_attribute)
7455 << NewDecl;
7456 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7457 NewDecl->dropAttr<DLLImportAttr>();
7458 NewDecl->addAttr(A: DLLExportAttr::CreateImplicit(
7459 Ctx&: S.Context, Range: NewImportAttr->getRange()));
7460 }
7461 } else if (IsMicrosoftABI && IsSpecialization) {
7462 assert(!IsDefinition);
7463 // MSVC allows this. Keep the inherited attribute.
7464 } else {
7465 S.Diag(Loc: NewDecl->getLocation(),
7466 DiagID: diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7467 << NewDecl << OldImportAttr;
7468 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7469 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_previous_attribute);
7470 OldDecl->dropAttr<DLLImportAttr>();
7471 NewDecl->dropAttr<DLLImportAttr>();
7472 }
7473 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7474 // In MinGW, seeing a function declared inline drops the dllimport
7475 // attribute.
7476 OldDecl->dropAttr<DLLImportAttr>();
7477 NewDecl->dropAttr<DLLImportAttr>();
7478 S.Diag(Loc: NewDecl->getLocation(),
7479 DiagID: diag::warn_dllimport_dropped_from_inline_function)
7480 << NewDecl << OldImportAttr;
7481 }
7482
7483 // A specialization of a class template member function is processed here
7484 // since it's a redeclaration. If the parent class is dllexport, the
7485 // specialization inherits that attribute. This doesn't happen automatically
7486 // since the parent class isn't instantiated until later.
7487 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDecl)) {
7488 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7489 !NewImportAttr && !NewExportAttr) {
7490 if (const DLLExportAttr *ParentExportAttr =
7491 MD->getParent()->getAttr<DLLExportAttr>()) {
7492 DLLExportAttr *NewAttr = ParentExportAttr->clone(C&: S.Context);
7493 NewAttr->setInherited(true);
7494 NewDecl->addAttr(A: NewAttr);
7495 }
7496 }
7497 }
7498}
7499
7500/// Given that we are within the definition of the given function,
7501/// will that definition behave like C99's 'inline', where the
7502/// definition is discarded except for optimization purposes?
7503static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7504 // Try to avoid calling GetGVALinkageForFunction.
7505
7506 // All cases of this require the 'inline' keyword.
7507 if (!FD->isInlined()) return false;
7508
7509 // This is only possible in C++ with the gnu_inline attribute.
7510 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7511 return false;
7512
7513 // Okay, go ahead and call the relatively-more-expensive function.
7514 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7515}
7516
7517/// Determine whether a variable is extern "C" prior to attaching
7518/// an initializer. We can't just call isExternC() here, because that
7519/// will also compute and cache whether the declaration is externally
7520/// visible, which might change when we attach the initializer.
7521///
7522/// This can only be used if the declaration is known to not be a
7523/// redeclaration of an internal linkage declaration.
7524///
7525/// For instance:
7526///
7527/// auto x = []{};
7528///
7529/// Attaching the initializer here makes this declaration not externally
7530/// visible, because its type has internal linkage.
7531///
7532/// FIXME: This is a hack.
7533template<typename T>
7534static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7535 if (S.getLangOpts().CPlusPlus) {
7536 // In C++, the overloadable attribute negates the effects of extern "C".
7537 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7538 return false;
7539
7540 // So do CUDA's host/device attributes.
7541 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7542 D->template hasAttr<CUDAHostAttr>()))
7543 return false;
7544 }
7545 return D->isExternC();
7546}
7547
7548static bool shouldConsiderLinkage(const VarDecl *VD) {
7549 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7550 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(Val: DC) ||
7551 isa<OMPDeclareMapperDecl>(Val: DC))
7552 return VD->hasExternalStorage();
7553 if (DC->isFileContext())
7554 return true;
7555 if (DC->isRecord())
7556 return false;
7557 if (DC->getDeclKind() == Decl::HLSLBuffer)
7558 return false;
7559
7560 if (isa<RequiresExprBodyDecl, CXXExpansionStmtDecl>(Val: DC))
7561 return false;
7562 llvm_unreachable("Unexpected context");
7563}
7564
7565static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7566 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7567 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7568 isa<OMPDeclareReductionDecl>(Val: DC) || isa<OMPDeclareMapperDecl>(Val: DC))
7569 return true;
7570 if (DC->isRecord() || isa<CXXExpansionStmtDecl>(Val: DC))
7571 return false;
7572 llvm_unreachable("Unexpected context");
7573}
7574
7575static bool hasParsedAttr(Scope *S, const Declarator &PD,
7576 ParsedAttr::Kind Kind) {
7577 // Check decl attributes on the DeclSpec.
7578 if (PD.getDeclSpec().getAttributes().hasAttribute(K: Kind))
7579 return true;
7580
7581 // Walk the declarator structure, checking decl attributes that were in a type
7582 // position to the decl itself.
7583 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7584 if (PD.getTypeObject(i: I).getAttrs().hasAttribute(K: Kind))
7585 return true;
7586 }
7587
7588 // Finally, check attributes on the decl itself.
7589 return PD.getAttributes().hasAttribute(K: Kind) ||
7590 PD.getDeclarationAttributes().hasAttribute(K: Kind);
7591}
7592
7593bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7594 if (!DC->isFunctionOrMethod())
7595 return false;
7596
7597 // If this is a local extern function or variable declared within a function
7598 // template, don't add it into the enclosing namespace scope until it is
7599 // instantiated; it might have a dependent type right now.
7600 if (DC->isDependentContext())
7601 return true;
7602
7603 // C++11 [basic.link]p7:
7604 // When a block scope declaration of an entity with linkage is not found to
7605 // refer to some other declaration, then that entity is a member of the
7606 // innermost enclosing namespace.
7607 //
7608 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7609 // semantically-enclosing namespace, not a lexically-enclosing one.
7610 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(Val: DC))
7611 DC = DC->getParent();
7612 return true;
7613}
7614
7615/// Returns true if given declaration has external C language linkage.
7616static bool isDeclExternC(const Decl *D) {
7617 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
7618 return FD->isExternC();
7619 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
7620 return VD->isExternC();
7621
7622 llvm_unreachable("Unknown type of decl!");
7623}
7624
7625/// Returns true if there hasn't been any invalid type diagnosed.
7626static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7627 DeclContext *DC = NewVD->getDeclContext();
7628 QualType R = NewVD->getType();
7629
7630 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7631 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7632 // argument.
7633 if (R->isImageType() || R->isPipeType()) {
7634 Se.Diag(Loc: NewVD->getLocation(),
7635 DiagID: diag::err_opencl_type_can_only_be_used_as_function_parameter)
7636 << R;
7637 NewVD->setInvalidDecl();
7638 return false;
7639 }
7640
7641 // OpenCL v1.2 s6.9.r:
7642 // The event type cannot be used to declare a program scope variable.
7643 // OpenCL v2.0 s6.9.q:
7644 // The clk_event_t and reserve_id_t types cannot be declared in program
7645 // scope.
7646 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7647 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7648 Se.Diag(Loc: NewVD->getLocation(),
7649 DiagID: diag::err_invalid_type_for_program_scope_var)
7650 << R;
7651 NewVD->setInvalidDecl();
7652 return false;
7653 }
7654 }
7655
7656 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7657 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
7658 LO: Se.getLangOpts())) {
7659 QualType NR = R.getCanonicalType();
7660 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7661 NR->isReferenceType()) {
7662 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7663 NR->isFunctionReferenceType()) {
7664 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_pointer)
7665 << NR->isReferenceType();
7666 NewVD->setInvalidDecl();
7667 return false;
7668 }
7669 NR = NR->getPointeeType();
7670 }
7671 }
7672
7673 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
7674 LO: Se.getLangOpts())) {
7675 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7676 // half array type (unless the cl_khr_fp16 extension is enabled).
7677 if (Se.Context.getBaseElementType(QT: R)->isHalfType()) {
7678 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_half_declaration) << R;
7679 NewVD->setInvalidDecl();
7680 return false;
7681 }
7682 }
7683
7684 // OpenCL v1.2 s6.9.r:
7685 // The event type cannot be used with the __local, __constant and __global
7686 // address space qualifiers.
7687 if (R->isEventT()) {
7688 if (R.getAddressSpace() != LangAS::opencl_private) {
7689 Se.Diag(Loc: NewVD->getBeginLoc(), DiagID: diag::err_event_t_addr_space_qual);
7690 NewVD->setInvalidDecl();
7691 return false;
7692 }
7693 }
7694
7695 if (R->isSamplerT()) {
7696 // OpenCL v1.2 s6.9.b p4:
7697 // The sampler type cannot be used with the __local and __global address
7698 // space qualifiers.
7699 if (R.getAddressSpace() == LangAS::opencl_local ||
7700 R.getAddressSpace() == LangAS::opencl_global) {
7701 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wrong_sampler_addressspace);
7702 NewVD->setInvalidDecl();
7703 }
7704
7705 // OpenCL v1.2 s6.12.14.1:
7706 // A global sampler must be declared with either the constant address
7707 // space qualifier or with the const qualifier.
7708 if (DC->isTranslationUnit() &&
7709 !(R.getAddressSpace() == LangAS::opencl_constant ||
7710 R.isConstQualified())) {
7711 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_nonconst_global_sampler);
7712 NewVD->setInvalidDecl();
7713 }
7714 if (NewVD->isInvalidDecl())
7715 return false;
7716 }
7717
7718 return true;
7719}
7720
7721template <typename AttrTy>
7722static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7723 const TypedefNameDecl *TND = TT->getDecl();
7724 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7725 AttrTy *Clone = Attribute->clone(S.Context);
7726 Clone->setInherited(true);
7727 D->addAttr(A: Clone);
7728 }
7729}
7730
7731// This function emits warning and a corresponding note based on the
7732// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7733// declarations of an annotated type must be const qualified.
7734static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7735 QualType VarType = VD->getType().getCanonicalType();
7736
7737 // Ignore local declarations (for now) and those with const qualification.
7738 // TODO: Local variables should not be allowed if their type declaration has
7739 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7740 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7741 return;
7742
7743 if (VarType->isArrayType()) {
7744 // Retrieve element type for array declarations.
7745 VarType = S.getASTContext().getBaseElementType(QT: VarType);
7746 }
7747
7748 const RecordDecl *RD = VarType->getAsRecordDecl();
7749
7750 // Check if the record declaration is present and if it has any attributes.
7751 if (RD == nullptr)
7752 return;
7753
7754 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7755 S.Diag(Loc: VD->getLocation(), DiagID: diag::warn_var_decl_not_read_only) << RD;
7756 S.Diag(Loc: ConstDecl->getLocation(), DiagID: diag::note_enforce_read_only_placement);
7757 return;
7758 }
7759}
7760
7761void Sema::ProcessPragmaExport(DeclaratorDecl *NewD) {
7762 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7763 "NewD is not a function or variable");
7764
7765 if (PendingExportedNames.empty())
7766 return;
7767 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: NewD)) {
7768 if (getLangOpts().CPlusPlus && !FD->isExternC())
7769 return;
7770 }
7771 IdentifierInfo *IdentName = NewD->getIdentifier();
7772 if (IdentName == nullptr)
7773 return;
7774 auto PendingName = PendingExportedNames.find(Val: IdentName);
7775 if (PendingName != PendingExportedNames.end()) {
7776 auto &Label = PendingName->second;
7777 if (!Label.Used) {
7778 Label.Used = true;
7779 if (NewD->hasExternalFormalLinkage())
7780 mergeVisibilityType(D: NewD, Loc: Label.NameLoc, Type: VisibilityAttr::Default);
7781 else
7782 Diag(Loc: Label.NameLoc, DiagID: diag::warn_pragma_not_applied) << "export" << NewD;
7783 }
7784 }
7785}
7786
7787// Checks if VD is declared at global scope or with C language linkage.
7788static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7789 return Name.getAsIdentifierInfo() &&
7790 Name.getAsIdentifierInfo()->isStr(Str: "main") &&
7791 !VD->getDescribedVarTemplate() &&
7792 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7793 VD->isExternC());
7794}
7795
7796void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7797 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7798
7799 // Quickly return if the function does not have an `asm` attribute.
7800 if (E == nullptr)
7801 return;
7802
7803 // The parser guarantees this is a string.
7804 StringLiteral *SE = cast<StringLiteral>(Val: E);
7805 StringRef Label = SE->getString();
7806 QualType R = TInfo->getType();
7807 if (R->isIncompleteType())
7808 return;
7809 if (S->getFnParent() != nullptr) {
7810 switch (SC) {
7811 case SC_None:
7812 case SC_Auto:
7813 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_asm_label_on_auto_decl) << Label;
7814 break;
7815 case SC_Register:
7816 // Local Named register
7817 if (DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: getCurFunctionDecl())) {
7818 const auto &TI = Context.getTargetInfo();
7819 if (!TI.isValidGCCRegisterName(Name: Label))
7820 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7821 else if (!TI.validateLocalRegisterVariable(
7822 RegName: TI.getNormalizedGCCRegisterName(Name: Label,
7823 /*ReturnCanonical=*/true)))
7824 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_invalid_local_var_reg) << Label;
7825 }
7826 break;
7827 case SC_Static:
7828 case SC_Extern:
7829 case SC_PrivateExtern:
7830 break;
7831 }
7832 } else if (SC == SC_Register) {
7833 // Global Named register
7834 if (DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) {
7835 const auto &TI = Context.getTargetInfo();
7836 bool HasSizeMismatch;
7837
7838 if (!TI.isValidGCCRegisterName(Name: Label))
7839 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7840 else if (!TI.validateGlobalRegisterVariable(RegName: Label, RegSize: Context.getTypeSize(T: R),
7841 HasSizeMismatch))
7842 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_invalid_global_var_reg) << Label;
7843 else if (HasSizeMismatch)
7844 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_register_size_mismatch) << Label;
7845 }
7846
7847 if (!R->isIntegralType(Ctx: Context) && !R->isPointerType()) {
7848 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
7849 DiagID: diag::err_asm_unsupported_register_type)
7850 << TInfo->getTypeLoc().getSourceRange();
7851 NewVD->setInvalidDecl(true);
7852 }
7853 }
7854}
7855
7856NamedDecl *Sema::ActOnVariableDeclarator(
7857 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7858 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7859 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7860 QualType R = TInfo->getType();
7861 DeclarationName Name = GetNameForDeclarator(D).getName();
7862
7863 IdentifierInfo *II = Name.getAsIdentifierInfo();
7864 bool IsPlaceholderVariable = false;
7865
7866 if (D.isDecompositionDeclarator()) {
7867 // Take the name of the first declarator as our name for diagnostic
7868 // purposes.
7869 auto &Decomp = D.getDecompositionDeclarator();
7870 if (!Decomp.bindings().empty()) {
7871 II = Decomp.bindings()[0].Name;
7872 Name = II;
7873 }
7874 } else if (!II) {
7875 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_variable_name) << Name;
7876 return nullptr;
7877 }
7878
7879
7880 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7881 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS: D.getDeclSpec());
7882 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7883 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7884
7885 IsPlaceholderVariable = true;
7886
7887 if (!Previous.empty()) {
7888 NamedDecl *PrevDecl = *Previous.begin();
7889 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7890 DC: DC->getRedeclContext());
7891 if (SameDC && isDeclInScope(D: PrevDecl, Ctx: CurContext, S, AllowInlineNamespace: false)) {
7892 IsPlaceholderVariable = !isa<ParmVarDecl>(Val: PrevDecl);
7893 if (IsPlaceholderVariable)
7894 DiagPlaceholderVariableDefinition(Loc: D.getIdentifierLoc());
7895 }
7896 }
7897 }
7898
7899 // dllimport globals without explicit storage class are treated as extern. We
7900 // have to change the storage class this early to get the right DeclContext.
7901 if (SC == SC_None && !DC->isRecord() &&
7902 hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLImport) &&
7903 !hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLExport))
7904 SC = SC_Extern;
7905
7906 DeclContext *OriginalDC = DC;
7907 bool IsLocalExternDecl = SC == SC_Extern &&
7908 adjustContextForLocalExternDecl(DC);
7909
7910 if (SCSpec == DeclSpec::SCS_mutable) {
7911 // mutable can only appear on non-static class members, so it's always
7912 // an error here
7913 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_mutable_nonmember);
7914 D.setInvalidType();
7915 SC = SC_None;
7916 }
7917
7918 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7919 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7920 loc: D.getDeclSpec().getStorageClassSpecLoc())) {
7921 // In C++11, the 'register' storage class specifier is deprecated.
7922 // Suppress the warning in system macros, it's used in macros in some
7923 // popular C system headers, such as in glibc's htonl() macro.
7924 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7925 DiagID: getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7926 : diag::warn_deprecated_register)
7927 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7928 }
7929
7930 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
7931
7932 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7933 // C99 6.9p2: The storage-class specifiers auto and register shall not
7934 // appear in the declaration specifiers in an external declaration.
7935 // Global Register+Asm is a GNU extension we support.
7936 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7937 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_typecheck_sclass_fscope);
7938 D.setInvalidType();
7939 }
7940 }
7941
7942 // If this variable has a VLA type and an initializer, try to
7943 // fold to a constant-sized type. This is otherwise invalid.
7944 if (D.hasInitializer() && R->isVariableArrayType())
7945 tryToFixVariablyModifiedVarType(TInfo, T&: R, Loc: D.getIdentifierLoc(),
7946 /*DiagID=*/FailedFoldDiagID: 0);
7947
7948 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7949 const AutoType *AT = TL.getTypePtr();
7950 CheckConstrainedAuto(AutoT: AT, Loc: TL.getConceptNameLoc());
7951 }
7952
7953 bool IsMemberSpecialization = false;
7954 bool IsVariableTemplateSpecialization = false;
7955 bool IsPartialSpecialization = false;
7956 bool IsVariableTemplate = false;
7957 VarDecl *NewVD = nullptr;
7958 VarTemplateDecl *NewTemplate = nullptr;
7959 TemplateParameterList *TemplateParams = nullptr;
7960 if (!getLangOpts().CPlusPlus) {
7961 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
7962 Id: II, T: R, TInfo, S: SC);
7963
7964 if (R->getContainedDeducedType())
7965 ParsingInitForAutoVars.insert(Ptr: NewVD);
7966
7967 if (D.isInvalidType())
7968 NewVD->setInvalidDecl();
7969
7970 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7971 NewVD->hasLocalStorage())
7972 checkNonTrivialCUnion(QT: NewVD->getType(), Loc: NewVD->getLocation(),
7973 UseContext: NonTrivialCUnionContext::AutoVar, NonTrivialKind: NTCUK_Destruct);
7974 } else {
7975 bool Invalid = false;
7976 // Match up the template parameter lists with the scope specifier, then
7977 // determine whether we have a template or a template specialization.
7978 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7979 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
7980 SS: D.getCXXScopeSpec(),
7981 TemplateId: D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7982 ? D.getName().TemplateId
7983 : nullptr,
7984 ParamLists: TemplateParamLists,
7985 /*never a friend*/ IsFriend: false, IsMemberSpecialization, Invalid);
7986
7987 if (TemplateParams) {
7988 if (DC->isDependentContext()) {
7989 ContextRAII SavedContext(*this, DC);
7990 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
7991 Invalid = true;
7992 }
7993
7994 if (!TemplateParams->size() &&
7995 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7996 // There is an extraneous 'template<>' for this variable. Complain
7997 // about it, but allow the declaration of the variable.
7998 Diag(Loc: TemplateParams->getTemplateLoc(),
7999 DiagID: diag::err_template_variable_noparams)
8000 << II
8001 << SourceRange(TemplateParams->getTemplateLoc(),
8002 TemplateParams->getRAngleLoc());
8003 TemplateParams = nullptr;
8004 } else {
8005 // Check that we can declare a template here.
8006 if (CheckTemplateDeclScope(S, TemplateParams))
8007 return nullptr;
8008
8009 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8010 // This is an explicit specialization or a partial specialization.
8011 IsVariableTemplateSpecialization = true;
8012 IsPartialSpecialization = TemplateParams->size() > 0;
8013 } else { // if (TemplateParams->size() > 0)
8014 // This is a template declaration.
8015 IsVariableTemplate = true;
8016
8017 // Only C++1y supports variable templates (N3651).
8018 DiagCompat(Loc: D.getIdentifierLoc(), CompatDiagId: diag_compat::variable_template);
8019 }
8020 }
8021 } else {
8022 // Check that we can declare a member specialization here.
8023 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
8024 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
8025 return nullptr;
8026 assert((Invalid ||
8027 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
8028 "should have a 'template<>' for this decl");
8029 }
8030
8031 bool IsExplicitSpecialization =
8032 IsVariableTemplateSpecialization && !IsPartialSpecialization;
8033
8034 // C++ [temp.expl.spec]p2:
8035 // The declaration in an explicit-specialization shall not be an
8036 // export-declaration. An explicit specialization shall not use a
8037 // storage-class-specifier other than thread_local.
8038 //
8039 // We use the storage-class-specifier from DeclSpec because we may have
8040 // added implicit 'extern' for declarations with __declspec(dllimport)!
8041 if (SCSpec != DeclSpec::SCS_unspecified &&
8042 (IsExplicitSpecialization || IsMemberSpecialization)) {
8043 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8044 DiagID: diag::ext_explicit_specialization_storage_class)
8045 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8046 }
8047
8048 if (CurContext->isRecord()) {
8049 if (SC == SC_Static) {
8050 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
8051 // Walk up the enclosing DeclContexts to check for any that are
8052 // incompatible with static data members.
8053 const DeclContext *FunctionOrMethod = nullptr;
8054 const CXXRecordDecl *AnonStruct = nullptr;
8055 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
8056 if (Ctxt->isFunctionOrMethod()) {
8057 FunctionOrMethod = Ctxt;
8058 break;
8059 }
8060 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Val: Ctxt);
8061 if (ParentDecl && !ParentDecl->getDeclName()) {
8062 AnonStruct = ParentDecl;
8063 break;
8064 }
8065 }
8066 if (FunctionOrMethod) {
8067 // C++ [class.static.data]p5: A local class shall not have static
8068 // data members.
8069 Diag(Loc: D.getIdentifierLoc(),
8070 DiagID: diag::err_static_data_member_not_allowed_in_local_class)
8071 << Name << RD->getDeclName() << RD->getTagKind();
8072 Invalid = true;
8073 } else if (AnonStruct) {
8074 // C++ [class.static.data]p4: Unnamed classes and classes contained
8075 // directly or indirectly within unnamed classes shall not contain
8076 // static data members.
8077 Diag(Loc: D.getIdentifierLoc(),
8078 DiagID: diag::err_static_data_member_not_allowed_in_anon_struct)
8079 << Name << AnonStruct->getTagKind();
8080 Invalid = true;
8081 } else if (RD->isUnion()) {
8082 // C++98 [class.union]p1: If a union contains a static data member,
8083 // the program is ill-formed. C++11 drops this restriction.
8084 DiagCompat(Loc: D.getIdentifierLoc(),
8085 CompatDiagId: diag_compat::static_data_member_in_union)
8086 << Name;
8087 }
8088 }
8089 } else if (IsVariableTemplate || IsPartialSpecialization) {
8090 // There is no such thing as a member field template.
8091 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_member)
8092 << II << TemplateParams->getSourceRange();
8093 // Recover by pretending this is a static data member template.
8094 SC = SC_Static;
8095 }
8096 } else if (DC->isRecord()) {
8097 // This is an out-of-line definition of a static data member.
8098 switch (SC) {
8099 case SC_None:
8100 break;
8101 case SC_Static:
8102 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8103 DiagID: diag::err_static_out_of_line)
8104 << FixItHint::CreateRemoval(
8105 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8106 break;
8107 case SC_Auto:
8108 case SC_Register:
8109 case SC_Extern:
8110 // [dcl.stc] p2: The auto or register specifiers shall be applied only
8111 // to names of variables declared in a block or to function parameters.
8112 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
8113 // of class members
8114
8115 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8116 DiagID: diag::err_storage_class_for_static_member)
8117 << FixItHint::CreateRemoval(
8118 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8119 break;
8120 case SC_PrivateExtern:
8121 llvm_unreachable("C storage class in c++!");
8122 }
8123 }
8124
8125 if (IsVariableTemplateSpecialization) {
8126 SourceLocation TemplateKWLoc =
8127 TemplateParamLists.size() > 0
8128 ? TemplateParamLists[0]->getTemplateLoc()
8129 : SourceLocation();
8130 DeclResult Res = ActOnVarTemplateSpecialization(
8131 S, D, TSI: TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8132 IsPartialSpecialization);
8133 if (Res.isInvalid())
8134 return nullptr;
8135 NewVD = cast<VarDecl>(Val: Res.get());
8136 AddToScope = false;
8137 } else if (D.isDecompositionDeclarator()) {
8138 NewVD = DecompositionDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8139 LSquareLoc: D.getIdentifierLoc(), RSquareLoc: D.getEndLoc(), T: R,
8140 TInfo, S: SC, Bindings);
8141 } else
8142 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8143 IdLoc: D.getIdentifierLoc(), Id: II, T: R, TInfo, S: SC);
8144
8145 // If this is supposed to be a variable template, create it as such.
8146 if (IsVariableTemplate) {
8147 NewTemplate =
8148 VarTemplateDecl::Create(C&: Context, DC, L: D.getIdentifierLoc(), Name,
8149 Params: TemplateParams, Decl: NewVD);
8150 NewVD->setDescribedVarTemplate(NewTemplate);
8151 }
8152
8153 // If this decl has an auto type in need of deduction, make a note of the
8154 // Decl so we can diagnose uses of it in its own initializer.
8155 if (R->getContainedDeducedType())
8156 ParsingInitForAutoVars.insert(Ptr: NewVD);
8157
8158 if (D.isInvalidType() || Invalid) {
8159 NewVD->setInvalidDecl();
8160 if (NewTemplate)
8161 NewTemplate->setInvalidDecl();
8162 }
8163
8164 SetNestedNameSpecifier(S&: *this, DD: NewVD, D);
8165
8166 // If we have any template parameter lists that don't directly belong to
8167 // the variable (matching the scope specifier), store them.
8168 // An explicit variable template specialization does not own any template
8169 // parameter lists.
8170 unsigned VDTemplateParamLists =
8171 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8172 if (TemplateParamLists.size() > VDTemplateParamLists)
8173 NewVD->setTemplateParameterListsInfo(
8174 Context, TPLists: TemplateParamLists.drop_back(N: VDTemplateParamLists));
8175 }
8176
8177 if (D.getDeclSpec().isInlineSpecified()) {
8178 if (!getLangOpts().CPlusPlus) {
8179 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
8180 << 0;
8181 } else if (CurContext->isFunctionOrMethod()) {
8182 // 'inline' is not allowed on block scope variable declaration.
8183 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8184 DiagID: diag::err_inline_declaration_block_scope) << Name
8185 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
8186 } else {
8187 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8188 DiagID: getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8189 : diag::compat_pre_cxx17_inline_variable);
8190 NewVD->setInlineSpecified();
8191 }
8192 }
8193
8194 // Set the lexical context. If the declarator has a C++ scope specifier, the
8195 // lexical context will be different from the semantic context.
8196 NewVD->setLexicalDeclContext(CurContext);
8197 if (NewTemplate)
8198 NewTemplate->setLexicalDeclContext(CurContext);
8199
8200 if (IsLocalExternDecl) {
8201 if (D.isDecompositionDeclarator())
8202 for (auto *B : Bindings)
8203 B->setLocalExternDecl();
8204 else
8205 NewVD->setLocalExternDecl();
8206 }
8207
8208 bool EmitTLSUnsupportedError = false;
8209 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
8210 // C++11 [dcl.stc]p4:
8211 // When thread_local is applied to a variable of block scope the
8212 // storage-class-specifier static is implied if it does not appear
8213 // explicitly.
8214 // Core issue: 'static' is not implied if the variable is declared
8215 // 'extern'.
8216 if (NewVD->hasLocalStorage() &&
8217 (SCSpec != DeclSpec::SCS_unspecified ||
8218 TSCS != DeclSpec::TSCS_thread_local ||
8219 !DC->isFunctionOrMethod()))
8220 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8221 DiagID: diag::err_thread_non_global)
8222 << DeclSpec::getSpecifierName(S: TSCS);
8223 else if (!Context.getTargetInfo().isTLSSupported()) {
8224 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8225 // Postpone error emission until we've collected attributes required to
8226 // figure out whether it's a host or device variable and whether the
8227 // error should be ignored.
8228 EmitTLSUnsupportedError = true;
8229 // We still need to mark the variable as TLS so it shows up in AST with
8230 // proper storage class for other tools to use even if we're not going
8231 // to emit any code for it.
8232 NewVD->setTSCSpec(TSCS);
8233 } else
8234 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8235 DiagID: diag::err_thread_unsupported);
8236 } else
8237 NewVD->setTSCSpec(TSCS);
8238 }
8239
8240 switch (D.getDeclSpec().getConstexprSpecifier()) {
8241 case ConstexprSpecKind::Unspecified:
8242 break;
8243
8244 case ConstexprSpecKind::Consteval:
8245 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8246 DiagID: diag::err_constexpr_wrong_decl_kind)
8247 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8248 [[fallthrough]];
8249
8250 case ConstexprSpecKind::Constexpr:
8251 NewVD->setConstexpr(true);
8252 // C++1z [dcl.spec.constexpr]p1:
8253 // A static data member declared with the constexpr specifier is
8254 // implicitly an inline variable.
8255 if (NewVD->isStaticDataMember() &&
8256 (getLangOpts().CPlusPlus17 ||
8257 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8258 NewVD->setImplicitlyInline();
8259 break;
8260
8261 case ConstexprSpecKind::Constinit:
8262 if (!NewVD->hasGlobalStorage())
8263 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8264 DiagID: diag::err_constinit_local_variable);
8265 else
8266 NewVD->addAttr(
8267 A: ConstInitAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getConstexprSpecLoc(),
8268 S: ConstInitAttr::Keyword_constinit));
8269 break;
8270 }
8271
8272 // C99 6.7.4p3
8273 // An inline definition of a function with external linkage shall
8274 // not contain a definition of a modifiable object with static or
8275 // thread storage duration...
8276 // We only apply this when the function is required to be defined
8277 // elsewhere, i.e. when the function is not 'extern inline'. Note
8278 // that a local variable with thread storage duration still has to
8279 // be marked 'static'. Also note that it's possible to get these
8280 // semantics in C++ using __attribute__((gnu_inline)).
8281 if (SC == SC_Static && S->getFnParent() != nullptr &&
8282 !NewVD->getType().isConstQualified()) {
8283 FunctionDecl *CurFD = getCurFunctionDecl();
8284 if (CurFD && isFunctionDefinitionDiscarded(S&: *this, FD: CurFD)) {
8285 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8286 DiagID: diag::warn_static_local_in_extern_inline);
8287 MaybeSuggestAddingStaticToDecl(D: CurFD);
8288 }
8289 }
8290
8291 if (D.getDeclSpec().isModulePrivateSpecified()) {
8292 if (IsVariableTemplateSpecialization)
8293 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8294 << (IsPartialSpecialization ? 1 : 0)
8295 << FixItHint::CreateRemoval(
8296 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8297 else if (IsMemberSpecialization)
8298 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8299 << 2
8300 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8301 else if (NewVD->hasLocalStorage())
8302 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_local)
8303 << 0 << NewVD
8304 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8305 << FixItHint::CreateRemoval(
8306 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8307 else {
8308 NewVD->setModulePrivate();
8309 if (NewTemplate)
8310 NewTemplate->setModulePrivate();
8311 for (auto *B : Bindings)
8312 B->setModulePrivate();
8313 }
8314 }
8315
8316 if (getLangOpts().OpenCL) {
8317 deduceOpenCLAddressSpace(Var: NewVD);
8318
8319 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
8320 if (TSC != TSCS_unspecified) {
8321 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8322 DiagID: diag::err_opencl_unknown_type_specifier)
8323 << getLangOpts().getOpenCLVersionString()
8324 << DeclSpec::getSpecifierName(S: TSC) << 1;
8325 NewVD->setInvalidDecl();
8326 }
8327 }
8328
8329 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8330 // address space if the table has local storage (semantic checks elsewhere
8331 // will produce an error anyway).
8332 if (const auto *ATy = dyn_cast<ArrayType>(Val: NewVD->getType())) {
8333 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8334 !NewVD->hasLocalStorage()) {
8335 QualType Type = Context.getAddrSpaceQualType(
8336 T: NewVD->getType(), AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: 1));
8337 NewVD->setType(Type);
8338 }
8339 }
8340
8341 LoadExternalExtnameUndeclaredIdentifiers();
8342
8343 if (Expr *E = D.getAsmLabel()) {
8344 // The parser guarantees this is a string.
8345 StringLiteral *SE = cast<StringLiteral>(Val: E);
8346 StringRef Label = SE->getString();
8347
8348 // Insert the asm attribute.
8349 NewVD->addAttr(A: AsmLabelAttr::Create(Ctx&: Context, Label, Range: SE->getStrTokenLoc(TokNum: 0)));
8350 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8351 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8352 ExtnameUndeclaredIdentifiers.find(Key: NewVD->getIdentifier());
8353 if (I != ExtnameUndeclaredIdentifiers.end()) {
8354 if (isDeclExternC(D: NewVD)) {
8355 NewVD->addAttr(A: I->second);
8356 ExtnameUndeclaredIdentifiers.erase(Iterator: I);
8357 } else if (NewVD->getDeclContext()
8358 ->getRedeclContext()
8359 ->isTranslationUnit())
8360 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
8361 << /*Variable*/ 1 << NewVD;
8362 }
8363 }
8364
8365 // Handle attributes prior to checking for duplicates in MergeVarDecl
8366 ProcessDeclAttributes(S, D: NewVD, PD: D);
8367
8368 if (getLangOpts().HLSL)
8369 HLSL().ActOnVariableDeclarator(VD: NewVD);
8370
8371 if (getLangOpts().OpenACC)
8372 OpenACC().ActOnVariableDeclarator(VD: NewVD);
8373
8374 // FIXME: This is probably the wrong location to be doing this and we should
8375 // probably be doing this for more attributes (especially for function
8376 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8377 // the code to copy attributes would be generated by TableGen.
8378 if (R->isFunctionPointerType())
8379 if (const auto *TT = R->getAs<TypedefType>())
8380 copyAttrFromTypedefToDecl<AllocSizeAttr>(S&: *this, D: NewVD, TT);
8381
8382 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8383 if (EmitTLSUnsupportedError &&
8384 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) ||
8385 (getLangOpts().OpenMPIsTargetDevice &&
8386 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD: NewVD))))
8387 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8388 DiagID: diag::err_thread_unsupported);
8389
8390 if (EmitTLSUnsupportedError &&
8391 (LangOpts.SYCLIsDevice ||
8392 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8393 targetDiag(Loc: D.getIdentifierLoc(), DiagID: diag::err_thread_unsupported);
8394 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8395 // storage [duration]."
8396 if (SC == SC_None && S->getFnParent() != nullptr &&
8397 (NewVD->hasAttr<CUDASharedAttr>() ||
8398 NewVD->hasAttr<CUDAConstantAttr>())) {
8399 NewVD->setStorageClass(SC_Static);
8400 }
8401 }
8402
8403 // Ensure that dllimport globals without explicit storage class are treated as
8404 // extern. The storage class is set above using parsed attributes. Now we can
8405 // check the VarDecl itself.
8406 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8407 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8408 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8409
8410 // In auto-retain/release, infer strong retension for variables of
8411 // retainable type.
8412 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewVD))
8413 NewVD->setInvalidDecl();
8414
8415 // Check the ASM label here, as we need to know all other attributes of the
8416 // Decl first. Otherwise, we can't know if the asm label refers to the
8417 // host or device in a CUDA context. The device has other registers than
8418 // host and we must know where the function will be placed.
8419 CheckAsmLabel(S, E: D.getAsmLabel(), SC, TInfo, NewVD);
8420
8421 // Find the shadowed declaration before filtering for scope.
8422 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8423 ? getShadowedDeclaration(D: NewVD, R: Previous)
8424 : nullptr;
8425
8426 // Don't consider existing declarations that are in a different
8427 // scope and are out-of-semantic-context declarations (if the new
8428 // declaration has linkage).
8429 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(VD: NewVD),
8430 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
8431 IsMemberSpecialization ||
8432 IsVariableTemplateSpecialization);
8433
8434 // Check whether the previous declaration is in the same block scope. This
8435 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8436 if (getLangOpts().CPlusPlus &&
8437 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8438 NewVD->setPreviousDeclInSameBlockScope(
8439 Previous.isSingleResult() && !Previous.isShadowed() &&
8440 isDeclInScope(D: Previous.getFoundDecl(), Ctx: OriginalDC, S, AllowInlineNamespace: false));
8441
8442 if (!getLangOpts().CPlusPlus) {
8443 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8444 } else {
8445 // If this is an explicit specialization of a static data member, check it.
8446 if (IsMemberSpecialization && !IsVariableTemplate &&
8447 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8448 CheckMemberSpecialization(Member: NewVD, Previous))
8449 NewVD->setInvalidDecl();
8450
8451 // Merge the decl with the existing one if appropriate.
8452 if (!Previous.empty()) {
8453 if (Previous.isSingleResult() &&
8454 isa<FieldDecl>(Val: Previous.getFoundDecl()) &&
8455 D.getCXXScopeSpec().isSet()) {
8456 // The user tried to define a non-static data member
8457 // out-of-line (C++ [dcl.meaning]p1).
8458 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_nonstatic_member_out_of_line)
8459 << D.getCXXScopeSpec().getRange();
8460 Previous.clear();
8461 NewVD->setInvalidDecl();
8462 }
8463 } else if (D.getCXXScopeSpec().isSet() &&
8464 !IsVariableTemplateSpecialization) {
8465 // No previous declaration in the qualifying scope.
8466 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_no_member)
8467 << Name << computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext: true)
8468 << D.getCXXScopeSpec().getRange();
8469 NewVD->setInvalidDecl();
8470
8471 // if this is a member specialization, we don't have any primary template
8472 // to be instantiated from. We set ourselves to a 'fake' clone of this so
8473 // that anything that attempts to refer to this invalid declaration can
8474 // act as if there IS a primary instantiation.
8475 if (NewTemplate && IsMemberSpecialization) {
8476 VarDecl *FakeVD =
8477 VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
8478 Id: II, T: R, TInfo, S: SC);
8479 FakeVD->setInvalidDecl();
8480 VarTemplateDecl *FakeInstantiatedFrom = VarTemplateDecl::Create(
8481 C&: Context, DC, L: D.getIdentifierLoc(), Name, Params: TemplateParams, Decl: FakeVD);
8482 FakeInstantiatedFrom->setInvalidDecl();
8483 NewTemplate->setInstantiatedFromMemberTemplate(FakeInstantiatedFrom);
8484 }
8485 }
8486
8487 if (!IsPlaceholderVariable)
8488 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8489
8490 // CheckVariableDeclaration will set NewVD as invalid if something is in
8491 // error like WebAssembly tables being declared as arrays with a non-zero
8492 // size, but then parsing continues and emits further errors on that line.
8493 // To avoid that we check here if it happened and return nullptr.
8494 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8495 return nullptr;
8496
8497 if (NewTemplate) {
8498 VarTemplateDecl *PrevVarTemplate =
8499 NewVD->getPreviousDecl()
8500 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8501 : nullptr;
8502
8503 // Check the template parameter list of this declaration, possibly
8504 // merging in the template parameter list from the previous variable
8505 // template declaration.
8506 if (CheckTemplateParameterList(
8507 NewParams: TemplateParams,
8508 OldParams: PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8509 : nullptr,
8510 TPC: (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8511 DC->isDependentContext())
8512 ? TPC_ClassTemplateMember
8513 : TPC_Other))
8514 NewVD->setInvalidDecl();
8515 }
8516 }
8517
8518 if (IsMemberSpecialization) {
8519 if (NewTemplate && NewVD->getPreviousDecl()) {
8520 NewTemplate->setMemberSpecialization();
8521 } else if (IsPartialSpecialization) {
8522 cast<VarTemplatePartialSpecializationDecl>(Val: NewVD)
8523 ->setMemberSpecialization();
8524 }
8525 }
8526
8527 // Diagnose shadowed variables iff this isn't a redeclaration.
8528 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8529 CheckShadow(D: NewVD, ShadowedDecl, R: Previous);
8530
8531 ProcessPragmaWeak(S, D: NewVD);
8532 ProcessPragmaExport(NewD: NewVD);
8533
8534 // If this is the first declaration of an extern C variable, update
8535 // the map of such variables.
8536 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8537 isIncompleteDeclExternC(S&: *this, D: NewVD))
8538 RegisterLocallyScopedExternCDecl(ND: NewVD, S);
8539
8540 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8541 MangleNumberingContext *MCtx;
8542 Decl *ManglingContextDecl;
8543 std::tie(args&: MCtx, args&: ManglingContextDecl) =
8544 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
8545 if (MCtx) {
8546 Context.setManglingNumber(
8547 ND: NewVD, Number: MCtx->getManglingNumber(
8548 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
8549 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
8550 }
8551 }
8552
8553 // Special handling of variable named 'main'.
8554 if (!getLangOpts().Freestanding && isMainVar(Name, VD: NewVD)) {
8555 // C++ [basic.start.main]p3:
8556 // A program that declares
8557 // - a variable main at global scope, or
8558 // - an entity named main with C language linkage (in any namespace)
8559 // is ill-formed
8560 if (getLangOpts().CPlusPlus)
8561 Diag(Loc: D.getBeginLoc(), DiagID: diag::err_main_global_variable)
8562 << NewVD->isExternC();
8563
8564 // In C, and external-linkage variable named main results in undefined
8565 // behavior.
8566 else if (NewVD->hasExternalFormalLinkage())
8567 Diag(Loc: D.getBeginLoc(), DiagID: diag::warn_main_redefined);
8568 }
8569
8570 if (D.isRedeclaration() && !Previous.empty()) {
8571 NamedDecl *Prev = Previous.getRepresentativeDecl();
8572 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewVD, IsSpecialization: IsMemberSpecialization,
8573 IsDefinition: D.isFunctionDefinition());
8574 }
8575
8576 if (NewTemplate) {
8577 if (NewVD->isInvalidDecl())
8578 NewTemplate->setInvalidDecl();
8579 ActOnDocumentableDecl(D: NewTemplate);
8580 return NewTemplate;
8581 }
8582
8583 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8584 CompleteMemberSpecialization(Member: NewVD, Previous);
8585
8586 emitReadOnlyPlacementAttrWarning(S&: *this, VD: NewVD);
8587
8588 return NewVD;
8589}
8590
8591/// Enum describing the %select options in diag::warn_decl_shadow.
8592enum ShadowedDeclKind {
8593 SDK_Local,
8594 SDK_Global,
8595 SDK_StaticMember,
8596 SDK_Field,
8597 SDK_Typedef,
8598 SDK_Using,
8599 SDK_StructuredBinding
8600};
8601
8602/// Determine what kind of declaration we're shadowing.
8603static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8604 const DeclContext *OldDC) {
8605 if (isa<TypeAliasDecl>(Val: ShadowedDecl))
8606 return SDK_Using;
8607 else if (isa<TypedefDecl>(Val: ShadowedDecl))
8608 return SDK_Typedef;
8609 else if (isa<BindingDecl>(Val: ShadowedDecl))
8610 return SDK_StructuredBinding;
8611 else if (isa<RecordDecl>(Val: OldDC))
8612 return isa<FieldDecl>(Val: ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8613
8614 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8615}
8616
8617/// Return the location of the capture if the given lambda captures the given
8618/// variable \p VD, or an invalid source location otherwise.
8619static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8620 const ValueDecl *VD) {
8621 for (const Capture &Capture : LSI->Captures) {
8622 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8623 return Capture.getLocation();
8624 }
8625 return SourceLocation();
8626}
8627
8628static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8629 const LookupResult &R) {
8630 // Only diagnose if we're shadowing an unambiguous field or variable.
8631 if (R.getResultKind() != LookupResultKind::Found)
8632 return false;
8633
8634 // Return false if warning is ignored.
8635 return !Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: R.getNameLoc());
8636}
8637
8638NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8639 const LookupResult &R) {
8640 if (!shouldWarnIfShadowedDecl(Diags, R))
8641 return nullptr;
8642
8643 // Don't diagnose declarations at file scope.
8644 if (D->hasGlobalStorage() && !D->isStaticLocal())
8645 return nullptr;
8646
8647 NamedDecl *ShadowedDecl = R.getFoundDecl();
8648 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8649 : nullptr;
8650}
8651
8652NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8653 const LookupResult &R) {
8654 // Don't warn if typedef declaration is part of a class
8655 if (D->getDeclContext()->isRecord())
8656 return nullptr;
8657
8658 if (!shouldWarnIfShadowedDecl(Diags, R))
8659 return nullptr;
8660
8661 NamedDecl *ShadowedDecl = R.getFoundDecl();
8662 return isa<TypedefNameDecl>(Val: ShadowedDecl) ? ShadowedDecl : nullptr;
8663}
8664
8665NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8666 const LookupResult &R) {
8667 if (!shouldWarnIfShadowedDecl(Diags, R))
8668 return nullptr;
8669
8670 NamedDecl *ShadowedDecl = R.getFoundDecl();
8671 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8672 : nullptr;
8673}
8674
8675void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8676 const LookupResult &R) {
8677 DeclContext *NewDC = D->getDeclContext();
8678
8679 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ShadowedDecl)) {
8680 DeclContext *FnDC = getFunctionLevelDeclContext();
8681 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDC)) {
8682 // Fields aren't shadowed in C++ static members or in member functions
8683 // with an explicit object parameter.
8684 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8685 return;
8686 } else if (isa<FunctionDecl>(Val: FnDC)) {
8687 // A FunctionDecl here (not a CXXMethodDecl) can only be an
8688 // inline-defined friend function, since that's the only way to
8689 // introduce a non-member function inside a class body. Friends have
8690 // no implicit `this`, so nothing here can shadow a field.
8691 return;
8692 }
8693 // Fields shadowed by constructor parameters are a special case. Usually
8694 // the constructor initializes the field with the parameter.
8695 if (isa<CXXConstructorDecl>(Val: NewDC))
8696 if (const auto PVD = dyn_cast<ParmVarDecl>(Val: D)) {
8697 // Remember that this was shadowed so we can either warn about its
8698 // modification or its existence depending on warning settings.
8699 ShadowingDecls.insert(KV: {PVD->getCanonicalDecl(), FD});
8700 return;
8701 }
8702 }
8703
8704 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(Val: ShadowedDecl))
8705 if (shadowedVar->isExternC()) {
8706 // For shadowing external vars, make sure that we point to the global
8707 // declaration, not a locally scoped extern declaration.
8708 for (auto *I : shadowedVar->redecls())
8709 if (I->isFileVarDecl()) {
8710 ShadowedDecl = I;
8711 break;
8712 }
8713 }
8714
8715 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8716
8717 unsigned WarningDiag = diag::warn_decl_shadow;
8718 SourceLocation CaptureLoc;
8719 if (isa<VarDecl>(Val: D) && NewDC && isa<CXXMethodDecl>(Val: NewDC)) {
8720 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: NewDC->getParent())) {
8721 if (RD->isLambda() && OldDC->Encloses(DC: NewDC->getLexicalParent())) {
8722 // Handle both VarDecl and BindingDecl in lambda contexts
8723 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8724 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8725 const auto *LSI = cast<LambdaScopeInfo>(Val: getCurFunction());
8726 if (RD->getLambdaCaptureDefault() == LCD_None) {
8727 // Try to avoid warnings for lambdas with an explicit capture
8728 // list. Warn only when the lambda captures the shadowed decl
8729 // explicitly.
8730 CaptureLoc = getCaptureLocation(LSI, VD);
8731 if (CaptureLoc.isInvalid())
8732 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8733 } else {
8734 // Remember that this was shadowed so we can avoid the warning if
8735 // the shadowed decl isn't captured and the warning settings allow
8736 // it.
8737 cast<LambdaScopeInfo>(Val: getCurFunction())
8738 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: VD});
8739 return;
8740 }
8741 }
8742 if (isa<FieldDecl>(Val: ShadowedDecl)) {
8743 // If lambda can capture this, then emit default shadowing warning,
8744 // Otherwise it is not really a shadowing case since field is not
8745 // available in lambda's body.
8746 // At this point we don't know that lambda can capture this, so
8747 // remember that this was shadowed and delay until we know.
8748 cast<LambdaScopeInfo>(Val: getCurFunction())
8749 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: ShadowedDecl});
8750 return;
8751 }
8752 }
8753 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8754 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8755 bool HasLocalStorage = false;
8756 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl))
8757 HasLocalStorage = VD->hasLocalStorage();
8758 else if (const auto *BD = dyn_cast<BindingDecl>(Val: ShadowedDecl))
8759 HasLocalStorage =
8760 cast<VarDecl>(Val: BD->getDecomposedDecl())->hasLocalStorage();
8761
8762 if (HasLocalStorage) {
8763 // A variable can't shadow a local variable or binding in an enclosing
8764 // scope, if they are separated by a non-capturing declaration
8765 // context.
8766 for (DeclContext *ParentDC = NewDC;
8767 ParentDC && !ParentDC->Equals(DC: OldDC);
8768 ParentDC = getLambdaAwareParentOfDeclContext(DC: ParentDC)) {
8769 // Only block literals, captured statements, and lambda expressions
8770 // can capture; other scopes don't.
8771 if (!isa<BlockDecl>(Val: ParentDC) && !isa<CapturedDecl>(Val: ParentDC) &&
8772 !isLambdaCallOperator(DC: ParentDC))
8773 return;
8774 }
8775 }
8776 }
8777 }
8778 }
8779
8780 // Never warn about shadowing a placeholder variable.
8781 if (ShadowedDecl->isPlaceholderVar(LangOpts: getLangOpts()))
8782 return;
8783
8784 // Only warn about certain kinds of shadowing for class members.
8785 if (NewDC) {
8786 // In particular, don't warn about shadowing non-class members.
8787 if (NewDC->isRecord() && !OldDC->isRecord())
8788 return;
8789
8790 // Skip shadowing check if we're in a class scope, dealing with an enum
8791 // constant in a different context.
8792 DeclContext *ReDC = NewDC->getRedeclContext();
8793 if (ReDC->isRecord() && isa<EnumConstantDecl>(Val: D) && !OldDC->Equals(DC: ReDC))
8794 return;
8795
8796 // TODO: should we warn about static data members shadowing
8797 // static data members from base classes?
8798
8799 // TODO: don't diagnose for inaccessible shadowed members.
8800 // This is hard to do perfectly because we might friend the
8801 // shadowing context, but that's just a false negative.
8802 }
8803
8804 DeclarationName Name = R.getLookupName();
8805
8806 // Emit warning and note.
8807 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8808 Diag(Loc: R.getNameLoc(), DiagID: WarningDiag) << Name << Kind << OldDC;
8809 if (!CaptureLoc.isInvalid())
8810 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8811 << Name << /*explicitly*/ 1;
8812 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8813}
8814
8815void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8816 for (const auto &Shadow : LSI->ShadowingDecls) {
8817 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8818 // Try to avoid the warning when the shadowed decl isn't captured.
8819 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8820 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8821 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8822 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8823 Diag(Loc: Shadow.VD->getLocation(),
8824 DiagID: CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8825 : diag::warn_decl_shadow)
8826 << Shadow.VD->getDeclName()
8827 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8828 if (CaptureLoc.isValid())
8829 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8830 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8831 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8832 } else if (isa<FieldDecl>(Val: ShadowedDecl)) {
8833 Diag(Loc: Shadow.VD->getLocation(),
8834 DiagID: LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8835 : diag::warn_decl_shadow_uncaptured_local)
8836 << Shadow.VD->getDeclName()
8837 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8838 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8839 }
8840 }
8841}
8842
8843void Sema::CheckShadow(Scope *S, VarDecl *D) {
8844 if (Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: D->getLocation()))
8845 return;
8846
8847 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8848 Sema::LookupOrdinaryName,
8849 RedeclarationKind::ForVisibleRedeclaration);
8850 LookupName(R, S);
8851 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8852 CheckShadow(D, ShadowedDecl, R);
8853}
8854
8855/// Check if 'E', which is an expression that is about to be modified, refers
8856/// to a constructor parameter that shadows a field.
8857void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8858 // Quickly ignore expressions that can't be shadowing ctor parameters.
8859 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8860 return;
8861 E = E->IgnoreParenImpCasts();
8862 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
8863 if (!DRE)
8864 return;
8865 const NamedDecl *D = cast<NamedDecl>(Val: DRE->getDecl()->getCanonicalDecl());
8866 auto I = ShadowingDecls.find(Val: D);
8867 if (I == ShadowingDecls.end())
8868 return;
8869 const NamedDecl *ShadowedDecl = I->second;
8870 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8871 Diag(Loc, DiagID: diag::warn_modifying_shadowing_decl) << D << OldDC;
8872 Diag(Loc: D->getLocation(), DiagID: diag::note_var_declared_here) << D;
8873 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8874
8875 // Avoid issuing multiple warnings about the same decl.
8876 ShadowingDecls.erase(I);
8877}
8878
8879/// Check for conflict between this global or extern "C" declaration and
8880/// previous global or extern "C" declarations. This is only used in C++.
8881template<typename T>
8882static bool checkGlobalOrExternCConflict(
8883 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8884 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8885 NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName());
8886
8887 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8888 // The common case: this global doesn't conflict with any extern "C"
8889 // declaration.
8890 return false;
8891 }
8892
8893 if (Prev) {
8894 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8895 // Both the old and new declarations have C language linkage. This is a
8896 // redeclaration.
8897 Previous.clear();
8898 Previous.addDecl(D: Prev);
8899 return true;
8900 }
8901
8902 // This is a global, non-extern "C" declaration, and there is a previous
8903 // non-global extern "C" declaration. Diagnose if this is a variable
8904 // declaration.
8905 if (!isa<VarDecl>(ND))
8906 return false;
8907 } else {
8908 // The declaration is extern "C". Check for any declaration in the
8909 // translation unit which might conflict.
8910 if (IsGlobal) {
8911 // We have already performed the lookup into the translation unit.
8912 IsGlobal = false;
8913 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8914 I != E; ++I) {
8915 if (isa<VarDecl>(Val: *I)) {
8916 Prev = *I;
8917 break;
8918 }
8919 }
8920 } else {
8921 DeclContext::lookup_result R =
8922 S.Context.getTranslationUnitDecl()->lookup(Name: ND->getDeclName());
8923 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8924 I != E; ++I) {
8925 if (isa<VarDecl>(Val: *I)) {
8926 Prev = *I;
8927 break;
8928 }
8929 // FIXME: If we have any other entity with this name in global scope,
8930 // the declaration is ill-formed, but that is a defect: it breaks the
8931 // 'stat' hack, for instance. Only variables can have mangled name
8932 // clashes with extern "C" declarations, so only they deserve a
8933 // diagnostic.
8934 }
8935 }
8936
8937 if (!Prev)
8938 return false;
8939 }
8940
8941 // Use the first declaration's location to ensure we point at something which
8942 // is lexically inside an extern "C" linkage-spec.
8943 assert(Prev && "should have found a previous declaration to diagnose");
8944 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: Prev))
8945 Prev = FD->getFirstDecl();
8946 else
8947 Prev = cast<VarDecl>(Val: Prev)->getFirstDecl();
8948
8949 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8950 << IsGlobal << ND;
8951 S.Diag(Loc: Prev->getLocation(), DiagID: diag::note_extern_c_global_conflict)
8952 << IsGlobal;
8953 return false;
8954}
8955
8956/// Apply special rules for handling extern "C" declarations. Returns \c true
8957/// if we have found that this is a redeclaration of some prior entity.
8958///
8959/// Per C++ [dcl.link]p6:
8960/// Two declarations [for a function or variable] with C language linkage
8961/// with the same name that appear in different scopes refer to the same
8962/// [entity]. An entity with C language linkage shall not be declared with
8963/// the same name as an entity in global scope.
8964template<typename T>
8965static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8966 LookupResult &Previous) {
8967 if (!S.getLangOpts().CPlusPlus) {
8968 // In C, when declaring a global variable, look for a corresponding 'extern'
8969 // variable declared in function scope. We don't need this in C++, because
8970 // we find local extern decls in the surrounding file-scope DeclContext.
8971 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8972 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName())) {
8973 Previous.clear();
8974 Previous.addDecl(D: Prev);
8975 return true;
8976 }
8977 }
8978 return false;
8979 }
8980
8981 // A declaration in the translation unit can conflict with an extern "C"
8982 // declaration.
8983 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8984 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8985
8986 // An extern "C" declaration can conflict with a declaration in the
8987 // translation unit or can be a redeclaration of an extern "C" declaration
8988 // in another scope.
8989 if (isIncompleteDeclExternC(S,ND))
8990 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8991
8992 // Neither global nor extern "C": nothing to do.
8993 return false;
8994}
8995
8996static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8997 QualType T) {
8998 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8999 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
9000 // any of its members, even recursively, shall not have an atomic type, or a
9001 // variably modified type, or a type that is volatile or restrict qualified.
9002 if (CanonT->isVariablyModifiedType()) {
9003 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
9004 return true;
9005 }
9006
9007 // Arrays are qualified by their element type, so get the base type (this
9008 // works on non-arrays as well).
9009 CanonT = SemaRef.Context.getBaseElementType(QT: CanonT);
9010
9011 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
9012 CanonT.isRestrictQualified()) {
9013 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
9014 return true;
9015 }
9016
9017 if (CanonT->isRecordType()) {
9018 const RecordDecl *RD = CanonT->getAsRecordDecl();
9019 if (!RD->isInvalidDecl() &&
9020 llvm::any_of(Range: RD->fields(), P: [&SemaRef, VarLoc](const FieldDecl *F) {
9021 return CheckC23ConstexprVarType(SemaRef, VarLoc, T: F->getType());
9022 }))
9023 return true;
9024 }
9025
9026 return false;
9027}
9028
9029static bool isSYCLAddressSpace(LangAS AS) {
9030 return AS >= LangAS::sycl_global && AS <= LangAS::sycl_constant;
9031}
9032
9033void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
9034 // If the decl is already known invalid, don't check it.
9035 if (NewVD->isInvalidDecl())
9036 return;
9037
9038 QualType T = NewVD->getType();
9039
9040 // Defer checking an 'auto' type until its initializer is attached.
9041 if (T->isUndeducedType())
9042 return;
9043
9044 if (NewVD->hasAttrs())
9045 CheckAlignasUnderalignment(D: NewVD);
9046
9047 if (T->isObjCObjectType()) {
9048 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_statically_allocated_object)
9049 << FixItHint::CreateInsertion(InsertionLoc: NewVD->getLocation(), Code: "*");
9050 T = Context.getObjCObjectPointerType(OIT: T);
9051 NewVD->setType(T);
9052 }
9053
9054 // The top-level type of a variable declaration cannot have a SYCL address
9055 // space qualifier.
9056 if (getLangOpts().isSYCL()) {
9057 LangAS AS = Context.getBaseElementType(QT: T).getAddressSpace();
9058 if (isSYCLAddressSpace(AS)) {
9059 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sycl_address_space_qualified_object)
9060 << Qualifiers::getAddrSpaceAsString(AS);
9061 NewVD->setInvalidDecl();
9062 return;
9063 }
9064 }
9065
9066 // Emit an error if an address space was applied to decl with local storage.
9067 // This includes arrays of objects with address space qualifiers, but not
9068 // automatic variables that point to other address spaces.
9069 // ISO/IEC TR 18037 S5.1.2
9070 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
9071 T.getAddressSpace() != LangAS::Default) {
9072 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 0;
9073 NewVD->setInvalidDecl();
9074 return;
9075 }
9076
9077 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
9078 // scope.
9079 if (getLangOpts().OpenCLVersion == 120 &&
9080 !getOpenCLOptions().isAvailableOption(Ext: "cl_clang_storage_class_specifiers",
9081 LO: getLangOpts()) &&
9082 NewVD->isStaticLocal()) {
9083 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_static_function_scope);
9084 NewVD->setInvalidDecl();
9085 return;
9086 }
9087
9088 if (getLangOpts().OpenCL) {
9089 if (!diagnoseOpenCLTypes(Se&: *this, NewVD))
9090 return;
9091
9092 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
9093 if (NewVD->hasAttr<BlocksAttr>()) {
9094 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_block_storage_type);
9095 return;
9096 }
9097
9098 if (T->isBlockPointerType()) {
9099 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
9100 // can't use 'extern' storage class.
9101 if (!T.isConstQualified()) {
9102 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
9103 << 0 /*const*/;
9104 NewVD->setInvalidDecl();
9105 return;
9106 }
9107 if (NewVD->hasExternalStorage()) {
9108 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_extern_block_declaration);
9109 NewVD->setInvalidDecl();
9110 return;
9111 }
9112 }
9113
9114 // FIXME: Adding local AS in C++ for OpenCL might make sense.
9115 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
9116 NewVD->hasExternalStorage()) {
9117 if (!T->isSamplerT() && !T->isDependentType() &&
9118 !(T.getAddressSpace() == LangAS::opencl_constant ||
9119 (T.getAddressSpace() == LangAS::opencl_global &&
9120 getOpenCLOptions().areProgramScopeVariablesSupported(
9121 Opts: getLangOpts())))) {
9122 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
9123 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()))
9124 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
9125 << Scope << "global or constant";
9126 else
9127 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
9128 << Scope << "constant";
9129 NewVD->setInvalidDecl();
9130 return;
9131 }
9132 } else {
9133 if (T.getAddressSpace() == LangAS::opencl_global) {
9134 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9135 << 1 /*is any function*/ << "global";
9136 NewVD->setInvalidDecl();
9137 return;
9138 }
9139 // When this extension is enabled, 'local' variables are permitted in
9140 // non-kernel functions and within nested scopes of kernel functions,
9141 // bypassing standard OpenCL address space restrictions.
9142 bool AllowFunctionScopeLocalVariables =
9143 T.getAddressSpace() == LangAS::opencl_local &&
9144 getOpenCLOptions().isAvailableOption(
9145 Ext: "__cl_clang_function_scope_local_variables", LO: getLangOpts());
9146 if (AllowFunctionScopeLocalVariables) {
9147 // Direct pass: No further diagnostics needed for this specific case.
9148 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
9149 T.getAddressSpace() == LangAS::opencl_local) {
9150 FunctionDecl *FD = getCurFunctionDecl();
9151 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
9152 // in functions.
9153 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
9154 if (T.getAddressSpace() == LangAS::opencl_constant)
9155 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9156 << 0 /*non-kernel only*/ << "constant";
9157 else
9158 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9159 << 0 /*non-kernel only*/ << "local";
9160 NewVD->setInvalidDecl();
9161 return;
9162 }
9163 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9164 // in the outermost scope of a kernel function.
9165 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9166 if (!getCurScope()->isFunctionScope()) {
9167 if (T.getAddressSpace() == LangAS::opencl_constant)
9168 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9169 << "constant";
9170 else
9171 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9172 << "local";
9173 NewVD->setInvalidDecl();
9174 return;
9175 }
9176 }
9177 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9178 // If we are parsing a template we didn't deduce an addr
9179 // space yet.
9180 T.getAddressSpace() != LangAS::Default) {
9181 // Do not allow other address spaces on automatic variable.
9182 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 1;
9183 NewVD->setInvalidDecl();
9184 return;
9185 }
9186 }
9187 }
9188
9189 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9190 && !NewVD->hasAttr<BlocksAttr>()) {
9191 if (getLangOpts().getGC() != LangOptions::NonGC)
9192 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_gc_attribute_weak_on_local);
9193 else {
9194 assert(!getLangOpts().ObjCAutoRefCount);
9195 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_attribute_weak_on_local);
9196 }
9197 }
9198
9199 // WebAssembly tables must be static with a zero length and can't be
9200 // declared within functions.
9201 if (T->isWebAssemblyTableType()) {
9202 if (getCurScope()->getParent()) { // Parent is null at top-level
9203 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_in_function);
9204 NewVD->setInvalidDecl();
9205 return;
9206 }
9207 if (NewVD->getStorageClass() != SC_Static) {
9208 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_must_be_static);
9209 NewVD->setInvalidDecl();
9210 return;
9211 }
9212 const auto *ATy = dyn_cast<ConstantArrayType>(Val: T.getTypePtr());
9213 if (!ATy || ATy->getZExtSize() != 0) {
9214 Diag(Loc: NewVD->getLocation(),
9215 DiagID: diag::err_typecheck_wasm_table_must_have_zero_length);
9216 NewVD->setInvalidDecl();
9217 return;
9218 }
9219 }
9220
9221 // zero sized static arrays are not allowed in HIP device functions
9222 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9223 if (FunctionDecl *FD = getCurFunctionDecl();
9224 FD &&
9225 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9226 if (const ConstantArrayType *ArrayT =
9227 getASTContext().getAsConstantArrayType(T);
9228 ArrayT && ArrayT->isZeroSize()) {
9229 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_zero_array_size) << 2;
9230 }
9231 }
9232 }
9233
9234 bool isVM = T->isVariablyModifiedType();
9235 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9236 NewVD->hasAttr<BlocksAttr>())
9237 setFunctionHasBranchProtectedScope();
9238
9239 if ((isVM && NewVD->hasLinkage()) ||
9240 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9241 bool SizeIsNegative;
9242 llvm::APSInt Oversized;
9243 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
9244 TInfo: NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9245 QualType FixedT;
9246 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9247 FixedT = FixedTInfo->getType();
9248 else if (FixedTInfo) {
9249 // Type and type-as-written are canonically different. We need to fix up
9250 // both types separately.
9251 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9252 Oversized);
9253 }
9254 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9255 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9256 // FIXME: This won't give the correct result for
9257 // int a[10][n];
9258 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9259
9260 if (NewVD->isFileVarDecl())
9261 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope)
9262 << SizeRange;
9263 else if (NewVD->isStaticLocal())
9264 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_static_storage)
9265 << SizeRange;
9266 else
9267 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_extern_linkage)
9268 << SizeRange;
9269 NewVD->setInvalidDecl();
9270 return;
9271 }
9272
9273 if (!FixedTInfo) {
9274 if (NewVD->isFileVarDecl())
9275 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
9276 else
9277 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_has_extern_linkage);
9278 NewVD->setInvalidDecl();
9279 return;
9280 }
9281
9282 Diag(Loc: NewVD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
9283 NewVD->setType(FixedT);
9284 NewVD->setTypeSourceInfo(FixedTInfo);
9285 }
9286
9287 if (T->isVoidType()) {
9288 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9289 // of objects and functions.
9290 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
9291 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
9292 << T;
9293 NewVD->setInvalidDecl();
9294 return;
9295 }
9296 }
9297
9298 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9299 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9300 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sizeless_nonlocal) << T;
9301 NewVD->setInvalidDecl();
9302 return;
9303 }
9304
9305 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9306 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_not_allowed_on)
9307 << diag::NotAllowedBlockVarReason::VariablyModifiedType;
9308 NewVD->setInvalidDecl();
9309 return;
9310 }
9311
9312 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9313 CheckC23ConstexprVarType(SemaRef&: *this, VarLoc: NewVD->getLocation(), T)) {
9314 NewVD->setInvalidDecl();
9315 return;
9316 }
9317
9318 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9319 !T->isDependentType() &&
9320 RequireLiteralType(Loc: NewVD->getLocation(), T,
9321 DiagID: diag::err_constexpr_var_non_literal)) {
9322 NewVD->setInvalidDecl();
9323 return;
9324 }
9325
9326 // PPC MMA non-pointer types are not allowed as non-local variable types.
9327 if (Context.getTargetInfo().getTriple().isPPC64() &&
9328 !NewVD->isLocalVarDecl() &&
9329 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewVD->getLocation())) {
9330 NewVD->setInvalidDecl();
9331 return;
9332 }
9333
9334 // Check that SVE types are only used in functions with SVE available.
9335 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9336 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9337 llvm::StringMap<bool> CallerFeatureMap;
9338 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9339 if (ARM().checkSVETypeSupport(Ty: T, Loc: NewVD->getLocation(), FD,
9340 FeatureMap: CallerFeatureMap)) {
9341 NewVD->setInvalidDecl();
9342 return;
9343 }
9344 }
9345
9346 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9347 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9348 llvm::StringMap<bool> CallerFeatureMap;
9349 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9350 RISCV().checkRVVTypeSupport(Ty: T, Loc: NewVD->getLocation(), D: cast<Decl>(Val: CurContext),
9351 FeatureMap: CallerFeatureMap);
9352 }
9353
9354 if (Context.getTargetInfo().hasAMDGPUTypes()) {
9355 if (!AMDGPU().checkAMDGPUTypeSupport(Ty: T, Loc: NewVD->getLocation())) {
9356 NewVD->setInvalidDecl();
9357 return;
9358 }
9359 }
9360
9361 if (T.hasAddressSpace() &&
9362 !CheckVarDeclSizeAddressSpace(VD: NewVD, AS: T.getAddressSpace())) {
9363 NewVD->setInvalidDecl();
9364 return;
9365 }
9366}
9367
9368bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
9369 CheckVariableDeclarationType(NewVD);
9370
9371 // If the decl is already known invalid, don't check it.
9372 if (NewVD->isInvalidDecl())
9373 return false;
9374
9375 // If we did not find anything by this name, look for a non-visible
9376 // extern "C" declaration with the same name.
9377 if (Previous.empty() &&
9378 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewVD, Previous))
9379 Previous.setShadowed();
9380
9381 if (!Previous.empty()) {
9382 MergeVarDecl(New: NewVD, Previous);
9383 return true;
9384 }
9385 return false;
9386}
9387
9388bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
9389 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
9390
9391 // Look for methods in base classes that this method might override.
9392 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9393 /*DetectVirtual=*/false);
9394 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9395 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9396 DeclarationName Name = MD->getDeclName();
9397
9398 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9399 // We really want to find the base class destructor here.
9400 Name = Context.DeclarationNames.getCXXDestructorName(
9401 Ty: Context.getCanonicalTagType(TD: BaseRecord));
9402 }
9403
9404 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9405 CXXMethodDecl *BaseMD =
9406 dyn_cast<CXXMethodDecl>(Val: BaseND->getCanonicalDecl());
9407 if (!BaseMD || !BaseMD->isVirtual() ||
9408 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9409 /*ConsiderCudaAttrs=*/true))
9410 continue;
9411 if (!CheckExplicitObjectOverride(New: MD, Old: BaseMD))
9412 continue;
9413 if (Overridden.insert(Ptr: BaseMD).second) {
9414 MD->addOverriddenMethod(MD: BaseMD);
9415 CheckOverridingFunctionReturnType(New: MD, Old: BaseMD);
9416 CheckOverridingFunctionAttributes(New: MD, Old: BaseMD);
9417 CheckOverridingFunctionExceptionSpec(New: MD, Old: BaseMD);
9418 CheckIfOverriddenFunctionIsMarkedFinal(New: MD, Old: BaseMD);
9419 }
9420
9421 // A method can only override one function from each base class. We
9422 // don't track indirectly overridden methods from bases of bases.
9423 return true;
9424 }
9425
9426 return false;
9427 };
9428
9429 DC->lookupInBases(BaseMatches: VisitBase, Paths);
9430 return !Overridden.empty();
9431}
9432
9433namespace {
9434 // Struct for holding all of the extra arguments needed by
9435 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9436 struct ActOnFDArgs {
9437 Scope *S;
9438 Declarator &D;
9439 MultiTemplateParamsArg TemplateParamLists;
9440 bool AddToScope;
9441 };
9442} // end anonymous namespace
9443
9444namespace {
9445
9446// Callback to only accept typo corrections that have a non-zero edit distance.
9447// Also only accept corrections that have the same parent decl.
9448class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9449 public:
9450 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9451 CXXRecordDecl *Parent)
9452 : Context(Context), OriginalFD(TypoFD),
9453 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9454
9455 bool ValidateCandidate(const TypoCorrection &candidate) override {
9456 if (candidate.getEditDistance() == 0)
9457 return false;
9458
9459 SmallVector<unsigned, 1> MismatchedParams;
9460 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9461 CDeclEnd = candidate.end();
9462 CDecl != CDeclEnd; ++CDecl) {
9463 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9464
9465 if (FD && !FD->hasBody() &&
9466 hasSimilarParameters(Context, Declaration: FD, Definition: OriginalFD, Params&: MismatchedParams)) {
9467 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
9468 CXXRecordDecl *Parent = MD->getParent();
9469 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9470 return true;
9471 } else if (!ExpectedParent) {
9472 return true;
9473 }
9474 }
9475 }
9476
9477 return false;
9478 }
9479
9480 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9481 return std::make_unique<DifferentNameValidatorCCC>(args&: *this);
9482 }
9483
9484 private:
9485 ASTContext &Context;
9486 FunctionDecl *OriginalFD;
9487 CXXRecordDecl *ExpectedParent;
9488};
9489
9490} // end anonymous namespace
9491
9492void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9493 TypoCorrectedFunctionDefinitions.insert(Ptr: F);
9494}
9495
9496/// Generate diagnostics for an invalid function redeclaration.
9497///
9498/// This routine handles generating the diagnostic messages for an invalid
9499/// function redeclaration, including finding possible similar declarations
9500/// or performing typo correction if there are no previous declarations with
9501/// the same name.
9502///
9503/// Returns a NamedDecl iff typo correction was performed and substituting in
9504/// the new declaration name does not cause new errors.
9505static NamedDecl *DiagnoseInvalidRedeclaration(
9506 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9507 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9508 DeclarationName Name = NewFD->getDeclName();
9509 DeclContext *NewDC = NewFD->getDeclContext();
9510 SmallVector<unsigned, 1> MismatchedParams;
9511 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9512 TypoCorrection Correction;
9513 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9514 unsigned DiagMsg =
9515 IsLocalFriend ? diag::err_no_matching_local_friend :
9516 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9517 diag::err_member_decl_does_not_match;
9518 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9519 IsLocalFriend ? Sema::LookupLocalFriendName
9520 : Sema::LookupOrdinaryName,
9521 RedeclarationKind::ForVisibleRedeclaration);
9522
9523 NewFD->setInvalidDecl();
9524 if (IsLocalFriend)
9525 SemaRef.LookupName(R&: Prev, S);
9526 else
9527 SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: NewDC);
9528 assert(!Prev.isAmbiguous() &&
9529 "Cannot have an ambiguity in previous-declaration lookup");
9530 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9531 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9532 MD ? MD->getParent() : nullptr);
9533 if (!Prev.empty()) {
9534 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9535 Func != FuncEnd; ++Func) {
9536 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *Func);
9537 if (FD &&
9538 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9539 // Add 1 to the index so that 0 can mean the mismatch didn't
9540 // involve a parameter
9541 unsigned ParamNum =
9542 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9543 NearMatches.push_back(Elt: std::make_pair(x&: FD, y&: ParamNum));
9544 }
9545 }
9546 // If the qualified name lookup yielded nothing, try typo correction
9547 } else if ((Correction = SemaRef.CorrectTypo(
9548 Typo: Prev.getLookupNameInfo(), LookupKind: Prev.getLookupKind(), S,
9549 SS: &ExtraArgs.D.getCXXScopeSpec(), CCC,
9550 Mode: CorrectTypoKind::ErrorRecovery,
9551 MemberContext: IsLocalFriend ? nullptr : NewDC))) {
9552 // Set up everything for the call to ActOnFunctionDeclarator
9553 ExtraArgs.D.SetIdentifier(Id: Correction.getCorrectionAsIdentifierInfo(),
9554 IdLoc: ExtraArgs.D.getIdentifierLoc());
9555 Previous.clear();
9556 Previous.setLookupName(Correction.getCorrection());
9557 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9558 CDeclEnd = Correction.end();
9559 CDecl != CDeclEnd; ++CDecl) {
9560 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9561 if (FD && !FD->hasBody() &&
9562 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9563 Previous.addDecl(D: FD);
9564 }
9565 }
9566 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9567
9568 NamedDecl *Result;
9569 // Retry building the function declaration with the new previous
9570 // declarations, and with errors suppressed.
9571 {
9572 // Trap errors.
9573 Sema::SFINAETrap Trap(SemaRef);
9574
9575 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9576 // pieces need to verify the typo-corrected C++ declaration and hopefully
9577 // eliminate the need for the parameter pack ExtraArgs.
9578 Result = SemaRef.ActOnFunctionDeclarator(
9579 S: ExtraArgs.S, D&: ExtraArgs.D,
9580 DC: Correction.getCorrectionDecl()->getDeclContext(),
9581 TInfo: NewFD->getTypeSourceInfo(), Previous, TemplateParamLists: ExtraArgs.TemplateParamLists,
9582 AddToScope&: ExtraArgs.AddToScope);
9583
9584 if (Trap.hasErrorOccurred())
9585 Result = nullptr;
9586 }
9587
9588 if (Result) {
9589 // Determine which correction we picked.
9590 Decl *Canonical = Result->getCanonicalDecl();
9591 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9592 I != E; ++I)
9593 if ((*I)->getCanonicalDecl() == Canonical)
9594 Correction.setCorrectionDecl(*I);
9595
9596 // Let Sema know about the correction.
9597 SemaRef.MarkTypoCorrectedFunctionDefinition(F: Result);
9598 SemaRef.diagnoseTypo(
9599 Correction,
9600 TypoDiag: SemaRef.PDiag(DiagID: IsLocalFriend
9601 ? diag::err_no_matching_local_friend_suggest
9602 : diag::err_member_decl_does_not_match_suggest)
9603 << Name << NewDC << IsDefinition);
9604 return Result;
9605 }
9606
9607 // Pretend the typo correction never occurred
9608 ExtraArgs.D.SetIdentifier(Id: Name.getAsIdentifierInfo(),
9609 IdLoc: ExtraArgs.D.getIdentifierLoc());
9610 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9611 Previous.clear();
9612 Previous.setLookupName(Name);
9613 }
9614
9615 SemaRef.Diag(Loc: NewFD->getLocation(), DiagID: DiagMsg)
9616 << Name << NewDC << IsDefinition << NewFD->getLocation();
9617
9618 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9619 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9620 CXXRecordDecl *RD = NewMD->getParent();
9621 SemaRef.Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here)
9622 << RD->getName() << RD->getLocation();
9623 }
9624
9625 bool NewFDisConst = NewMD && NewMD->isConst();
9626
9627 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9628 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9629 NearMatch != NearMatchEnd; ++NearMatch) {
9630 FunctionDecl *FD = NearMatch->first;
9631 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
9632 bool FDisConst = MD && MD->isConst();
9633 bool IsMember = MD || !IsLocalFriend;
9634
9635 // FIXME: These notes are poorly worded for the local friend case.
9636 if (unsigned Idx = NearMatch->second) {
9637 ParmVarDecl *FDParam = FD->getParamDecl(i: Idx-1);
9638 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9639 if (Loc.isInvalid()) Loc = FD->getLocation();
9640 SemaRef.Diag(Loc, DiagID: IsMember ? diag::note_member_def_close_param_match
9641 : diag::note_local_decl_close_param_match)
9642 << Idx << FDParam->getType()
9643 << NewFD->getParamDecl(i: Idx - 1)->getType();
9644 } else if (FDisConst != NewFDisConst) {
9645 auto DB = SemaRef.Diag(Loc: FD->getLocation(),
9646 DiagID: diag::note_member_def_close_const_match)
9647 << NewFDisConst << FD->getSourceRange().getEnd();
9648 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9649 DB << FixItHint::CreateInsertion(InsertionLoc: FTI.getRParenLoc().getLocWithOffset(Offset: 1),
9650 Code: " const");
9651 else if (FTI.hasMethodTypeQualifiers() &&
9652 FTI.getConstQualifierLoc().isValid())
9653 DB << FixItHint::CreateRemoval(RemoveRange: FTI.getConstQualifierLoc());
9654 } else {
9655 SemaRef.Diag(Loc: FD->getLocation(),
9656 DiagID: IsMember ? diag::note_member_def_close_match
9657 : diag::note_local_decl_close_match);
9658 }
9659 }
9660 return nullptr;
9661}
9662
9663static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9664 switch (D.getDeclSpec().getStorageClassSpec()) {
9665 default: llvm_unreachable("Unknown storage class!");
9666 case DeclSpec::SCS_auto:
9667 case DeclSpec::SCS_register:
9668 case DeclSpec::SCS_mutable:
9669 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9670 DiagID: diag::err_typecheck_sclass_func);
9671 D.getMutableDeclSpec().ClearStorageClassSpecs();
9672 D.setInvalidType();
9673 break;
9674 case DeclSpec::SCS_unspecified: break;
9675 case DeclSpec::SCS_extern:
9676 if (D.getDeclSpec().isExternInLinkageSpec())
9677 return SC_None;
9678 return SC_Extern;
9679 case DeclSpec::SCS_static: {
9680 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9681 // C99 6.7.1p5:
9682 // The declaration of an identifier for a function that has
9683 // block scope shall have no explicit storage-class specifier
9684 // other than extern
9685 // See also (C++ [dcl.stc]p4).
9686 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9687 DiagID: diag::err_static_block_func);
9688 break;
9689 } else
9690 return SC_Static;
9691 }
9692 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9693 }
9694
9695 // No explicit storage class has already been returned
9696 return SC_None;
9697}
9698
9699static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9700 DeclContext *DC, QualType &R,
9701 TypeSourceInfo *TInfo,
9702 StorageClass SC,
9703 bool &IsVirtualOkay) {
9704 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9705 DeclarationName Name = NameInfo.getName();
9706
9707 FunctionDecl *NewFD = nullptr;
9708 bool isInline = D.getDeclSpec().isInlineSpecified();
9709
9710 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9711 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9712 (SemaRef.getLangOpts().C23 &&
9713 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9714
9715 if (SemaRef.getLangOpts().C23)
9716 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9717 DiagID: diag::err_c23_constexpr_not_variable);
9718 else
9719 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9720 DiagID: diag::err_constexpr_wrong_decl_kind)
9721 << static_cast<int>(ConstexprKind);
9722 ConstexprKind = ConstexprSpecKind::Unspecified;
9723 D.getMutableDeclSpec().ClearConstexprSpec();
9724 }
9725
9726 if (!SemaRef.getLangOpts().CPlusPlus) {
9727 // Determine whether the function was written with a prototype. This is
9728 // true when:
9729 // - there is a prototype in the declarator, or
9730 // - the type R of the function is some kind of typedef or other non-
9731 // attributed reference to a type name (which eventually refers to a
9732 // function type). Note, we can't always look at the adjusted type to
9733 // check this case because attributes may cause a non-function
9734 // declarator to still have a function type. e.g.,
9735 // typedef void func(int a);
9736 // __attribute__((noreturn)) func other_func; // This has a prototype
9737 bool HasPrototype =
9738 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9739 (D.getDeclSpec().isTypeRep() &&
9740 SemaRef.GetTypeFromParser(Ty: D.getDeclSpec().getRepAsType(), TInfo: nullptr)
9741 ->isFunctionProtoType()) ||
9742 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9743 assert(
9744 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9745 "Strict prototypes are required");
9746
9747 NewFD = FunctionDecl::Create(
9748 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9749 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline, hasWrittenPrototype: HasPrototype,
9750 ConstexprKind: ConstexprSpecKind::Unspecified,
9751 /*TrailingRequiresClause=*/{});
9752 if (D.isInvalidType())
9753 NewFD->setInvalidDecl();
9754
9755 return NewFD;
9756 }
9757
9758 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9759 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9760
9761 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9762
9763 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9764 // This is a C++ constructor declaration.
9765 assert(DC->isRecord() &&
9766 "Constructors can only be declared in a member context");
9767
9768 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9769 return CXXConstructorDecl::Create(
9770 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9771 TInfo, ES: ExplicitSpecifier, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(),
9772 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9773 Inherited: InheritedConstructor(), TrailingRequiresClause);
9774
9775 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9776 // This is a C++ destructor declaration.
9777 if (DC->isRecord()) {
9778 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9779 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC);
9780 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9781 C&: SemaRef.Context, RD: Record, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo,
9782 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9783 /*isImplicitlyDeclared=*/false, ConstexprKind,
9784 TrailingRequiresClause);
9785 // User defined destructors start as not selected if the class definition is still
9786 // not done.
9787 if (Record->isBeingDefined())
9788 NewDD->setIneligibleOrNotSelected(true);
9789
9790 // If the destructor needs an implicit exception specification, set it
9791 // now. FIXME: It'd be nice to be able to create the right type to start
9792 // with, but the type needs to reference the destructor declaration.
9793 if (SemaRef.getLangOpts().CPlusPlus11)
9794 SemaRef.AdjustDestructorExceptionSpec(Destructor: NewDD);
9795
9796 IsVirtualOkay = true;
9797 return NewDD;
9798
9799 } else {
9800 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_not_member);
9801 D.setInvalidType();
9802
9803 // Create a FunctionDecl to satisfy the function definition parsing
9804 // code path.
9805 return FunctionDecl::Create(
9806 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NLoc: D.getIdentifierLoc(), N: Name, T: R,
9807 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9808 /*hasPrototype=*/hasWrittenPrototype: true, ConstexprKind, TrailingRequiresClause);
9809 }
9810
9811 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9812 if (!DC->isRecord()) {
9813 SemaRef.Diag(Loc: D.getIdentifierLoc(),
9814 DiagID: diag::err_conv_function_not_member);
9815 return nullptr;
9816 }
9817
9818 SemaRef.CheckConversionDeclarator(D, R, SC);
9819 if (D.isInvalidType())
9820 return nullptr;
9821
9822 IsVirtualOkay = true;
9823 return CXXConversionDecl::Create(
9824 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9825 TInfo, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9826 ES: ExplicitSpecifier, ConstexprKind, EndLocation: SourceLocation(),
9827 TrailingRequiresClause);
9828
9829 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9830 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9831 return nullptr;
9832 return CXXDeductionGuideDecl::Create(
9833 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), ES: ExplicitSpecifier, NameInfo, T: R,
9834 TInfo, EndLocation: D.getEndLoc(), /*Ctor=*/nullptr,
9835 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9836 } else if (DC->isRecord()) {
9837 // If the name of the function is the same as the name of the record,
9838 // then this must be an invalid constructor that has a return type.
9839 // (The parser checks for a return type and makes the declarator a
9840 // constructor if it has no return type).
9841 if (Name.getAsIdentifierInfo() &&
9842 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(Val: DC)->getIdentifier()){
9843 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_return_type)
9844 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9845 << SourceRange(D.getIdentifierLoc());
9846 return nullptr;
9847 }
9848
9849 // This is a C++ method declaration.
9850 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9851 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9852 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9853 ConstexprKind, EndLocation: SourceLocation(), TrailingRequiresClause);
9854 IsVirtualOkay = !Ret->isStatic();
9855 return Ret;
9856 } else {
9857 bool isFriend =
9858 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9859 if (!isFriend && SemaRef.CurContext->isRecord())
9860 return nullptr;
9861
9862 // Determine whether the function was written with a
9863 // prototype. This true when:
9864 // - we're in C++ (where every function has a prototype),
9865 return FunctionDecl::Create(
9866 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9867 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9868 hasWrittenPrototype: true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9869 }
9870}
9871
9872enum OpenCLParamType {
9873 ValidKernelParam,
9874 PtrPtrKernelParam,
9875 PtrKernelParam,
9876 InvalidAddrSpacePtrKernelParam,
9877 InvalidKernelParam,
9878 RecordKernelParam
9879};
9880
9881static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9882 // Size dependent types are just typedefs to normal integer types
9883 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9884 // integers other than by their names.
9885 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9886
9887 // Remove typedefs one by one until we reach a typedef
9888 // for a size dependent type.
9889 QualType DesugaredTy = Ty;
9890 do {
9891 ArrayRef<StringRef> Names(SizeTypeNames);
9892 auto Match = llvm::find(Range&: Names, Val: DesugaredTy.getUnqualifiedType().getAsString());
9893 if (Names.end() != Match)
9894 return true;
9895
9896 Ty = DesugaredTy;
9897 DesugaredTy = Ty.getSingleStepDesugaredType(Context: C);
9898 } while (DesugaredTy != Ty);
9899
9900 return false;
9901}
9902
9903static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9904 if (PT->isDependentType())
9905 return InvalidKernelParam;
9906
9907 if (PT->isPointerOrReferenceType()) {
9908 QualType PointeeType = PT->getPointeeType();
9909 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9910 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9911 PointeeType.getAddressSpace() == LangAS::Default)
9912 return InvalidAddrSpacePtrKernelParam;
9913
9914 if (PointeeType->isPointerType()) {
9915 // This is a pointer to pointer parameter.
9916 // Recursively check inner type.
9917 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PT: PointeeType);
9918 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9919 ParamKind == InvalidKernelParam)
9920 return ParamKind;
9921
9922 // OpenCL v3.0 s6.11.a:
9923 // A restriction to pass pointers to pointers only applies to OpenCL C
9924 // v1.2 or below.
9925 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9926 return ValidKernelParam;
9927
9928 return PtrPtrKernelParam;
9929 }
9930
9931 // C++ for OpenCL v1.0 s2.4:
9932 // Moreover the types used in parameters of the kernel functions must be:
9933 // Standard layout types for pointer parameters. The same applies to
9934 // reference if an implementation supports them in kernel parameters.
9935 if (S.getLangOpts().OpenCLCPlusPlus &&
9936 !S.getOpenCLOptions().isAvailableOption(
9937 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts())) {
9938 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9939 bool IsStandardLayoutType = true;
9940 if (CXXRec) {
9941 // If template type is not ODR-used its definition is only available
9942 // in the template definition not its instantiation.
9943 // FIXME: This logic doesn't work for types that depend on template
9944 // parameter (PR58590).
9945 if (!CXXRec->hasDefinition())
9946 CXXRec = CXXRec->getTemplateInstantiationPattern();
9947 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9948 IsStandardLayoutType = false;
9949 }
9950 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9951 !IsStandardLayoutType)
9952 return InvalidKernelParam;
9953 }
9954
9955 // OpenCL v1.2 s6.9.p:
9956 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9957 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9958 return ValidKernelParam;
9959
9960 return PtrKernelParam;
9961 }
9962
9963 // OpenCL v1.2 s6.9.k:
9964 // Arguments to kernel functions in a program cannot be declared with the
9965 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9966 // uintptr_t or a struct and/or union that contain fields declared to be one
9967 // of these built-in scalar types.
9968 if (isOpenCLSizeDependentType(C&: S.getASTContext(), Ty: PT))
9969 return InvalidKernelParam;
9970
9971 if (PT->isImageType())
9972 return PtrKernelParam;
9973
9974 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9975 return InvalidKernelParam;
9976
9977 // OpenCL extension spec v1.2 s9.5:
9978 // This extension adds support for half scalar and vector types as built-in
9979 // types that can be used for arithmetic operations, conversions etc.
9980 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: S.getLangOpts()) &&
9981 PT->isHalfType())
9982 return InvalidKernelParam;
9983
9984 // Look into an array argument to check if it has a forbidden type.
9985 if (PT->isArrayType()) {
9986 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9987 // Call ourself to check an underlying type of an array. Since the
9988 // getPointeeOrArrayElementType returns an innermost type which is not an
9989 // array, this recursive call only happens once.
9990 return getOpenCLKernelParameterType(S, PT: QualType(UnderlyingTy, 0));
9991 }
9992
9993 // C++ for OpenCL v1.0 s2.4:
9994 // Moreover the types used in parameters of the kernel functions must be:
9995 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9996 // types) for parameters passed by value;
9997 if (S.getLangOpts().OpenCLCPlusPlus &&
9998 !S.getOpenCLOptions().isAvailableOption(
9999 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts()) &&
10000 !PT->isOpenCLSpecificType() && !PT.isPODType(Context: S.Context))
10001 return InvalidKernelParam;
10002
10003 if (PT->isRecordType())
10004 return RecordKernelParam;
10005
10006 return ValidKernelParam;
10007}
10008
10009static void checkIsValidOpenCLKernelParameter(
10010 Sema &S,
10011 Declarator &D,
10012 ParmVarDecl *Param,
10013 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
10014 QualType PT = Param->getType();
10015
10016 // Cache the valid types we encounter to avoid rechecking structs that are
10017 // used again
10018 if (ValidTypes.count(Ptr: PT.getTypePtr()))
10019 return;
10020
10021 switch (getOpenCLKernelParameterType(S, PT)) {
10022 case PtrPtrKernelParam:
10023 // OpenCL v3.0 s6.11.a:
10024 // A kernel function argument cannot be declared as a pointer to a pointer
10025 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
10026 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_opencl_ptrptr_kernel_param);
10027 D.setInvalidType();
10028 return;
10029
10030 case InvalidAddrSpacePtrKernelParam:
10031 // OpenCL v1.0 s6.5:
10032 // __kernel function arguments declared to be a pointer of a type can point
10033 // to one of the following address spaces only : __global, __local or
10034 // __constant.
10035 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_kernel_arg_address_space);
10036 D.setInvalidType();
10037 return;
10038
10039 // OpenCL v1.2 s6.9.k:
10040 // Arguments to kernel functions in a program cannot be declared with the
10041 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
10042 // uintptr_t or a struct and/or union that contain fields declared to be
10043 // one of these built-in scalar types.
10044
10045 case InvalidKernelParam:
10046 // OpenCL v1.2 s6.8 n:
10047 // A kernel function argument cannot be declared
10048 // of event_t type.
10049 // Do not diagnose half type since it is diagnosed as invalid argument
10050 // type for any function elsewhere.
10051 if (!PT->isHalfType()) {
10052 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
10053
10054 // Explain what typedefs are involved.
10055 const TypedefType *Typedef = nullptr;
10056 while ((Typedef = PT->getAs<TypedefType>())) {
10057 SourceLocation Loc = Typedef->getDecl()->getLocation();
10058 // SourceLocation may be invalid for a built-in type.
10059 if (Loc.isValid())
10060 S.Diag(Loc, DiagID: diag::note_entity_declared_at) << PT;
10061 PT = Typedef->desugar();
10062 }
10063 }
10064
10065 D.setInvalidType();
10066 return;
10067
10068 case PtrKernelParam:
10069 case ValidKernelParam:
10070 ValidTypes.insert(Ptr: PT.getTypePtr());
10071 return;
10072
10073 case RecordKernelParam:
10074 break;
10075 }
10076
10077 // Track nested structs we will inspect
10078 SmallVector<const Decl *, 4> VisitStack;
10079
10080 // Track where we are in the nested structs. Items will migrate from
10081 // VisitStack to HistoryStack as we do the DFS for bad field.
10082 SmallVector<const FieldDecl *, 4> HistoryStack;
10083 HistoryStack.push_back(Elt: nullptr);
10084
10085 // At this point we already handled everything except of a RecordType.
10086 assert(PT->isRecordType() && "Unexpected type.");
10087 const auto *PD = PT->castAsRecordDecl();
10088 VisitStack.push_back(Elt: PD);
10089 assert(VisitStack.back() && "First decl null?");
10090
10091 do {
10092 const Decl *Next = VisitStack.pop_back_val();
10093 if (!Next) {
10094 assert(!HistoryStack.empty());
10095 // Found a marker, we have gone up a level
10096 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
10097 ValidTypes.insert(Ptr: Hist->getType().getTypePtr());
10098
10099 continue;
10100 }
10101
10102 // Adds everything except the original parameter declaration (which is not a
10103 // field itself) to the history stack.
10104 const RecordDecl *RD;
10105 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: Next)) {
10106 HistoryStack.push_back(Elt: Field);
10107
10108 QualType FieldTy = Field->getType();
10109 // Other field types (known to be valid or invalid) are handled while we
10110 // walk around RecordDecl::fields().
10111 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
10112 "Unexpected type.");
10113 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
10114
10115 RD = FieldRecTy->castAsRecordDecl();
10116 } else {
10117 RD = cast<RecordDecl>(Val: Next);
10118 }
10119
10120 // Add a null marker so we know when we've gone back up a level
10121 VisitStack.push_back(Elt: nullptr);
10122
10123 for (const auto *FD : RD->fields()) {
10124 QualType QT = FD->getType();
10125
10126 if (ValidTypes.count(Ptr: QT.getTypePtr()))
10127 continue;
10128
10129 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, PT: QT);
10130 if (ParamType == ValidKernelParam)
10131 continue;
10132
10133 if (ParamType == RecordKernelParam) {
10134 VisitStack.push_back(Elt: FD);
10135 continue;
10136 }
10137
10138 // OpenCL v1.2 s6.9.p:
10139 // Arguments to kernel functions that are declared to be a struct or union
10140 // do not allow OpenCL objects to be passed as elements of the struct or
10141 // union. This restriction was lifted in OpenCL v2.0 with the introduction
10142 // of SVM.
10143 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
10144 ParamType == InvalidAddrSpacePtrKernelParam) {
10145 S.Diag(Loc: Param->getLocation(),
10146 DiagID: diag::err_record_with_pointers_kernel_param)
10147 << PT->isUnionType()
10148 << PT;
10149 } else {
10150 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
10151 }
10152
10153 S.Diag(Loc: PD->getLocation(), DiagID: diag::note_within_field_of_type)
10154 << PD->getDeclName();
10155
10156 // We have an error, now let's go back up through history and show where
10157 // the offending field came from
10158 for (ArrayRef<const FieldDecl *>::const_iterator
10159 I = HistoryStack.begin() + 1,
10160 E = HistoryStack.end();
10161 I != E; ++I) {
10162 const FieldDecl *OuterField = *I;
10163 S.Diag(Loc: OuterField->getLocation(), DiagID: diag::note_within_field_of_type)
10164 << OuterField->getType();
10165 }
10166
10167 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_illegal_field_declared_here)
10168 << QT->isPointerType()
10169 << QT;
10170 D.setInvalidType();
10171 return;
10172 }
10173 } while (!VisitStack.empty());
10174}
10175
10176/// Find the DeclContext in which a tag is implicitly declared if we see an
10177/// elaborated type specifier in the specified context, and lookup finds
10178/// nothing.
10179static DeclContext *getTagInjectionContext(DeclContext *DC) {
10180 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10181 DC = DC->getParent();
10182 return DC;
10183}
10184
10185/// Find the Scope in which a tag is implicitly declared if we see an
10186/// elaborated type specifier in the specified context, and lookup finds
10187/// nothing.
10188static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10189 while (S->isClassScope() ||
10190 (LangOpts.CPlusPlus &&
10191 S->isFunctionPrototypeScope()) ||
10192 ((S->getFlags() & Scope::DeclScope) == 0) ||
10193 (S->getEntity() && S->getEntity()->isTransparentContext()))
10194 S = S->getParent();
10195 return S;
10196}
10197
10198/// Determine whether a declaration matches a known function in namespace std.
10199static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
10200 unsigned BuiltinID) {
10201 switch (BuiltinID) {
10202 case Builtin::BI__GetExceptionInfo:
10203 // No type checking whatsoever.
10204 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10205
10206 case Builtin::BIaddressof:
10207 case Builtin::BI__addressof:
10208 case Builtin::BIforward:
10209 case Builtin::BIforward_like:
10210 case Builtin::BImove:
10211 case Builtin::BImove_if_noexcept:
10212 case Builtin::BIas_const: {
10213 // Ensure that we don't treat the algorithm
10214 // OutputIt std::move(InputIt, InputIt, OutputIt)
10215 // as the builtin std::move.
10216 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10217 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10218 }
10219
10220 default:
10221 return false;
10222 }
10223}
10224
10225void Sema::addImplicitCallingConvAbiTag(FunctionDecl *FD) {
10226 const auto *FT = FD->getType()->getAs<FunctionType>();
10227 if (!FT)
10228 return;
10229
10230 StringRef Tag;
10231 switch (FT->getCallConv()) {
10232#define CC_VLS_CASE(ABI_VLEN) \
10233 case CC_RISCVVLSCall_##ABI_VLEN: \
10234 Tag = "riscv_vls_cc_" #ABI_VLEN; \
10235 break;
10236 CC_VLS_CASE(32)
10237 CC_VLS_CASE(64)
10238 CC_VLS_CASE(128)
10239 CC_VLS_CASE(256)
10240 CC_VLS_CASE(512)
10241 CC_VLS_CASE(1024)
10242 CC_VLS_CASE(2048)
10243 CC_VLS_CASE(4096)
10244 CC_VLS_CASE(8192)
10245 CC_VLS_CASE(16384)
10246 CC_VLS_CASE(32768)
10247 CC_VLS_CASE(65536)
10248#undef CC_VLS_CASE
10249 default:
10250 return;
10251 }
10252
10253 SmallVector<AbiTagAttr *, 2> Existing(FD->specific_attrs<AbiTagAttr>());
10254 AbiTagAttr *Old = Existing.empty() ? nullptr : Existing.front();
10255
10256 SmallVector<StringRef, 4> Tags;
10257 if (Old)
10258 llvm::append_range(C&: Tags, R: Old->tags());
10259 if (llvm::is_contained(Range&: Tags, Element: Tag))
10260 return;
10261 Tags.push_back(Elt: Tag);
10262
10263 AbiTagAttr *Merged =
10264 Old ? AbiTagAttr::Create(Ctx&: Context, Tags: Tags.data(), TagsSize: Tags.size(), CommonInfo: *Old)
10265 : AbiTagAttr::CreateImplicit(Ctx&: Context, Tags: Tags.data(), TagsSize: Tags.size(),
10266 Range: FD->getLocation());
10267 FD->dropAttr<AbiTagAttr>();
10268 FD->addAttr(A: Merged);
10269 for (size_t I = 1, E = Existing.size(); I < E; ++I)
10270 FD->addAttr(A: Existing[I]);
10271}
10272
10273NamedDecl*
10274Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
10275 TypeSourceInfo *TInfo, LookupResult &Previous,
10276 MultiTemplateParamsArg TemplateParamListsRef,
10277 bool &AddToScope) {
10278 QualType R = TInfo->getType();
10279
10280 assert(R->isFunctionType());
10281 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10282 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_decl_cmse_ns_call);
10283
10284 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10285 llvm::append_range(C&: TemplateParamLists, R&: TemplateParamListsRef);
10286 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
10287 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10288 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10289 TemplateParamLists.back() = Invented;
10290 else
10291 TemplateParamLists.push_back(Elt: Invented);
10292 }
10293
10294 // TODO: consider using NameInfo for diagnostic.
10295 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10296 DeclarationName Name = NameInfo.getName();
10297 StorageClass SC = getFunctionStorageClass(SemaRef&: *this, D);
10298
10299 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
10300 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
10301 DiagID: diag::err_invalid_thread)
10302 << DeclSpec::getSpecifierName(S: TSCS);
10303
10304 if (D.isFirstDeclarationOfMember())
10305 adjustMemberFunctionCC(
10306 T&: R, HasThisPointer: !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
10307 IsCtorOrDtor: D.isCtorOrDtor(), Loc: D.getIdentifierLoc());
10308
10309 bool isFriend = false;
10310 FunctionTemplateDecl *FunctionTemplate = nullptr;
10311 bool isMemberSpecialization = false;
10312 bool isFunctionTemplateSpecialization = false;
10313
10314 bool HasExplicitTemplateArgs = false;
10315 TemplateArgumentListInfo TemplateArgs;
10316
10317 bool isVirtualOkay = false;
10318
10319 DeclContext *OriginalDC = DC;
10320 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10321
10322 FunctionDecl *NewFD = CreateNewFunctionDecl(SemaRef&: *this, D, DC, R, TInfo, SC,
10323 IsVirtualOkay&: isVirtualOkay);
10324 if (!NewFD) return nullptr;
10325
10326 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10327 NewFD->setTopLevelDeclInObjCContainer();
10328
10329 // Set the lexical context. If this is a function-scope declaration, or has a
10330 // C++ scope specifier, or is the object of a friend declaration, the lexical
10331 // context will be different from the semantic context.
10332 NewFD->setLexicalDeclContext(CurContext);
10333
10334 if (IsLocalExternDecl)
10335 NewFD->setLocalExternDecl();
10336
10337 if (getLangOpts().CPlusPlus) {
10338 // The rules for implicit inlines changed in C++20 for methods and friends
10339 // with an in-class definition (when such a definition is not attached to
10340 // the global module). This does not affect declarations that are already
10341 // inline (whether explicitly or implicitly by being declared constexpr,
10342 // consteval, etc).
10343 // FIXME: We need a better way to separate C++ standard and clang modules.
10344 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10345 !NewFD->getOwningModule() ||
10346 NewFD->isFromGlobalModule() ||
10347 NewFD->getOwningModule()->isHeaderLikeModule();
10348 bool isInline = D.getDeclSpec().isInlineSpecified();
10349 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10350 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10351 isFriend = D.getDeclSpec().isFriendSpecified();
10352 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10353 // Pre-C++20 [class.friend]p5
10354 // A function can be defined in a friend declaration of a
10355 // class . . . . Such a function is implicitly inline.
10356 // Post C++20 [class.friend]p7
10357 // Such a function is implicitly an inline function if it is attached
10358 // to the global module.
10359 NewFD->setImplicitlyInline();
10360 }
10361
10362 // If this is a method defined in an __interface, and is not a constructor
10363 // or an overloaded operator, then set the pure flag (isVirtual will already
10364 // return true).
10365 if (const CXXRecordDecl *Parent =
10366 dyn_cast<CXXRecordDecl>(Val: NewFD->getDeclContext())) {
10367 if (Parent->isInterface() && cast<CXXMethodDecl>(Val: NewFD)->isUserProvided())
10368 NewFD->setIsPureVirtual(true);
10369
10370 // C++ [class.union]p2
10371 // A union can have member functions, but not virtual functions.
10372 if (isVirtual && Parent->isUnion()) {
10373 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_virtual_in_union);
10374 NewFD->setInvalidDecl();
10375 }
10376 if ((Parent->isClass() || Parent->isStruct()) &&
10377 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10378 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10379 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10380 if (auto *Def = Parent->getDefinition())
10381 Def->setInitMethod(true);
10382 }
10383 }
10384
10385 SetNestedNameSpecifier(S&: *this, DD: NewFD, D);
10386 isMemberSpecialization = false;
10387 isFunctionTemplateSpecialization = false;
10388 if (D.isInvalidType())
10389 NewFD->setInvalidDecl();
10390
10391 // Match up the template parameter lists with the scope specifier, then
10392 // determine whether we have a template or a template specialization.
10393 bool Invalid = false;
10394 TemplateIdAnnotation *TemplateId =
10395 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
10396 ? D.getName().TemplateId
10397 : nullptr;
10398 TemplateParameterList *TemplateParams =
10399 MatchTemplateParametersToScopeSpecifier(
10400 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
10401 SS: D.getCXXScopeSpec(), TemplateId, ParamLists: TemplateParamLists, IsFriend: isFriend,
10402 IsMemberSpecialization&: isMemberSpecialization, Invalid);
10403 if (TemplateParams) {
10404 // Check that we can declare a template here.
10405 if (CheckTemplateDeclScope(S, TemplateParams))
10406 NewFD->setInvalidDecl();
10407
10408 if (TemplateParams->size() > 0) {
10409 // This is a function template
10410
10411 // A destructor cannot be a template.
10412 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
10413 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_template);
10414 NewFD->setInvalidDecl();
10415 // Function template with explicit template arguments.
10416 } else if (TemplateId) {
10417 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_template_partial_spec)
10418 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10419 NewFD->setInvalidDecl();
10420 }
10421
10422 // If we're adding a template to a dependent context, we may need to
10423 // rebuilding some of the types used within the template parameter list,
10424 // now that we know what the current instantiation is.
10425 if (DC->isDependentContext()) {
10426 ContextRAII SavedContext(*this, DC);
10427 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
10428 Invalid = true;
10429 }
10430
10431 FunctionTemplate = FunctionTemplateDecl::Create(C&: Context, DC,
10432 L: NewFD->getLocation(),
10433 Name, Params: TemplateParams,
10434 Decl: NewFD);
10435 FunctionTemplate->setLexicalDeclContext(CurContext);
10436 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
10437
10438 // For source fidelity, store the other template param lists.
10439 if (TemplateParamLists.size() > 1) {
10440 NewFD->setTemplateParameterListsInfo(Context,
10441 TPLists: ArrayRef<TemplateParameterList *>(TemplateParamLists)
10442 .drop_back(N: 1));
10443 }
10444 } else {
10445 // This is a function template specialization.
10446 isFunctionTemplateSpecialization = true;
10447 // For source fidelity, store all the template param lists.
10448 if (TemplateParamLists.size() > 0)
10449 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10450
10451 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10452 if (isFriend) {
10453 // We want to remove the "template<>", found here.
10454 SourceRange RemoveRange = TemplateParams->getSourceRange();
10455
10456 // If we remove the template<> and the name is not a
10457 // template-id, we're actually silently creating a problem:
10458 // the friend declaration will refer to an untemplated decl,
10459 // and clearly the user wants a template specialization. So
10460 // we need to insert '<>' after the name.
10461 SourceLocation InsertLoc;
10462 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10463 InsertLoc = D.getName().getSourceRange().getEnd();
10464 InsertLoc = getLocForEndOfToken(Loc: InsertLoc);
10465 }
10466
10467 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_spec_decl_friend)
10468 << Name << RemoveRange
10469 << FixItHint::CreateRemoval(RemoveRange)
10470 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: "<>");
10471 Invalid = true;
10472
10473 // Recover by faking up an empty template argument list.
10474 HasExplicitTemplateArgs = true;
10475 TemplateArgs.setLAngleLoc(InsertLoc);
10476 TemplateArgs.setRAngleLoc(InsertLoc);
10477 }
10478 }
10479 } else {
10480 // Check that we can declare a template here.
10481 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10482 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
10483 NewFD->setInvalidDecl();
10484
10485 // All template param lists were matched against the scope specifier:
10486 // this is NOT (an explicit specialization of) a template.
10487 if (TemplateParamLists.size() > 0)
10488 // For source fidelity, store all the template param lists.
10489 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10490
10491 // "friend void foo<>(int);" is an implicit specialization decl.
10492 if (isFriend && TemplateId)
10493 isFunctionTemplateSpecialization = true;
10494 }
10495
10496 // If this is a function template specialization and the unqualified-id of
10497 // the declarator-id is a template-id, convert the template argument list
10498 // into our AST format and check for unexpanded packs.
10499 if (isFunctionTemplateSpecialization && TemplateId) {
10500 HasExplicitTemplateArgs = true;
10501
10502 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10503 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10504 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10505 TemplateId->NumArgs);
10506 translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgs);
10507
10508 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10509 // declaration of a function template partial specialization? Should we
10510 // consider the unexpanded pack context to be a partial specialization?
10511 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10512 if (DiagnoseUnexpandedParameterPack(
10513 Arg: ArgLoc, UPPC: isFriend ? UPPC_FriendDeclaration
10514 : UPPC_ExplicitSpecialization))
10515 NewFD->setInvalidDecl();
10516 }
10517 }
10518
10519 if (Invalid) {
10520 NewFD->setInvalidDecl();
10521 if (FunctionTemplate)
10522 FunctionTemplate->setInvalidDecl();
10523 }
10524
10525 // C++ [dcl.fct.spec]p5:
10526 // The virtual specifier shall only be used in declarations of
10527 // nonstatic class member functions that appear within a
10528 // member-specification of a class declaration; see 10.3.
10529 //
10530 if (isVirtual && !NewFD->isInvalidDecl()) {
10531 if (!isVirtualOkay) {
10532 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10533 DiagID: diag::err_virtual_non_function);
10534 } else if (!CurContext->isRecord()) {
10535 // 'virtual' was specified outside of the class.
10536 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10537 DiagID: diag::err_virtual_out_of_class)
10538 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10539 } else if (NewFD->getDescribedFunctionTemplate()) {
10540 // C++ [temp.mem]p3:
10541 // A member function template shall not be virtual.
10542 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10543 DiagID: diag::err_virtual_member_function_template)
10544 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10545 } else {
10546 // Okay: Add virtual to the method.
10547 NewFD->setVirtualAsWritten(true);
10548 }
10549
10550 if (getLangOpts().CPlusPlus14 &&
10551 NewFD->getReturnType()->isUndeducedType())
10552 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_auto_fn_virtual);
10553 }
10554
10555 // C++ [dcl.fct.spec]p3:
10556 // The inline specifier shall not appear on a block scope function
10557 // declaration.
10558 if (isInline && !NewFD->isInvalidDecl()) {
10559 if (CurContext->isFunctionOrMethod()) {
10560 // 'inline' is not allowed on block scope function declaration.
10561 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10562 DiagID: diag::err_inline_declaration_block_scope) << Name
10563 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10564 }
10565 }
10566
10567 // C++ [dcl.fct.spec]p6:
10568 // The explicit specifier shall be used only in the declaration of a
10569 // constructor or conversion function within its class definition;
10570 // see 12.3.1 and 12.3.2.
10571 if (hasExplicit && !NewFD->isInvalidDecl() &&
10572 !isa<CXXDeductionGuideDecl>(Val: NewFD)) {
10573 if (!CurContext->isRecord()) {
10574 // 'explicit' was specified outside of the class.
10575 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10576 DiagID: diag::err_explicit_out_of_class)
10577 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10578 } else if (!isa<CXXConstructorDecl>(Val: NewFD) &&
10579 !isa<CXXConversionDecl>(Val: NewFD)) {
10580 // 'explicit' was specified on a function that wasn't a constructor
10581 // or conversion function.
10582 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10583 DiagID: diag::err_explicit_non_ctor_or_conv_function)
10584 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10585 }
10586 }
10587
10588 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10589 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10590 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10591 // are implicitly inline.
10592 NewFD->setImplicitlyInline();
10593
10594 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10595 // be either constructors or to return a literal type. Therefore,
10596 // destructors cannot be declared constexpr.
10597 if (isa<CXXDestructorDecl>(Val: NewFD) &&
10598 (!getLangOpts().CPlusPlus20 ||
10599 ConstexprKind == ConstexprSpecKind::Consteval)) {
10600 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_constexpr_dtor)
10601 << static_cast<int>(ConstexprKind);
10602 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10603 ? ConstexprSpecKind::Unspecified
10604 : ConstexprSpecKind::Constexpr);
10605 }
10606 // C++20 [dcl.constexpr]p2: An allocation function, or a
10607 // deallocation function shall not be declared with the consteval
10608 // specifier.
10609 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10610 NewFD->getDeclName().isAnyOperatorNewOrDelete()) {
10611 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10612 DiagID: diag::err_invalid_consteval_decl_kind)
10613 << NewFD;
10614 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10615 }
10616 }
10617
10618 // If __module_private__ was specified, mark the function accordingly.
10619 if (D.getDeclSpec().isModulePrivateSpecified()) {
10620 if (isFunctionTemplateSpecialization) {
10621 SourceLocation ModulePrivateLoc
10622 = D.getDeclSpec().getModulePrivateSpecLoc();
10623 Diag(Loc: ModulePrivateLoc, DiagID: diag::err_module_private_specialization)
10624 << 0
10625 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
10626 } else {
10627 NewFD->setModulePrivate();
10628 if (FunctionTemplate)
10629 FunctionTemplate->setModulePrivate();
10630 }
10631 }
10632
10633 if (isFriend) {
10634 if (FunctionTemplate) {
10635 FunctionTemplate->setObjectOfFriendDecl();
10636 FunctionTemplate->setAccess(AS_public);
10637 }
10638 NewFD->setObjectOfFriendDecl();
10639 NewFD->setAccess(AS_public);
10640 }
10641
10642 // If a function is defined as defaulted or deleted, mark it as such now.
10643 // We'll do the relevant checks on defaulted / deleted functions later.
10644 switch (D.getFunctionDefinitionKind()) {
10645 case FunctionDefinitionKind::Declaration:
10646 case FunctionDefinitionKind::Definition:
10647 break;
10648
10649 case FunctionDefinitionKind::Defaulted:
10650 NewFD->setDefaulted();
10651 break;
10652
10653 case FunctionDefinitionKind::Deleted:
10654 NewFD->setDeletedAsWritten();
10655 break;
10656 }
10657
10658 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(Val: NewFD) && DC == CurContext &&
10659 D.isFunctionDefinition()) {
10660 // Pre C++20 [class.mfct]p2:
10661 // A member function may be defined (8.4) in its class definition, in
10662 // which case it is an inline member function (7.1.2)
10663 // Post C++20 [class.mfct]p1:
10664 // If a member function is attached to the global module and is defined
10665 // in its class definition, it is inline.
10666 NewFD->setImplicitlyInline();
10667 }
10668
10669 if (!isFriend && SC != SC_None) {
10670 // C++ [temp.expl.spec]p2:
10671 // The declaration in an explicit-specialization shall not be an
10672 // export-declaration. An explicit specialization shall not use a
10673 // storage-class-specifier other than thread_local.
10674 //
10675 // We diagnose friend declarations with storage-class-specifiers
10676 // elsewhere.
10677 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10678 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10679 DiagID: diag::ext_explicit_specialization_storage_class)
10680 << FixItHint::CreateRemoval(
10681 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10682 }
10683
10684 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10685 assert(isa<CXXMethodDecl>(NewFD) &&
10686 "Out-of-line member function should be a CXXMethodDecl");
10687 // C++ [class.static]p1:
10688 // A data or function member of a class may be declared static
10689 // in a class definition, in which case it is a static member of
10690 // the class.
10691
10692 // Complain about the 'static' specifier if it's on an out-of-line
10693 // member function definition.
10694
10695 // MSVC permits the use of a 'static' storage specifier on an
10696 // out-of-line member function template declaration and class member
10697 // template declaration (MSVC versions before 2015), warn about this.
10698 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10699 DiagID: ((!getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
10700 cast<CXXRecordDecl>(Val: DC)->getDescribedClassTemplate()) ||
10701 (getLangOpts().MSVCCompat &&
10702 NewFD->getDescribedFunctionTemplate()))
10703 ? diag::ext_static_out_of_line
10704 : diag::err_static_out_of_line)
10705 << FixItHint::CreateRemoval(
10706 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10707 }
10708 }
10709
10710 // C++11 [except.spec]p15:
10711 // A deallocation function with no exception-specification is treated
10712 // as if it were specified with noexcept(true).
10713 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10714 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10715 !FPT->hasExceptionSpec())
10716 NewFD->setType(Context.getFunctionType(
10717 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
10718 EPI: FPT->getExtProtoInfo().withExceptionSpec(ESI: EST_BasicNoexcept)));
10719
10720 // C++20 [dcl.inline]/7
10721 // If an inline function or variable that is attached to a named module
10722 // is declared in a definition domain, it shall be defined in that
10723 // domain.
10724 // So, if the current declaration does not have a definition, we must
10725 // check at the end of the TU (or when the PMF starts) to see that we
10726 // have a definition at that point.
10727 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10728 NewFD->isInNamedModule()) {
10729 PendingInlineFuncDecls.insert(Ptr: NewFD);
10730 }
10731 }
10732
10733 // Filter out previous declarations that don't match the scope.
10734 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(FD: NewFD),
10735 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
10736 isMemberSpecialization ||
10737 isFunctionTemplateSpecialization);
10738
10739 LoadExternalExtnameUndeclaredIdentifiers();
10740
10741 // Handle GNU asm-label extension (encoded as an attribute).
10742 if (Expr *E = D.getAsmLabel()) {
10743 // The parser guarantees this is a string.
10744 StringLiteral *SE = cast<StringLiteral>(Val: E);
10745 NewFD->addAttr(
10746 A: AsmLabelAttr::Create(Ctx&: Context, Label: SE->getString(), Range: SE->getStrTokenLoc(TokNum: 0)));
10747 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10748 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
10749 ExtnameUndeclaredIdentifiers.find(Key: NewFD->getIdentifier());
10750 if (I != ExtnameUndeclaredIdentifiers.end()) {
10751 if (isDeclExternC(D: NewFD)) {
10752 NewFD->addAttr(A: I->second);
10753 ExtnameUndeclaredIdentifiers.erase(Iterator: I);
10754 } else if (NewFD->getDeclContext()
10755 ->getRedeclContext()
10756 ->isTranslationUnit())
10757 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
10758 << /*Variable*/0 << NewFD;
10759 }
10760 }
10761
10762 // Copy the parameter declarations from the declarator D to the function
10763 // declaration NewFD, if they are available. First scavenge them into Params.
10764 SmallVector<ParmVarDecl*, 16> Params;
10765 unsigned FTIIdx;
10766 if (D.isFunctionDeclarator(idx&: FTIIdx)) {
10767 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(i: FTIIdx).Fun;
10768
10769 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10770 // function that takes no arguments, not a function that takes a
10771 // single void argument.
10772 // We let through "const void" here because Sema::GetTypeForDeclarator
10773 // already checks for that case.
10774 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10775 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10776 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
10777 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10778 Param->setDeclContext(NewFD);
10779 Params.push_back(Elt: Param);
10780
10781 if (Param->isInvalidDecl())
10782 NewFD->setInvalidDecl();
10783 }
10784 }
10785
10786 if (!getLangOpts().CPlusPlus) {
10787 // In C, find all the tag declarations from the prototype and move them
10788 // into the function DeclContext. Remove them from the surrounding tag
10789 // injection context of the function, which is typically but not always
10790 // the TU.
10791 DeclContext *PrototypeTagContext =
10792 getTagInjectionContext(DC: NewFD->getLexicalDeclContext());
10793 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10794 auto *TD = dyn_cast<TagDecl>(Val: NonParmDecl);
10795
10796 // We don't want to reparent enumerators. Look at their parent enum
10797 // instead.
10798 if (!TD) {
10799 if (auto *ECD = dyn_cast<EnumConstantDecl>(Val: NonParmDecl))
10800 TD = cast<EnumDecl>(Val: ECD->getDeclContext());
10801 }
10802 if (!TD)
10803 continue;
10804 DeclContext *TagDC = TD->getLexicalDeclContext();
10805 if (!TagDC->containsDecl(D: TD))
10806 continue;
10807 TagDC->removeDecl(D: TD);
10808 TD->setDeclContext(NewFD);
10809 NewFD->addDecl(D: TD);
10810
10811 // Preserve the lexical DeclContext if it is not the surrounding tag
10812 // injection context of the FD. In this example, the semantic context of
10813 // E will be f and the lexical context will be S, while both the
10814 // semantic and lexical contexts of S will be f:
10815 // void f(struct S { enum E { a } f; } s);
10816 if (TagDC != PrototypeTagContext)
10817 TD->setLexicalDeclContext(TagDC);
10818 }
10819 }
10820 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10821 // When we're declaring a function with a typedef, typeof, etc as in the
10822 // following example, we'll need to synthesize (unnamed)
10823 // parameters for use in the declaration.
10824 //
10825 // @code
10826 // typedef void fn(int);
10827 // fn f;
10828 // @endcode
10829
10830 // Synthesize a parameter for each argument type.
10831 for (const auto &AI : FT->param_types()) {
10832 ParmVarDecl *Param =
10833 BuildParmVarDeclForTypedef(DC: NewFD, Loc: D.getIdentifierLoc(), T: AI);
10834 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
10835 Params.push_back(Elt: Param);
10836 }
10837 } else {
10838 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10839 "Should not need args for typedef of non-prototype fn");
10840 }
10841
10842 // Finally, we know we have the right number of parameters, install them.
10843 NewFD->setParams(Params);
10844
10845 // If this declarator is a declaration and not a definition, its parameters
10846 // will not be pushed onto a scope chain. That means we will not issue any
10847 // reserved identifier warnings for the declaration, but we will for the
10848 // definition. Handle those here.
10849 if (!D.isFunctionDefinition()) {
10850 for (const ParmVarDecl *PVD : Params)
10851 warnOnReservedIdentifier(D: PVD);
10852 }
10853
10854 if (D.getDeclSpec().isNoreturnSpecified())
10855 NewFD->addAttr(
10856 A: C11NoReturnAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getNoreturnSpecLoc()));
10857
10858 // Functions returning a variably modified type violate C99 6.7.5.2p2
10859 // because all functions have linkage.
10860 if (!NewFD->isInvalidDecl() &&
10861 NewFD->getReturnType()->isVariablyModifiedType()) {
10862 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_vm_func_decl);
10863 NewFD->setInvalidDecl();
10864 }
10865
10866 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10867 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10868 !NewFD->hasAttr<SectionAttr>())
10869 NewFD->addAttr(A: PragmaClangTextSectionAttr::CreateImplicit(
10870 Ctx&: Context, Name: PragmaClangTextSection.SectionName,
10871 Range: PragmaClangTextSection.PragmaLocation));
10872
10873 // Apply an implicit SectionAttr if #pragma code_seg is active.
10874 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10875 !NewFD->hasAttr<SectionAttr>()) {
10876 NewFD->addAttr(A: SectionAttr::CreateImplicit(
10877 Ctx&: Context, Name: CodeSegStack.CurrentValue->getString(),
10878 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate));
10879 if (UnifySection(SectionName: CodeSegStack.CurrentValue->getString(),
10880 SectionFlags: ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10881 ASTContext::PSF_Read,
10882 TheDecl: NewFD))
10883 NewFD->dropAttr<SectionAttr>();
10884 }
10885
10886 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10887 // active.
10888 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10889 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10890 NewFD->addAttr(A: StrictGuardStackCheckAttr::CreateImplicit(
10891 Ctx&: Context, Range: PragmaClangTextSection.PragmaLocation));
10892
10893 // Apply an implicit CodeSegAttr from class declspec or
10894 // apply an implicit SectionAttr from #pragma code_seg if active.
10895 if (!NewFD->hasAttr<CodeSegAttr>()) {
10896 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(FD: NewFD,
10897 IsDefinition: D.isFunctionDefinition())) {
10898 NewFD->addAttr(A: SAttr);
10899 }
10900 }
10901
10902 // Handle attributes.
10903 ProcessDeclAttributes(S, D: NewFD, PD: D);
10904 addImplicitCallingConvAbiTag(FD: NewFD);
10905 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10906 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10907 !NewTVA->isDefaultVersion() &&
10908 !Context.getTargetInfo().hasFeature(Feature: "fmv")) {
10909 // Don't add to scope fmv functions declarations if fmv disabled
10910 AddToScope = false;
10911 return NewFD;
10912 }
10913
10914 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10915 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10916 // type.
10917 //
10918 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10919 // type declaration will generate a compilation error.
10920 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10921 if (AddressSpace != LangAS::Default) {
10922 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_return_value_with_address_space);
10923 NewFD->setInvalidDecl();
10924 }
10925 }
10926
10927 if (!getLangOpts().CPlusPlus) {
10928 // Perform semantic checking on the function declaration.
10929 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10930 CheckMain(FD: NewFD, D: D.getDeclSpec());
10931
10932 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10933 CheckMSVCRTEntryPoint(FD: NewFD);
10934
10935 if (!NewFD->isInvalidDecl())
10936 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10937 IsMemberSpecialization: isMemberSpecialization,
10938 DeclIsDefn: D.isFunctionDefinition()));
10939 else if (!Previous.empty())
10940 // Recover gracefully from an invalid redeclaration.
10941 D.setRedeclaration(true);
10942 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10943 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10944 "previous declaration set still overloaded");
10945
10946 // Diagnose no-prototype function declarations with calling conventions that
10947 // don't support variadic calls. Only do this in C and do it after merging
10948 // possibly prototyped redeclarations.
10949 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10950 if (isa<FunctionNoProtoType>(Val: FT) && !D.isFunctionDefinition()) {
10951 CallingConv CC = FT->getExtInfo().getCC();
10952 if (!supportsVariadicCall(CC)) {
10953 // Windows system headers sometimes accidentally use stdcall without
10954 // (void) parameters, so we relax this to a warning.
10955 int DiagID =
10956 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10957 Diag(Loc: NewFD->getLocation(), DiagID)
10958 << FunctionType::getNameForCallConv(CC);
10959 }
10960 }
10961
10962 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10963 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10964 checkNonTrivialCUnion(
10965 QT: NewFD->getReturnType(), Loc: NewFD->getReturnTypeSourceRange().getBegin(),
10966 UseContext: NonTrivialCUnionContext::FunctionReturn, NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
10967 } else {
10968 // C++11 [replacement.functions]p3:
10969 // The program's definitions shall not be specified as inline.
10970 //
10971 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10972 //
10973 // Suppress the diagnostic if the function is __attribute__((used)), since
10974 // that forces an external definition to be emitted.
10975 if (D.getDeclSpec().isInlineSpecified() &&
10976 NewFD->isReplaceableGlobalAllocationFunction() &&
10977 !NewFD->hasAttr<UsedAttr>())
10978 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10979 DiagID: diag::ext_operator_new_delete_declared_inline)
10980 << NewFD->getDeclName();
10981
10982 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10983 // C++20 [dcl.decl.general]p4:
10984 // The optional requires-clause in an init-declarator or
10985 // member-declarator shall be present only if the declarator declares a
10986 // templated function.
10987 //
10988 // C++20 [temp.pre]p8:
10989 // An entity is templated if it is
10990 // - a template,
10991 // - an entity defined or created in a templated entity,
10992 // - a member of a templated entity,
10993 // - an enumerator for an enumeration that is a templated entity, or
10994 // - the closure type of a lambda-expression appearing in the
10995 // declaration of a templated entity.
10996 //
10997 // [Note 6: A local class, a local or block variable, or a friend
10998 // function defined in a templated entity is a templated entity.
10999 // — end note]
11000 //
11001 // A templated function is a function template or a function that is
11002 // templated. A templated class is a class template or a class that is
11003 // templated. A templated variable is a variable template or a variable
11004 // that is templated.
11005 if (!FunctionTemplate) {
11006 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
11007 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
11008 // An explicit specialization shall not have a trailing
11009 // requires-clause unless it declares a function template.
11010 //
11011 // Since a friend function template specialization cannot be
11012 // definition, and since a non-template friend declaration with a
11013 // trailing requires-clause must be a definition, we diagnose
11014 // friend function template specializations with trailing
11015 // requires-clauses on the same path as explicit specializations
11016 // even though they aren't necessarily prohibited by the same
11017 // language rule.
11018 Diag(Loc: TRC->getBeginLoc(), DiagID: diag::err_non_temp_spec_requires_clause)
11019 << isFriend;
11020 } else if (isFriend && NewFD->isTemplated() &&
11021 !D.isFunctionDefinition()) {
11022 // C++ [temp.friend]p9:
11023 // A non-template friend declaration with a requires-clause shall be
11024 // a definition.
11025 Diag(Loc: NewFD->getBeginLoc(),
11026 DiagID: diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
11027 NewFD->setInvalidDecl();
11028 } else if (!NewFD->isTemplated() ||
11029 !(isa<CXXMethodDecl>(Val: NewFD) || D.isFunctionDefinition())) {
11030 Diag(Loc: TRC->getBeginLoc(),
11031 DiagID: diag::err_constrained_non_templated_function);
11032 }
11033 }
11034 }
11035
11036 // We do not add HD attributes to specializations here because
11037 // they may have different constexpr-ness compared to their
11038 // templates and, after maybeAddHostDeviceAttrs() is applied,
11039 // may end up with different effective targets. Instead, a
11040 // specialization inherits its target attributes from its template
11041 // in the CheckFunctionTemplateSpecialization() call below.
11042 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
11043 CUDA().maybeAddHostDeviceAttrs(FD: NewFD, Previous);
11044
11045 // Handle explicit specializations of function templates
11046 // and friend function declarations with an explicit
11047 // template argument list.
11048 if (isFunctionTemplateSpecialization) {
11049 bool isDependentSpecialization = false;
11050 if (isFriend) {
11051 // For friend function specializations, this is a dependent
11052 // specialization if its semantic context is dependent, its
11053 // qualifier is dependent, its type is dependent, or its template-id is
11054 // dependent.
11055 isDependentSpecialization =
11056 DC->isDependentContext() || NewFD->getQualifier().isDependent() ||
11057 NewFD->getType()->isDependentType() ||
11058 (HasExplicitTemplateArgs &&
11059 TemplateSpecializationType::
11060 anyInstantiationDependentTemplateArguments(
11061 Args: TemplateArgs.arguments()));
11062 assert((!isDependentSpecialization ||
11063 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
11064 "dependent friend function specialization without template "
11065 "args");
11066 } else {
11067 // For class-scope explicit specializations of function templates,
11068 // if the lexical context is dependent, then the specialization
11069 // is dependent.
11070 isDependentSpecialization =
11071 CurContext->isRecord() && CurContext->isDependentContext();
11072 }
11073
11074 TemplateArgumentListInfo *ExplicitTemplateArgs =
11075 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
11076 if (isDependentSpecialization) {
11077 // If it's a dependent specialization, it may not be possible
11078 // to determine the primary template (for explicit specializations)
11079 // or befriended declaration (for friends) until the enclosing
11080 // template is instantiated. In such cases, we store the declarations
11081 // found by name lookup and defer resolution until instantiation.
11082 if (CheckDependentFunctionTemplateSpecialization(
11083 FD: NewFD, ExplicitTemplateArgs, Previous))
11084 NewFD->setInvalidDecl();
11085 } else if (!NewFD->isInvalidDecl()) {
11086 if (CheckFunctionTemplateSpecialization(FD: NewFD, ExplicitTemplateArgs,
11087 Previous))
11088 NewFD->setInvalidDecl();
11089 }
11090 } else if (isMemberSpecialization && !FunctionTemplate) {
11091 if (CheckMemberSpecialization(Member: NewFD, Previous))
11092 NewFD->setInvalidDecl();
11093 }
11094
11095 // Perform semantic checking on the function declaration.
11096 if (!NewFD->isInvalidDecl() && NewFD->isMain())
11097 CheckMain(FD: NewFD, D: D.getDeclSpec());
11098
11099 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
11100 CheckMSVCRTEntryPoint(FD: NewFD);
11101
11102 if (!NewFD->isInvalidDecl())
11103 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
11104 IsMemberSpecialization: isMemberSpecialization,
11105 DeclIsDefn: D.isFunctionDefinition()));
11106 else if (!Previous.empty())
11107 // Recover gracefully from an invalid redeclaration.
11108 D.setRedeclaration(true);
11109
11110 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
11111 !D.isRedeclaration() ||
11112 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
11113 "previous declaration set still overloaded");
11114
11115 NamedDecl *PrincipalDecl = (FunctionTemplate
11116 ? cast<NamedDecl>(Val: FunctionTemplate)
11117 : NewFD);
11118
11119 if (isFriend && NewFD->getPreviousDecl()) {
11120 AccessSpecifier Access = AS_public;
11121 if (!NewFD->isInvalidDecl())
11122 Access = NewFD->getPreviousDecl()->getAccess();
11123
11124 NewFD->setAccess(Access);
11125 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
11126 }
11127
11128 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
11129 PrincipalDecl->isInIdentifierNamespace(NS: Decl::IDNS_Ordinary))
11130 PrincipalDecl->setNonMemberOperator();
11131
11132 // If we have a function template, check the template parameter
11133 // list. This will check and merge default template arguments.
11134 if (FunctionTemplate) {
11135 FunctionTemplateDecl *PrevTemplate =
11136 FunctionTemplate->getPreviousDecl();
11137 CheckTemplateParameterList(NewParams: FunctionTemplate->getTemplateParameters(),
11138 OldParams: PrevTemplate ? PrevTemplate->getTemplateParameters()
11139 : nullptr,
11140 TPC: D.getDeclSpec().isFriendSpecified()
11141 ? (D.isFunctionDefinition()
11142 ? TPC_FriendFunctionTemplateDefinition
11143 : TPC_FriendFunctionTemplate)
11144 : (D.getCXXScopeSpec().isSet() &&
11145 DC && DC->isRecord() &&
11146 DC->isDependentContext())
11147 ? TPC_ClassTemplateMember
11148 : TPC_FunctionTemplate);
11149 }
11150
11151 if (NewFD->isInvalidDecl()) {
11152 // Ignore all the rest of this.
11153 } else if (!D.isRedeclaration()) {
11154 struct ActOnFDArgs ExtraArgs = { .S: S, .D: D, .TemplateParamLists: TemplateParamLists,
11155 .AddToScope: AddToScope };
11156 // Fake up an access specifier if it's supposed to be a class member.
11157 if (isa<CXXRecordDecl>(Val: NewFD->getDeclContext()))
11158 NewFD->setAccess(AS_public);
11159
11160 // Qualified decls generally require a previous declaration.
11161 if (D.getCXXScopeSpec().isSet()) {
11162 // ...with the major exception of templated-scope or
11163 // dependent-scope friend declarations.
11164
11165 // TODO: we currently also suppress this check in dependent
11166 // contexts because (1) the parameter depth will be off when
11167 // matching friend templates and (2) we might actually be
11168 // selecting a friend based on a dependent factor. But there
11169 // are situations where these conditions don't apply and we
11170 // can actually do this check immediately.
11171 //
11172 // Unless the scope is dependent, it's always an error if qualified
11173 // redeclaration lookup found nothing at all. Diagnose that now;
11174 // nothing will diagnose that error later.
11175 if (isFriend &&
11176 (D.getCXXScopeSpec().getScopeRep().isDependent() ||
11177 (!Previous.empty() && CurContext->isDependentContext()))) {
11178 // ignore these
11179 } else if (NewFD->isCPUDispatchMultiVersion() ||
11180 NewFD->isCPUSpecificMultiVersion()) {
11181 // ignore this, we allow the redeclaration behavior here to create new
11182 // versions of the function.
11183 } else {
11184 // The user tried to provide an out-of-line definition for a
11185 // function that is a member of a class or namespace, but there
11186 // was no such member function declared (C++ [class.mfct]p2,
11187 // C++ [namespace.memdef]p2). For example:
11188 //
11189 // class X {
11190 // void f() const;
11191 // };
11192 //
11193 // void X::f() { } // ill-formed
11194 //
11195 // Complain about this problem, and attempt to suggest close
11196 // matches (e.g., those that differ only in cv-qualifiers and
11197 // whether the parameter types are references).
11198
11199 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
11200 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: false, S: nullptr)) {
11201 AddToScope = ExtraArgs.AddToScope;
11202 return Result;
11203 }
11204 }
11205
11206 // Unqualified local friend declarations are required to resolve
11207 // to something.
11208 } else if (isFriend && cast<CXXRecordDecl>(Val: CurContext)->isLocalClass()) {
11209 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
11210 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: true, S)) {
11211 AddToScope = ExtraArgs.AddToScope;
11212 return Result;
11213 }
11214 }
11215 } else if (!D.isFunctionDefinition() &&
11216 isa<CXXMethodDecl>(Val: NewFD) && NewFD->isOutOfLine() &&
11217 !isFriend && !isFunctionTemplateSpecialization &&
11218 !isMemberSpecialization) {
11219 // An out-of-line member function declaration must also be a
11220 // definition (C++ [class.mfct]p2).
11221 // Note that this is not the case for explicit specializations of
11222 // function templates or member functions of class templates, per
11223 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11224 // extension for compatibility with old SWIG code which likes to
11225 // generate them.
11226 Diag(Loc: NewFD->getLocation(), DiagID: diag::ext_out_of_line_declaration)
11227 << D.getCXXScopeSpec().getRange();
11228 }
11229 }
11230
11231 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11232 // Any top level function could potentially be specified as an entry.
11233 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11234 HLSL().ActOnTopLevelFunction(FD: NewFD);
11235
11236 if (NewFD->hasAttr<HLSLShaderAttr>())
11237 HLSL().CheckEntryPoint(FD: NewFD);
11238
11239 // Resources cannot be passed to functions that are not inlined.
11240 if (const NoInlineAttr *NoInline = NewFD->getAttr<NoInlineAttr>()) {
11241 for (const ParmVarDecl *PVD : NewFD->parameters()) {
11242 QualType ParamTy = PVD->getType().getNonReferenceType();
11243 QualType EltTy = Context.getBaseElementType(QT: ParamTy);
11244 // `isCompleteType` forces completion of the element type without
11245 // reporting an error (diagnosed elsewhere) so the resource parameter
11246 // check is valid.
11247 if (!EltTy->isDependentType() &&
11248 isCompleteType(Loc: PVD->getLocation(), T: EltTy) &&
11249 ParamTy->isHLSLIntangibleType()) {
11250 Diag(Loc: PVD->getLocation(),
11251 DiagID: diag::err_hlsl_resource_param_in_noinline_function)
11252 << ParamTy;
11253 Diag(Loc: NoInline->getLocation(), DiagID: diag::note_attribute);
11254 }
11255 }
11256 }
11257 }
11258
11259 // If this is the first declaration of a library builtin function, add
11260 // attributes as appropriate.
11261 if (!D.isRedeclaration()) {
11262 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11263 if (unsigned BuiltinID = II->getBuiltinID()) {
11264 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID);
11265 if (!InStdNamespace &&
11266 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
11267 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11268 // Validate the type matches unless this builtin is specified as
11269 // matching regardless of its declared type.
11270 if (Context.BuiltinInfo.allowTypeMismatch(ID: BuiltinID)) {
11271 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11272 } else {
11273 ASTContext::GetBuiltinTypeError Error;
11274 LookupNecessaryTypesForBuiltin(S, ID: BuiltinID);
11275 QualType BuiltinType = Context.GetBuiltinType(ID: BuiltinID, Error);
11276
11277 if (!Error && !BuiltinType.isNull() &&
11278 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11279 T: NewFD->getType(), U: BuiltinType))
11280 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11281 }
11282 }
11283 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11284 isStdBuiltin(Ctx&: Context, FD: NewFD, BuiltinID)) {
11285 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11286 }
11287 }
11288 }
11289 }
11290
11291 ProcessPragmaWeak(S, D: NewFD);
11292 ProcessPragmaExport(NewD: NewFD);
11293 checkAttributesAfterMerging(S&: *this, ND&: *NewFD);
11294
11295 AddKnownFunctionAttributes(FD: NewFD);
11296 // The above can add the format attribute for known builtin/library functions
11297 // which is required by the modular_format attribute, thus
11298 // validate modular_format now after those attributes have been added.
11299 checkModularFormatAttr(S&: *this, ND&: *NewFD);
11300
11301 if (NewFD->hasAttr<OverloadableAttr>() &&
11302 !NewFD->getType()->getAs<FunctionProtoType>()) {
11303 Diag(Loc: NewFD->getLocation(),
11304 DiagID: diag::err_attribute_overloadable_no_prototype)
11305 << NewFD;
11306 NewFD->dropAttr<OverloadableAttr>();
11307 }
11308
11309 // If there's a #pragma GCC visibility in scope, and this isn't a class
11310 // member, set the visibility of this function.
11311 if (!DC->isRecord() && NewFD->isExternallyVisible())
11312 AddPushedVisibilityAttribute(RD: NewFD);
11313
11314 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11315 // marking the function.
11316 ObjC().AddCFAuditedAttribute(D: NewFD);
11317
11318 // If this is a function definition, check if we have to apply any
11319 // attributes (i.e. optnone and no_builtin) due to a pragma.
11320 if (D.isFunctionDefinition()) {
11321 AddRangeBasedOptnone(FD: NewFD);
11322 AddImplicitMSFunctionNoBuiltinAttr(FD: NewFD);
11323 AddSectionMSAllocText(FD: NewFD);
11324 ModifyFnAttributesMSPragmaOptimize(FD: NewFD);
11325 }
11326
11327 // If this is the first declaration of an extern C variable, update
11328 // the map of such variables.
11329 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11330 isIncompleteDeclExternC(S&: *this, D: NewFD))
11331 RegisterLocallyScopedExternCDecl(ND: NewFD, S);
11332
11333 // Set this FunctionDecl's range up to the right paren.
11334 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11335
11336 if (D.isRedeclaration() && !Previous.empty()) {
11337 NamedDecl *Prev = Previous.getRepresentativeDecl();
11338 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewFD,
11339 IsSpecialization: isMemberSpecialization ||
11340 isFunctionTemplateSpecialization,
11341 IsDefinition: D.isFunctionDefinition());
11342 }
11343
11344 if (getLangOpts().CUDA) {
11345 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11346 if (II->isStr(Str: CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11347 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11348 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11349 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11350 << CUDA().getConfigureFuncName();
11351 Context.setcudaConfigureCallDecl(NewFD);
11352 }
11353 if (II->isStr(Str: CUDA().getGetParameterBufferFuncName()) &&
11354 !NewFD->isInvalidDecl() &&
11355 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11356 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11357 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_pointer_return)
11358 << CUDA().getConfigureFuncName();
11359 Context.setcudaGetParameterBufferDecl(NewFD);
11360 }
11361 if (II->isStr(Str: CUDA().getLaunchDeviceFuncName()) &&
11362 !NewFD->isInvalidDecl() &&
11363 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11364 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11365 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11366 << CUDA().getConfigureFuncName();
11367 Context.setcudaLaunchDeviceDecl(NewFD);
11368 }
11369 }
11370 }
11371
11372 MarkUnusedFileScopedDecl(D: NewFD);
11373
11374 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11375 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11376 if (SC == SC_Static) {
11377 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_static_kernel);
11378 D.setInvalidType();
11379 }
11380
11381 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11382 if (!NewFD->getReturnType()->isVoidType()) {
11383 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11384 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_expected_kernel_void_return_type)
11385 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "void")
11386 : FixItHint());
11387 D.setInvalidType();
11388 }
11389
11390 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
11391 for (auto *Param : NewFD->parameters())
11392 checkIsValidOpenCLKernelParameter(S&: *this, D, Param, ValidTypes);
11393
11394 if (getLangOpts().OpenCLCPlusPlus) {
11395 if (DC->isRecord()) {
11396 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_method_kernel);
11397 D.setInvalidType();
11398 }
11399 if (FunctionTemplate) {
11400 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_kernel);
11401 D.setInvalidType();
11402 }
11403 }
11404 }
11405
11406 if (getLangOpts().CPlusPlus) {
11407 // Precalculate whether this is a friend function template with a constraint
11408 // that depends on an enclosing template, per [temp.friend]p9.
11409 if (isFriend && FunctionTemplate &&
11410 FriendConstraintsDependOnEnclosingTemplate(FD: NewFD)) {
11411 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
11412
11413 // C++ [temp.friend]p9:
11414 // A friend function template with a constraint that depends on a
11415 // template parameter from an enclosing template shall be a definition.
11416 if (!D.isFunctionDefinition()) {
11417 Diag(Loc: NewFD->getBeginLoc(),
11418 DiagID: diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11419 NewFD->setInvalidDecl();
11420 }
11421 }
11422
11423 if (FunctionTemplate) {
11424 if (NewFD->isInvalidDecl())
11425 FunctionTemplate->setInvalidDecl();
11426 return FunctionTemplate;
11427 }
11428
11429 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11430 CompleteMemberSpecialization(Member: NewFD, Previous);
11431 }
11432
11433 for (const ParmVarDecl *Param : NewFD->parameters()) {
11434 QualType PT = Param->getType();
11435
11436 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11437 // types.
11438 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11439 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11440 QualType ElemTy = PipeTy->getElementType();
11441 if (ElemTy->isPointerOrReferenceType()) {
11442 Diag(Loc: Param->getTypeSpecStartLoc(), DiagID: diag::err_reference_pipe_type);
11443 D.setInvalidType();
11444 }
11445 }
11446 }
11447 // WebAssembly tables can't be used as function parameters.
11448 if (Context.getTargetInfo().getTriple().isWasm()) {
11449 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
11450 Diag(Loc: Param->getTypeSpecStartLoc(),
11451 DiagID: diag::err_wasm_table_as_function_parameter);
11452 D.setInvalidType();
11453 }
11454 }
11455 }
11456
11457 // Diagnose availability attributes. Availability cannot be used on functions
11458 // that are run during load/unload.
11459 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11460 if (NewFD->hasAttr<ConstructorAttr>()) {
11461 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11462 << 1;
11463 NewFD->dropAttr<AvailabilityAttr>();
11464 }
11465 if (NewFD->hasAttr<DestructorAttr>()) {
11466 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11467 << 2;
11468 NewFD->dropAttr<AvailabilityAttr>();
11469 }
11470 }
11471
11472 // Diagnose no_builtin attribute on function declaration that are not a
11473 // definition.
11474 // FIXME: We should really be doing this in
11475 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11476 // the FunctionDecl and at this point of the code
11477 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11478 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11479 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11480 switch (D.getFunctionDefinitionKind()) {
11481 case FunctionDefinitionKind::Defaulted:
11482 case FunctionDefinitionKind::Deleted:
11483 Diag(Loc: NBA->getLocation(),
11484 DiagID: diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11485 << NBA->getSpelling();
11486 break;
11487 case FunctionDefinitionKind::Declaration:
11488 Diag(Loc: NBA->getLocation(), DiagID: diag::err_attribute_no_builtin_on_non_definition)
11489 << NBA->getSpelling();
11490 break;
11491 case FunctionDefinitionKind::Definition:
11492 break;
11493 }
11494
11495 // Similar to no_builtin logic above, at this point of the code
11496 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11497 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11498 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11499 !NewFD->isInvalidDecl() &&
11500 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
11501 ExternalDeclarations.push_back(Elt: NewFD);
11502
11503 // Used for a warning on the 'next' declaration when used with a
11504 // `routine(name)`.
11505 if (getLangOpts().OpenACC)
11506 OpenACC().ActOnFunctionDeclarator(FD: NewFD);
11507
11508 return NewFD;
11509}
11510
11511/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11512/// when __declspec(code_seg) "is applied to a class, all member functions of
11513/// the class and nested classes -- this includes compiler-generated special
11514/// member functions -- are put in the specified segment."
11515/// The actual behavior is a little more complicated. The Microsoft compiler
11516/// won't check outer classes if there is an active value from #pragma code_seg.
11517/// The CodeSeg is always applied from the direct parent but only from outer
11518/// classes when the #pragma code_seg stack is empty. See:
11519/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11520/// available since MS has removed the page.
11521static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
11522 const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
11523 if (!Method)
11524 return nullptr;
11525 const CXXRecordDecl *Parent = Method->getParent();
11526 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11527 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11528 NewAttr->setImplicit(true);
11529 return NewAttr;
11530 }
11531
11532 // The Microsoft compiler won't check outer classes for the CodeSeg
11533 // when the #pragma code_seg stack is active.
11534 if (S.CodeSegStack.CurrentValue)
11535 return nullptr;
11536
11537 while ((Parent = dyn_cast<CXXRecordDecl>(Val: Parent->getParent()))) {
11538 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11539 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11540 NewAttr->setImplicit(true);
11541 return NewAttr;
11542 }
11543 }
11544 return nullptr;
11545}
11546
11547Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
11548 bool IsDefinition) {
11549 if (Attr *A = getImplicitCodeSegAttrFromClass(S&: *this, FD))
11550 return A;
11551 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11552 CodeSegStack.CurrentValue)
11553 return SectionAttr::CreateImplicit(
11554 Ctx&: getASTContext(), Name: CodeSegStack.CurrentValue->getString(),
11555 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate);
11556 return nullptr;
11557}
11558
11559bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
11560 QualType NewT, QualType OldT) {
11561 if (!NewD->getLexicalDeclContext()->isDependentContext())
11562 return true;
11563
11564 // For dependently-typed local extern declarations and friends, we can't
11565 // perform a correct type check in general until instantiation:
11566 //
11567 // int f();
11568 // template<typename T> void g() { T f(); }
11569 //
11570 // (valid if g() is only instantiated with T = int).
11571 if (NewT->isDependentType() &&
11572 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11573 return false;
11574
11575 // Similarly, if the previous declaration was a dependent local extern
11576 // declaration, we don't really know its type yet.
11577 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11578 return false;
11579
11580 return true;
11581}
11582
11583bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11584 if (!D->getLexicalDeclContext()->isDependentContext())
11585 return true;
11586
11587 // Don't chain dependent friend function definitions until instantiation, to
11588 // permit cases like
11589 //
11590 // void func();
11591 // template<typename T> class C1 { friend void func() {} };
11592 // template<typename T> class C2 { friend void func() {} };
11593 //
11594 // ... which is valid if only one of C1 and C2 is ever instantiated.
11595 //
11596 // FIXME: This need only apply to function definitions. For now, we proxy
11597 // this by checking for a file-scope function. We do not want this to apply
11598 // to friend declarations nominating member functions, because that gets in
11599 // the way of access checks.
11600 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11601 return false;
11602
11603 auto *VD = dyn_cast<ValueDecl>(Val: D);
11604 auto *PrevVD = dyn_cast<ValueDecl>(Val: PrevDecl);
11605 return !VD || !PrevVD ||
11606 canFullyTypeCheckRedeclaration(NewD: VD, OldD: PrevVD, NewT: VD->getType(),
11607 OldT: PrevVD->getType());
11608}
11609
11610/// Check the target or target_version attribute of the function for
11611/// MultiVersion validity.
11612///
11613/// Returns true if there was an error, false otherwise.
11614static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11615 const auto *TA = FD->getAttr<TargetAttr>();
11616 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11617
11618 assert((TA || TVA) && "Expecting target or target_version attribute");
11619
11620 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11621 enum ErrType { Feature = 0, Architecture = 1 };
11622
11623 if (TA) {
11624 ParsedTargetAttr ParseInfo =
11625 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TA->getFeaturesStr());
11626 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(Name: ParseInfo.CPU)) {
11627 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11628 << Architecture << ParseInfo.CPU;
11629 return true;
11630 }
11631 for (const auto &Feat : ParseInfo.Features) {
11632 auto BareFeat = StringRef{Feat}.substr(Start: 1);
11633 if (Feat[0] == '-') {
11634 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11635 << Feature << ("no-" + BareFeat);
11636 return true;
11637 }
11638
11639 if (!TargetInfo.validateCpuSupports(Name: BareFeat) ||
11640 !TargetInfo.isValidFeatureName(Feature: BareFeat) ||
11641 (BareFeat != "default" && TargetInfo.getFMVPriority(Features: BareFeat) == 0)) {
11642 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11643 << Feature << BareFeat;
11644 return true;
11645 }
11646 }
11647 }
11648
11649 if (TVA) {
11650 llvm::SmallVector<StringRef, 8> Feats;
11651 ParsedTargetAttr ParseInfo;
11652 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11653 ParseInfo =
11654 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TVA->getName());
11655 for (auto &Feat : ParseInfo.Features)
11656 Feats.push_back(Elt: StringRef{Feat}.substr(Start: 1));
11657 } else {
11658 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11659 TVA->getFeatures(Out&: Feats);
11660 }
11661 for (const auto &Feat : Feats) {
11662 if (!TargetInfo.validateCpuSupports(Name: Feat)) {
11663 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11664 << Feature << Feat;
11665 return true;
11666 }
11667 }
11668 }
11669 return false;
11670}
11671
11672// Provide a white-list of attributes that are allowed to be combined with
11673// multiversion functions.
11674static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11675 MultiVersionKind MVKind) {
11676 // Note: this list/diagnosis must match the list in
11677 // checkMultiversionAttributesAllSame.
11678 switch (Kind) {
11679 default:
11680 return false;
11681 case attr::ArmLocallyStreaming:
11682 return MVKind == MultiVersionKind::TargetVersion ||
11683 MVKind == MultiVersionKind::TargetClones;
11684 case attr::Used:
11685 return MVKind == MultiVersionKind::Target;
11686 case attr::NonNull:
11687 case attr::NoThrow:
11688 return true;
11689 }
11690}
11691
11692static bool checkNonMultiVersionCompatAttributes(Sema &S,
11693 const FunctionDecl *FD,
11694 const FunctionDecl *CausedFD,
11695 MultiVersionKind MVKind) {
11696 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11697 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_disallowed_other_attr)
11698 << static_cast<unsigned>(MVKind) << A;
11699 if (CausedFD)
11700 S.Diag(Loc: CausedFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11701 return true;
11702 };
11703
11704 for (const Attr *A : FD->attrs()) {
11705 switch (A->getKind()) {
11706 case attr::CPUDispatch:
11707 case attr::CPUSpecific:
11708 if (MVKind != MultiVersionKind::CPUDispatch &&
11709 MVKind != MultiVersionKind::CPUSpecific)
11710 return Diagnose(S, A);
11711 break;
11712 case attr::Target:
11713 if (MVKind != MultiVersionKind::Target)
11714 return Diagnose(S, A);
11715 break;
11716 case attr::TargetVersion:
11717 if (MVKind != MultiVersionKind::TargetVersion &&
11718 MVKind != MultiVersionKind::TargetClones)
11719 return Diagnose(S, A);
11720 break;
11721 case attr::TargetClones:
11722 if (MVKind != MultiVersionKind::TargetClones &&
11723 MVKind != MultiVersionKind::TargetVersion)
11724 return Diagnose(S, A);
11725 break;
11726 default:
11727 if (!AttrCompatibleWithMultiVersion(Kind: A->getKind(), MVKind))
11728 return Diagnose(S, A);
11729 break;
11730 }
11731 }
11732 return false;
11733}
11734
11735bool Sema::areMultiversionVariantFunctionsCompatible(
11736 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11737 const PartialDiagnostic &NoProtoDiagID,
11738 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11739 const PartialDiagnosticAt &NoSupportDiagIDAt,
11740 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11741 bool ConstexprSupported, bool CLinkageMayDiffer) {
11742 enum DoesntSupport {
11743 FuncTemplates = 0,
11744 VirtFuncs = 1,
11745 DeducedReturn = 2,
11746 Constructors = 3,
11747 Destructors = 4,
11748 DeletedFuncs = 5,
11749 DefaultedFuncs = 6,
11750 ConstexprFuncs = 7,
11751 ConstevalFuncs = 8,
11752 Lambda = 9,
11753 };
11754 enum Different {
11755 CallingConv = 0,
11756 ReturnType = 1,
11757 ConstexprSpec = 2,
11758 InlineSpec = 3,
11759 Linkage = 4,
11760 LanguageLinkage = 5,
11761 };
11762
11763 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11764 !OldFD->getType()->getAs<FunctionProtoType>()) {
11765 Diag(Loc: OldFD->getLocation(), PD: NoProtoDiagID);
11766 Diag(Loc: NoteCausedDiagIDAt.first, PD: NoteCausedDiagIDAt.second);
11767 return true;
11768 }
11769
11770 if (NoProtoDiagID.getDiagID() != 0 &&
11771 !NewFD->getType()->getAs<FunctionProtoType>())
11772 return Diag(Loc: NewFD->getLocation(), PD: NoProtoDiagID);
11773
11774 if (!TemplatesSupported &&
11775 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11776 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11777 << FuncTemplates;
11778
11779 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
11780 if (NewCXXFD->isVirtual())
11781 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11782 << VirtFuncs;
11783
11784 if (isa<CXXConstructorDecl>(Val: NewCXXFD))
11785 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11786 << Constructors;
11787
11788 if (isa<CXXDestructorDecl>(Val: NewCXXFD))
11789 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11790 << Destructors;
11791 }
11792
11793 if (NewFD->isDeleted())
11794 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11795 << DeletedFuncs;
11796
11797 if (NewFD->isDefaulted())
11798 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11799 << DefaultedFuncs;
11800
11801 if (!ConstexprSupported && NewFD->isConstexpr())
11802 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11803 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11804
11805 QualType NewQType = Context.getCanonicalType(T: NewFD->getType());
11806 const auto *NewType = cast<FunctionType>(Val&: NewQType);
11807 QualType NewReturnType = NewType->getReturnType();
11808
11809 if (NewReturnType->isUndeducedType())
11810 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11811 << DeducedReturn;
11812
11813 // Ensure the return type is identical.
11814 if (OldFD) {
11815 QualType OldQType = Context.getCanonicalType(T: OldFD->getType());
11816 const auto *OldType = cast<FunctionType>(Val&: OldQType);
11817 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11818 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11819
11820 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11821 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11822
11823 bool ArmStreamingCCMismatched = false;
11824 if (OldFPT && NewFPT) {
11825 unsigned Diff =
11826 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11827 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11828 // cannot be mixed.
11829 if (Diff & (FunctionType::SME_PStateSMEnabledMask |
11830 FunctionType::SME_PStateSMCompatibleMask))
11831 ArmStreamingCCMismatched = true;
11832 }
11833
11834 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11835 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << CallingConv;
11836
11837 QualType OldReturnType = OldType->getReturnType();
11838
11839 if (OldReturnType != NewReturnType)
11840 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ReturnType;
11841
11842 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11843 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ConstexprSpec;
11844
11845 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11846 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << InlineSpec;
11847
11848 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11849 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << Linkage;
11850
11851 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11852 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << LanguageLinkage;
11853
11854 if (CheckEquivalentExceptionSpec(Old: OldFPT, OldLoc: OldFD->getLocation(), New: NewFPT,
11855 NewLoc: NewFD->getLocation()))
11856 return true;
11857 }
11858 return false;
11859}
11860
11861static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11862 const FunctionDecl *NewFD,
11863 bool CausesMV,
11864 MultiVersionKind MVKind) {
11865 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11866 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_supported);
11867 if (OldFD)
11868 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11869 return true;
11870 }
11871
11872 bool IsCPUSpecificCPUDispatchMVKind =
11873 MVKind == MultiVersionKind::CPUDispatch ||
11874 MVKind == MultiVersionKind::CPUSpecific;
11875
11876 if (CausesMV && OldFD &&
11877 checkNonMultiVersionCompatAttributes(S, FD: OldFD, CausedFD: NewFD, MVKind))
11878 return true;
11879
11880 if (checkNonMultiVersionCompatAttributes(S, FD: NewFD, CausedFD: nullptr, MVKind))
11881 return true;
11882
11883 // Only allow transition to MultiVersion if it hasn't been used.
11884 if (OldFD && CausesMV && OldFD->isUsed(CheckUsedAttr: false)) {
11885 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
11886 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11887 return true;
11888 }
11889
11890 return S.areMultiversionVariantFunctionsCompatible(
11891 OldFD, NewFD, NoProtoDiagID: S.PDiag(DiagID: diag::err_multiversion_noproto),
11892 NoteCausedDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11893 S.PDiag(DiagID: diag::note_multiversioning_caused_here)),
11894 NoSupportDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11895 S.PDiag(DiagID: diag::err_multiversion_doesnt_support)
11896 << static_cast<unsigned>(MVKind)),
11897 DiffDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11898 S.PDiag(DiagID: diag::err_multiversion_diff)),
11899 /*TemplatesSupported=*/false,
11900 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11901 /*CLinkageMayDiffer=*/false);
11902}
11903
11904/// Check the validity of a multiversion function declaration that is the
11905/// first of its kind. Also sets the multiversion'ness' of the function itself.
11906///
11907/// This sets NewFD->isInvalidDecl() to true if there was an error.
11908///
11909/// Returns true if there was an error, false otherwise.
11910static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11911 MultiVersionKind MVKind = FD->getMultiVersionKind();
11912 assert(MVKind != MultiVersionKind::None &&
11913 "Function lacks multiversion attribute");
11914 const auto *TA = FD->getAttr<TargetAttr>();
11915 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11916 // The target attribute only causes MV if this declaration is the default,
11917 // otherwise it is treated as a normal function.
11918 if (TA && !TA->isDefaultVersion())
11919 return false;
11920
11921 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11922 FD->setInvalidDecl();
11923 return true;
11924 }
11925
11926 if (CheckMultiVersionAdditionalRules(S, OldFD: nullptr, NewFD: FD, CausesMV: true, MVKind)) {
11927 FD->setInvalidDecl();
11928 return true;
11929 }
11930
11931 FD->setIsMultiVersion();
11932 return false;
11933}
11934
11935static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11936 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11937 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11938 return true;
11939 }
11940
11941 return false;
11942}
11943
11944static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
11945 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11946 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11947 return;
11948
11949 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11950 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11951
11952 if (MVKindTo == MultiVersionKind::None &&
11953 (MVKindFrom == MultiVersionKind::TargetVersion ||
11954 MVKindFrom == MultiVersionKind::TargetClones))
11955 To->addAttr(A: TargetVersionAttr::CreateImplicit(
11956 Ctx&: To->getASTContext(), NamesStr: "default", Range: To->getSourceRange()));
11957}
11958
11959static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11960 FunctionDecl *NewFD,
11961 bool &Redeclaration,
11962 NamedDecl *&OldDecl,
11963 LookupResult &Previous) {
11964 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11965
11966 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11967 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11968 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11969 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11970
11971 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11972
11973 // The definitions should be allowed in any order. If we have discovered
11974 // a new target version and the preceeding was the default, then add the
11975 // corresponding attribute to it.
11976 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11977
11978 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11979 // to change, this is a simple redeclaration.
11980 if (NewTA && !NewTA->isDefaultVersion() &&
11981 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11982 return false;
11983
11984 // Otherwise, this decl causes MultiVersioning.
11985 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, CausesMV: true,
11986 MVKind: NewTVA ? MultiVersionKind::TargetVersion
11987 : MultiVersionKind::Target)) {
11988 NewFD->setInvalidDecl();
11989 return true;
11990 }
11991
11992 if (CheckMultiVersionValue(S, FD: NewFD)) {
11993 NewFD->setInvalidDecl();
11994 return true;
11995 }
11996
11997 // If this is 'default', permit the forward declaration.
11998 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11999 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
12000 Redeclaration = true;
12001 OldDecl = OldFD;
12002 OldFD->setIsMultiVersion();
12003 NewFD->setIsMultiVersion();
12004 return false;
12005 }
12006
12007 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, FD: OldFD)) {
12008 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
12009 NewFD->setInvalidDecl();
12010 return true;
12011 }
12012
12013 if (NewTA) {
12014 ParsedTargetAttr OldParsed =
12015 S.getASTContext().getTargetInfo().parseTargetAttr(
12016 Str: OldTA->getFeaturesStr());
12017 llvm::sort(C&: OldParsed.Features);
12018 ParsedTargetAttr NewParsed =
12019 S.getASTContext().getTargetInfo().parseTargetAttr(
12020 Str: NewTA->getFeaturesStr());
12021 // Sort order doesn't matter, it just needs to be consistent.
12022 llvm::sort(C&: NewParsed.Features);
12023 if (OldParsed == NewParsed) {
12024 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12025 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
12026 NewFD->setInvalidDecl();
12027 return true;
12028 }
12029 }
12030
12031 for (const auto *FD : OldFD->redecls()) {
12032 const auto *CurTA = FD->getAttr<TargetAttr>();
12033 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
12034 // We allow forward declarations before ANY multiversioning attributes, but
12035 // nothing after the fact.
12036 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
12037 ((NewTA && (!CurTA || CurTA->isInherited())) ||
12038 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
12039 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
12040 << (NewTA ? 0 : 2);
12041 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
12042 NewFD->setInvalidDecl();
12043 return true;
12044 }
12045 }
12046
12047 OldFD->setIsMultiVersion();
12048 NewFD->setIsMultiVersion();
12049 Redeclaration = false;
12050 OldDecl = nullptr;
12051 Previous.clear();
12052 return false;
12053}
12054
12055static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {
12056 MultiVersionKind OldKind = Old->getMultiVersionKind();
12057 MultiVersionKind NewKind = New->getMultiVersionKind();
12058
12059 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
12060 NewKind == MultiVersionKind::None)
12061 return true;
12062
12063 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
12064 switch (OldKind) {
12065 case MultiVersionKind::TargetVersion:
12066 return NewKind == MultiVersionKind::TargetClones;
12067 case MultiVersionKind::TargetClones:
12068 return NewKind == MultiVersionKind::TargetVersion;
12069 default:
12070 return false;
12071 }
12072 } else {
12073 switch (OldKind) {
12074 case MultiVersionKind::CPUDispatch:
12075 return NewKind == MultiVersionKind::CPUSpecific;
12076 case MultiVersionKind::CPUSpecific:
12077 return NewKind == MultiVersionKind::CPUDispatch;
12078 default:
12079 return false;
12080 }
12081 }
12082}
12083
12084/// Check the validity of a new function declaration being added to an existing
12085/// multiversioned declaration collection.
12086static bool CheckMultiVersionAdditionalDecl(
12087 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
12088 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
12089 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
12090 LookupResult &Previous) {
12091
12092 // Disallow mixing of multiversioning types.
12093 if (!MultiVersionTypesCompatible(Old: OldFD, New: NewFD)) {
12094 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_types_mixed);
12095 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
12096 NewFD->setInvalidDecl();
12097 return true;
12098 }
12099
12100 // Add the default target_version attribute if it's missing.
12101 patchDefaultTargetVersion(From: OldFD, To: NewFD);
12102 patchDefaultTargetVersion(From: NewFD, To: OldFD);
12103
12104 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12105 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12106 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
12107 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
12108
12109 ParsedTargetAttr NewParsed;
12110 if (NewTA) {
12111 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
12112 Str: NewTA->getFeaturesStr());
12113 llvm::sort(C&: NewParsed.Features);
12114 }
12115 llvm::SmallVector<StringRef, 8> NewFeats;
12116 if (NewTVA) {
12117 NewTVA->getFeatures(Out&: NewFeats);
12118 llvm::sort(C&: NewFeats);
12119 }
12120
12121 bool UseMemberUsingDeclRules =
12122 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
12123
12124 bool MayNeedOverloadableChecks =
12125 AllowOverloadingOfFunction(Previous, Context&: S.Context, New: NewFD);
12126
12127 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
12128 // of a previous member of the MultiVersion set.
12129 for (NamedDecl *ND : Previous) {
12130 FunctionDecl *CurFD = ND->getAsFunction();
12131 if (!CurFD || CurFD->isInvalidDecl())
12132 continue;
12133 if (MayNeedOverloadableChecks &&
12134 S.IsOverload(New: NewFD, Old: CurFD, UseMemberUsingDeclRules))
12135 continue;
12136
12137 switch (NewMVKind) {
12138 case MultiVersionKind::None:
12139 assert(OldMVKind == MultiVersionKind::TargetClones &&
12140 "Only target_clones can be omitted in subsequent declarations");
12141 break;
12142 case MultiVersionKind::Target: {
12143 const auto *CurTA = CurFD->getAttr<TargetAttr>();
12144 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
12145 NewFD->setIsMultiVersion();
12146 Redeclaration = true;
12147 OldDecl = ND;
12148 return false;
12149 }
12150
12151 ParsedTargetAttr CurParsed =
12152 S.getASTContext().getTargetInfo().parseTargetAttr(
12153 Str: CurTA->getFeaturesStr());
12154 llvm::sort(C&: CurParsed.Features);
12155 if (CurParsed == NewParsed) {
12156 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12157 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12158 NewFD->setInvalidDecl();
12159 return true;
12160 }
12161 break;
12162 }
12163 case MultiVersionKind::TargetVersion: {
12164 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12165 if (CurTVA->getName() == NewTVA->getName()) {
12166 NewFD->setIsMultiVersion();
12167 Redeclaration = true;
12168 OldDecl = ND;
12169 return false;
12170 }
12171 llvm::SmallVector<StringRef, 8> CurFeats;
12172 CurTVA->getFeatures(Out&: CurFeats);
12173 llvm::sort(C&: CurFeats);
12174
12175 if (CurFeats == NewFeats) {
12176 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12177 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12178 NewFD->setInvalidDecl();
12179 return true;
12180 }
12181 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12182 // Default
12183 if (NewFeats.empty())
12184 break;
12185
12186 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
12187 llvm::SmallVector<StringRef, 8> CurFeats;
12188 CurClones->getFeatures(Out&: CurFeats, Index: I);
12189 llvm::sort(C&: CurFeats);
12190
12191 if (CurFeats == NewFeats) {
12192 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12193 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12194 NewFD->setInvalidDecl();
12195 return true;
12196 }
12197 }
12198 }
12199 break;
12200 }
12201 case MultiVersionKind::TargetClones: {
12202 assert(NewClones && "MultiVersionKind does not match attribute type");
12203 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12204 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
12205 !std::equal(first1: CurClones->featuresStrs_begin(),
12206 last1: CurClones->featuresStrs_end(),
12207 first2: NewClones->featuresStrs_begin())) {
12208 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_target_clone_doesnt_match);
12209 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12210 NewFD->setInvalidDecl();
12211 return true;
12212 }
12213 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12214 llvm::SmallVector<StringRef, 8> CurFeats;
12215 CurTVA->getFeatures(Out&: CurFeats);
12216 llvm::sort(C&: CurFeats);
12217
12218 // Default
12219 if (CurFeats.empty())
12220 break;
12221
12222 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
12223 NewFeats.clear();
12224 NewClones->getFeatures(Out&: NewFeats, Index: I);
12225 llvm::sort(C&: NewFeats);
12226
12227 if (CurFeats == NewFeats) {
12228 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12229 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12230 NewFD->setInvalidDecl();
12231 return true;
12232 }
12233 }
12234 break;
12235 }
12236 Redeclaration = true;
12237 OldDecl = CurFD;
12238 NewFD->setIsMultiVersion();
12239 return false;
12240 }
12241 case MultiVersionKind::CPUSpecific:
12242 case MultiVersionKind::CPUDispatch: {
12243 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
12244 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
12245 // Handle CPUDispatch/CPUSpecific versions.
12246 // Only 1 CPUDispatch function is allowed, this will make it go through
12247 // the redeclaration errors.
12248 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12249 CurFD->hasAttr<CPUDispatchAttr>()) {
12250 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12251 std::equal(
12252 first1: CurCPUDisp->cpus_begin(), last1: CurCPUDisp->cpus_end(),
12253 first2: NewCPUDisp->cpus_begin(),
12254 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12255 return Cur->getName() == New->getName();
12256 })) {
12257 NewFD->setIsMultiVersion();
12258 Redeclaration = true;
12259 OldDecl = ND;
12260 return false;
12261 }
12262
12263 // If the declarations don't match, this is an error condition.
12264 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_dispatch_mismatch);
12265 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12266 NewFD->setInvalidDecl();
12267 return true;
12268 }
12269 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12270 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12271 std::equal(
12272 first1: CurCPUSpec->cpus_begin(), last1: CurCPUSpec->cpus_end(),
12273 first2: NewCPUSpec->cpus_begin(),
12274 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12275 return Cur->getName() == New->getName();
12276 })) {
12277 NewFD->setIsMultiVersion();
12278 Redeclaration = true;
12279 OldDecl = ND;
12280 return false;
12281 }
12282
12283 // Only 1 version of CPUSpecific is allowed for each CPU.
12284 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12285 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12286 if (CurII == NewII) {
12287 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_specific_multiple_defs)
12288 << NewII;
12289 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12290 NewFD->setInvalidDecl();
12291 return true;
12292 }
12293 }
12294 }
12295 }
12296 break;
12297 }
12298 }
12299 }
12300
12301 // Redeclarations of a target_clones function may omit the attribute, in which
12302 // case it will be inherited during declaration merging.
12303 if (NewMVKind == MultiVersionKind::None &&
12304 OldMVKind == MultiVersionKind::TargetClones) {
12305 NewFD->setIsMultiVersion();
12306 Redeclaration = true;
12307 OldDecl = OldFD;
12308 return false;
12309 }
12310
12311 // Else, this is simply a non-redecl case. Checking the 'value' is only
12312 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12313 // handled in the attribute adding step.
12314 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, FD: NewFD)) {
12315 NewFD->setInvalidDecl();
12316 return true;
12317 }
12318
12319 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12320 CausesMV: !OldFD->isMultiVersion(), MVKind: NewMVKind)) {
12321 NewFD->setInvalidDecl();
12322 return true;
12323 }
12324
12325 // Permit forward declarations in the case where these two are compatible.
12326 if (!OldFD->isMultiVersion()) {
12327 OldFD->setIsMultiVersion();
12328 NewFD->setIsMultiVersion();
12329 Redeclaration = true;
12330 OldDecl = OldFD;
12331 return false;
12332 }
12333
12334 NewFD->setIsMultiVersion();
12335 Redeclaration = false;
12336 OldDecl = nullptr;
12337 Previous.clear();
12338 return false;
12339}
12340
12341/// Check the validity of a mulitversion function declaration.
12342/// Also sets the multiversion'ness' of the function itself.
12343///
12344/// This sets NewFD->isInvalidDecl() to true if there was an error.
12345///
12346/// Returns true if there was an error, false otherwise.
12347static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
12348 bool &Redeclaration, NamedDecl *&OldDecl,
12349 LookupResult &Previous) {
12350 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12351
12352 // Check if FMV is disabled.
12353 if (TI.getTriple().isAArch64() && !TI.hasFeature(Feature: "fmv"))
12354 return false;
12355
12356 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12357 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12358 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12359 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12360 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12361 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12362
12363 // Main isn't allowed to become a multiversion function, however it IS
12364 // permitted to have 'main' be marked with the 'target' optimization hint,
12365 // for 'target_version' only default is allowed.
12366 if (NewFD->isMain()) {
12367 if (MVKind != MultiVersionKind::None &&
12368 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12369 !(MVKind == MultiVersionKind::TargetVersion &&
12370 NewTVA->isDefaultVersion())) {
12371 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_allowed_on_main);
12372 NewFD->setInvalidDecl();
12373 return true;
12374 }
12375 return false;
12376 }
12377
12378 // Target attribute on AArch64 is not used for multiversioning
12379 if (NewTA && TI.getTriple().isAArch64())
12380 return false;
12381
12382 // Target attribute on RISCV is not used for multiversioning
12383 if (NewTA && TI.getTriple().isRISCV())
12384 return false;
12385
12386 if (!OldDecl || !OldDecl->getAsFunction() ||
12387 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12388 DC: NewFD->getDeclContext()->getRedeclContext())) {
12389 // If there's no previous declaration, AND this isn't attempting to cause
12390 // multiversioning, this isn't an error condition.
12391 if (MVKind == MultiVersionKind::None)
12392 return false;
12393 return CheckMultiVersionFirstFunction(S, FD: NewFD);
12394 }
12395
12396 FunctionDecl *OldFD = OldDecl->getAsFunction();
12397
12398 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12399 return false;
12400
12401 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12402 // for target_clones and target_version.
12403 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12404 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
12405 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
12406 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
12407 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
12408 NewFD->setInvalidDecl();
12409 return true;
12410 }
12411
12412 if (!OldFD->isMultiVersion()) {
12413 switch (MVKind) {
12414 case MultiVersionKind::Target:
12415 case MultiVersionKind::TargetVersion:
12416 return CheckDeclarationCausesMultiVersioning(
12417 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12418 case MultiVersionKind::TargetClones:
12419 if (OldFD->isUsed(CheckUsedAttr: false)) {
12420 NewFD->setInvalidDecl();
12421 return S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
12422 }
12423 OldFD->setIsMultiVersion();
12424 break;
12425
12426 case MultiVersionKind::CPUDispatch:
12427 case MultiVersionKind::CPUSpecific:
12428 case MultiVersionKind::None:
12429 break;
12430 }
12431 }
12432
12433 // At this point, we have a multiversion function decl (in OldFD) AND an
12434 // appropriate attribute in the current function decl (unless it's allowed to
12435 // omit the attribute). Resolve that these are still compatible with previous
12436 // declarations.
12437 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12438 NewCPUSpec, NewClones, Redeclaration,
12439 OldDecl, Previous);
12440}
12441
12442static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {
12443 bool IsPure = NewFD->hasAttr<PureAttr>();
12444 bool IsConst = NewFD->hasAttr<ConstAttr>();
12445
12446 // If there are no pure or const attributes, there's nothing to check.
12447 if (!IsPure && !IsConst)
12448 return;
12449
12450 // If the function is marked both pure and const, we retain the const
12451 // attribute because it makes stronger guarantees than the pure attribute, and
12452 // we drop the pure attribute explicitly to prevent later confusion about
12453 // semantics.
12454 if (IsPure && IsConst) {
12455 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_const_attr_with_pure_attr);
12456 NewFD->dropAttrs<PureAttr>();
12457 }
12458
12459 // Constructors and destructors are functions which return void, so are
12460 // handled here as well.
12461 if (NewFD->getReturnType()->isVoidType()) {
12462 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_pure_function_returns_void)
12463 << IsConst;
12464 NewFD->dropAttrs<PureAttr, ConstAttr>();
12465 }
12466}
12467
12468bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
12469 LookupResult &Previous,
12470 bool IsMemberSpecialization,
12471 bool DeclIsDefn) {
12472 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12473 "Variably modified return types are not handled here");
12474
12475 // Determine whether the type of this function should be merged with
12476 // a previous visible declaration. This never happens for functions in C++,
12477 // and always happens in C if the previous declaration was visible.
12478 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12479 !Previous.isShadowed();
12480
12481 bool Redeclaration = false;
12482 NamedDecl *OldDecl = nullptr;
12483 bool MayNeedOverloadableChecks = false;
12484
12485 inferLifetimeCaptureByAttribute(FD: NewFD);
12486 // Merge or overload the declaration with an existing declaration of
12487 // the same name, if appropriate.
12488 if (!Previous.empty()) {
12489 // Determine whether NewFD is an overload of PrevDecl or
12490 // a declaration that requires merging. If it's an overload,
12491 // there's no more work to do here; we'll just add the new
12492 // function to the scope.
12493 if (!AllowOverloadingOfFunction(Previous, Context, New: NewFD)) {
12494 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12495 if (shouldLinkPossiblyHiddenDecl(Old: Candidate, New: NewFD)) {
12496 Redeclaration = true;
12497 OldDecl = Candidate;
12498 }
12499 } else {
12500 MayNeedOverloadableChecks = true;
12501 switch (CheckOverload(S, New: NewFD, OldDecls: Previous, OldDecl,
12502 /*NewIsUsingDecl*/ UseMemberUsingDeclRules: false)) {
12503 case OverloadKind::Match:
12504 Redeclaration = true;
12505 break;
12506
12507 case OverloadKind::NonFunction:
12508 Redeclaration = true;
12509 break;
12510
12511 case OverloadKind::Overload:
12512 Redeclaration = false;
12513 break;
12514 }
12515 }
12516 }
12517
12518 // Check for a previous extern "C" declaration with this name.
12519 if (!Redeclaration &&
12520 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewFD, Previous)) {
12521 if (!Previous.empty()) {
12522 // This is an extern "C" declaration with the same name as a previous
12523 // declaration, and thus redeclares that entity...
12524 Redeclaration = true;
12525 OldDecl = Previous.getFoundDecl();
12526 MergeTypeWithPrevious = false;
12527
12528 // ... except in the presence of __attribute__((overloadable)).
12529 if (OldDecl->hasAttr<OverloadableAttr>() ||
12530 NewFD->hasAttr<OverloadableAttr>()) {
12531 if (IsOverload(New: NewFD, Old: cast<FunctionDecl>(Val: OldDecl), UseMemberUsingDeclRules: false)) {
12532 MayNeedOverloadableChecks = true;
12533 Redeclaration = false;
12534 OldDecl = nullptr;
12535 }
12536 }
12537 }
12538 }
12539
12540 if (CheckMultiVersionFunction(S&: *this, NewFD, Redeclaration, OldDecl, Previous))
12541 return Redeclaration;
12542
12543 // PPC MMA non-pointer types are not allowed as function return types.
12544 if (Context.getTargetInfo().getTriple().isPPC64() &&
12545 PPC().CheckPPCMMAType(Type: NewFD->getReturnType(), TypeLoc: NewFD->getLocation())) {
12546 NewFD->setInvalidDecl();
12547 }
12548
12549 CheckConstPureAttributesUsage(S&: *this, NewFD);
12550
12551 // C++ [dcl.spec.auto.general]p12:
12552 // Return type deduction for a templated function with a placeholder in its
12553 // declared type occurs when the definition is instantiated even if the
12554 // function body contains a return statement with a non-type-dependent
12555 // operand.
12556 //
12557 // C++ [temp.dep.expr]p3:
12558 // An id-expression is type-dependent if it is a template-id that is not a
12559 // concept-id and is dependent; or if its terminal name is:
12560 // - [...]
12561 // - associated by name lookup with one or more declarations of member
12562 // functions of a class that is the current instantiation declared with a
12563 // return type that contains a placeholder type,
12564 // - [...]
12565 //
12566 // If this is a templated function with a placeholder in its return type,
12567 // make the placeholder type dependent since it won't be deduced until the
12568 // definition is instantiated. We do this here because it needs to happen
12569 // for implicitly instantiated member functions/member function templates.
12570 if (getLangOpts().CPlusPlus14 &&
12571 (NewFD->isDependentContext() &&
12572 NewFD->getReturnType()->isUndeducedType())) {
12573 const FunctionProtoType *FPT =
12574 NewFD->getType()->castAs<FunctionProtoType>();
12575 QualType NewReturnType = SubstAutoTypeDependent(TypeWithAuto: FPT->getReturnType());
12576 NewFD->setType(Context.getFunctionType(ResultTy: NewReturnType, Args: FPT->getParamTypes(),
12577 EPI: FPT->getExtProtoInfo()));
12578 }
12579
12580 // C++11 [dcl.constexpr]p8:
12581 // A constexpr specifier for a non-static member function that is not
12582 // a constructor declares that member function to be const.
12583 //
12584 // This needs to be delayed until we know whether this is an out-of-line
12585 // definition of a static member function.
12586 //
12587 // This rule is not present in C++1y, so we produce a backwards
12588 // compatibility warning whenever it happens in C++11.
12589 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
12590 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12591 !MD->isStatic() && !isa<CXXConstructorDecl>(Val: MD) &&
12592 !isa<CXXDestructorDecl>(Val: MD) && !MD->getMethodQualifiers().hasConst()) {
12593 CXXMethodDecl *OldMD = nullptr;
12594 if (OldDecl)
12595 OldMD = dyn_cast_or_null<CXXMethodDecl>(Val: OldDecl->getAsFunction());
12596 if (!OldMD || !OldMD->isStatic()) {
12597 const FunctionProtoType *FPT =
12598 MD->getType()->castAs<FunctionProtoType>();
12599 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12600 EPI.TypeQuals.addConst();
12601 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
12602 Args: FPT->getParamTypes(), EPI));
12603
12604 // Warn that we did this, if we're not performing template instantiation.
12605 // In that case, we'll have warned already when the template was defined.
12606 if (!inTemplateInstantiation()) {
12607 SourceLocation AddConstLoc;
12608 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
12609 .IgnoreParens().getAs<FunctionTypeLoc>())
12610 AddConstLoc = getLocForEndOfToken(Loc: FTL.getRParenLoc());
12611
12612 Diag(Loc: MD->getLocation(), DiagID: diag::warn_cxx14_compat_constexpr_not_const)
12613 << FixItHint::CreateInsertion(InsertionLoc: AddConstLoc, Code: " const");
12614 }
12615 }
12616 }
12617
12618 if (Redeclaration) {
12619 // NewFD and OldDecl represent declarations that need to be
12620 // merged.
12621 if (MergeFunctionDecl(New: NewFD, OldD&: OldDecl, S, MergeTypeWithOld: MergeTypeWithPrevious,
12622 NewDeclIsDefn: DeclIsDefn)) {
12623 NewFD->setInvalidDecl();
12624 return Redeclaration;
12625 }
12626
12627 Previous.clear();
12628 Previous.addDecl(D: OldDecl);
12629
12630 if (FunctionTemplateDecl *OldTemplateDecl =
12631 dyn_cast<FunctionTemplateDecl>(Val: OldDecl)) {
12632 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12633 FunctionTemplateDecl *NewTemplateDecl
12634 = NewFD->getDescribedFunctionTemplate();
12635 assert(NewTemplateDecl && "Template/non-template mismatch");
12636
12637 // The call to MergeFunctionDecl above may have created some state in
12638 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12639 // can add it as a redeclaration.
12640 NewTemplateDecl->mergePrevDecl(Prev: OldTemplateDecl);
12641
12642 NewFD->setPreviousDeclaration(OldFD);
12643 if (NewFD->isCXXClassMember()) {
12644 NewFD->setAccess(OldTemplateDecl->getAccess());
12645 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12646 }
12647
12648 // If this is an explicit specialization of a member that is a function
12649 // template, mark it as a member specialization.
12650 if (IsMemberSpecialization &&
12651 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12652 NewTemplateDecl->setMemberSpecialization();
12653 assert(OldTemplateDecl->isMemberSpecialization());
12654 // Explicit specializations of a member template do not inherit deleted
12655 // status from the parent member template that they are specializing.
12656 if (OldFD->isDeleted()) {
12657 // FIXME: This assert will not hold in the presence of modules.
12658 assert(OldFD->getCanonicalDecl() == OldFD);
12659 // FIXME: We need an update record for this AST mutation.
12660 OldFD->setDeletedAsWritten(D: false);
12661 }
12662 }
12663
12664 } else {
12665 if (shouldLinkDependentDeclWithPrevious(D: NewFD, PrevDecl: OldDecl)) {
12666 auto *OldFD = cast<FunctionDecl>(Val: OldDecl);
12667 // This needs to happen first so that 'inline' propagates.
12668 NewFD->setPreviousDeclaration(OldFD);
12669 if (NewFD->isCXXClassMember())
12670 NewFD->setAccess(OldFD->getAccess());
12671 }
12672 }
12673 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12674 !NewFD->getAttr<OverloadableAttr>()) {
12675 assert((Previous.empty() ||
12676 llvm::any_of(Previous,
12677 [](const NamedDecl *ND) {
12678 return ND->hasAttr<OverloadableAttr>();
12679 })) &&
12680 "Non-redecls shouldn't happen without overloadable present");
12681
12682 auto OtherUnmarkedIter = llvm::find_if(Range&: Previous, P: [](const NamedDecl *ND) {
12683 const auto *FD = dyn_cast<FunctionDecl>(Val: ND);
12684 return FD && !FD->hasAttr<OverloadableAttr>();
12685 });
12686
12687 if (OtherUnmarkedIter != Previous.end()) {
12688 Diag(Loc: NewFD->getLocation(),
12689 DiagID: diag::err_attribute_overloadable_multiple_unmarked_overloads);
12690 Diag(Loc: (*OtherUnmarkedIter)->getLocation(),
12691 DiagID: diag::note_attribute_overloadable_prev_overload)
12692 << false;
12693
12694 NewFD->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
12695 }
12696 }
12697
12698 if (LangOpts.OpenMP)
12699 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(D: NewFD);
12700
12701 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12702 SYCL().CheckSYCLEntryPointFunctionDecl(FD: NewFD);
12703
12704 if (NewFD->hasAttr<SYCLExternalAttr>())
12705 SYCL().CheckSYCLExternalFunctionDecl(FD: NewFD);
12706
12707 // Semantic checking for this function declaration (in isolation).
12708
12709 if (getLangOpts().CPlusPlus) {
12710 // C++-specific checks.
12711 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: NewFD)) {
12712 CheckConstructor(Constructor);
12713 } else if (CXXDestructorDecl *Destructor =
12714 dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
12715 // We check here for invalid destructor names.
12716 // If we have a friend destructor declaration that is dependent, we can't
12717 // diagnose right away because cases like this are still valid:
12718 // template <class T> struct A { friend T::X::~Y(); };
12719 // struct B { struct Y { ~Y(); }; using X = Y; };
12720 // template struct A<B>;
12721 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12722 (!Destructor->getFunctionObjectParameterType()->isDependentType() &&
12723 !Destructor->getDeclName().isDependentName())) {
12724 CanQualType ClassType =
12725 Context.getCanonicalTagType(TD: Destructor->getParent());
12726
12727 DeclarationName Name =
12728 Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
12729 if (NewFD->getDeclName() != Name) {
12730 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_name);
12731 NewFD->setInvalidDecl();
12732 return Redeclaration;
12733 }
12734 }
12735 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: NewFD)) {
12736 if (auto *TD = Guide->getDescribedFunctionTemplate())
12737 CheckDeductionGuideTemplate(TD);
12738
12739 // A deduction guide is not on the list of entities that can be
12740 // explicitly specialized.
12741 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12742 Diag(Loc: Guide->getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
12743 << /*explicit specialization*/ 1;
12744 }
12745
12746 // Find any virtual functions that this function overrides.
12747 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
12748 if (!Method->isFunctionTemplateSpecialization() &&
12749 !Method->getDescribedFunctionTemplate() &&
12750 Method->isCanonicalDecl()) {
12751 AddOverriddenMethods(DC: Method->getParent(), MD: Method);
12752 }
12753 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12754 // C++2a [class.virtual]p6
12755 // A virtual method shall not have a requires-clause.
12756 Diag(Loc: NewFD->getTrailingRequiresClause().ConstraintExpr->getBeginLoc(),
12757 DiagID: diag::err_constrained_virtual_method);
12758
12759 if (Method->isStatic())
12760 checkThisInStaticMemberFunctionType(Method);
12761 }
12762
12763 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: NewFD))
12764 ActOnConversionDeclarator(Conversion);
12765
12766 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12767 if (NewFD->isOverloadedOperator() &&
12768 CheckOverloadedOperatorDeclaration(FnDecl: NewFD)) {
12769 NewFD->setInvalidDecl();
12770 return Redeclaration;
12771 }
12772
12773 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12774 if (NewFD->getLiteralIdentifier() &&
12775 CheckLiteralOperatorDeclaration(FnDecl: NewFD)) {
12776 NewFD->setInvalidDecl();
12777 return Redeclaration;
12778 }
12779
12780 // In C++, check default arguments now that we have merged decls. Unless
12781 // the lexical context is the class, because in this case this is done
12782 // during delayed parsing anyway.
12783 if (!CurContext->isRecord())
12784 CheckCXXDefaultArguments(FD: NewFD);
12785
12786 // If this function is declared as being extern "C", then check to see if
12787 // the function returns a UDT (class, struct, or union type) that is not C
12788 // compatible, and if it does, warn the user.
12789 // But, issue any diagnostic on the first declaration only.
12790 if (Previous.empty() && NewFD->isExternC()) {
12791 QualType R = NewFD->getReturnType();
12792 if (R->isIncompleteType() && !R->isVoidType())
12793 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt_incomplete)
12794 << NewFD << R;
12795 else if (!R.isPODType(Context) && !R->isVoidType() &&
12796 !R->isObjCObjectPointerType())
12797 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt) << NewFD << R;
12798 }
12799
12800 // C++1z [dcl.fct]p6:
12801 // [...] whether the function has a non-throwing exception-specification
12802 // [is] part of the function type
12803 //
12804 // This results in an ABI break between C++14 and C++17 for functions whose
12805 // declared type includes an exception-specification in a parameter or
12806 // return type. (Exception specifications on the function itself are OK in
12807 // most cases, and exception specifications are not permitted in most other
12808 // contexts where they could make it into a mangling.)
12809 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12810 auto HasNoexcept = [&](QualType T) -> bool {
12811 // Strip off declarator chunks that could be between us and a function
12812 // type. We don't need to look far, exception specifications are very
12813 // restricted prior to C++17.
12814 if (auto *RT = T->getAs<ReferenceType>())
12815 T = RT->getPointeeType();
12816 else if (T->isAnyPointerType())
12817 T = T->getPointeeType();
12818 else if (auto *MPT = T->getAs<MemberPointerType>())
12819 T = MPT->getPointeeType();
12820 if (auto *FPT = T->getAs<FunctionProtoType>())
12821 if (FPT->isNothrow())
12822 return true;
12823 return false;
12824 };
12825
12826 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12827 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12828 for (QualType T : FPT->param_types())
12829 AnyNoexcept |= HasNoexcept(T);
12830 if (AnyNoexcept)
12831 Diag(Loc: NewFD->getLocation(),
12832 DiagID: diag::warn_cxx17_compat_exception_spec_in_signature)
12833 << NewFD;
12834 }
12835
12836 if (!Redeclaration && LangOpts.CUDA) {
12837 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12838 for (auto *Parm : NewFD->parameters()) {
12839 if (!Parm->getType()->isDependentType() &&
12840 Parm->hasAttr<CUDAGridConstantAttr>() &&
12841 !(IsKernel && Parm->getType().isConstQualified()))
12842 Diag(Loc: Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12843 DiagID: diag::err_cuda_grid_constant_not_allowed);
12844 }
12845 CUDA().checkTargetOverload(NewFD, Previous);
12846 }
12847 }
12848
12849 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12850 ARM().CheckSMEFunctionDefAttributes(FD: NewFD);
12851
12852 return Redeclaration;
12853}
12854
12855void Sema::CheckMain(FunctionDecl *FD, const DeclSpec &DS) {
12856 // [basic.start.main]p3
12857 // The main function shall not be declared with C linkage-specification.
12858 if (FD->isExternCContext())
12859 Diag(Loc: FD->getLocation(), DiagID: diag::ext_main_invalid_linkage_specification);
12860
12861 // C++11 [basic.start.main]p3:
12862 // A program that [...] declares main to be inline, static or
12863 // constexpr is ill-formed.
12864 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12865 // appear in a declaration of main.
12866 // static main is not an error under C99, but we should warn about it.
12867 // We accept _Noreturn main as an extension.
12868 if (FD->getStorageClass() == SC_Static)
12869 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus
12870 ? diag::err_static_main : diag::warn_static_main)
12871 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
12872 if (FD->isInlineSpecified())
12873 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_main)
12874 << FixItHint::CreateRemoval(RemoveRange: DS.getInlineSpecLoc());
12875 if (DS.isNoreturnSpecified()) {
12876 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12877 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(Loc: NoreturnLoc));
12878 Diag(Loc: NoreturnLoc, DiagID: diag::ext_noreturn_main);
12879 Diag(Loc: NoreturnLoc, DiagID: diag::note_main_remove_noreturn)
12880 << FixItHint::CreateRemoval(RemoveRange: NoreturnRange);
12881 }
12882 if (FD->isConstexpr()) {
12883 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_main)
12884 << FD->isConsteval()
12885 << FixItHint::CreateRemoval(RemoveRange: DS.getConstexprSpecLoc());
12886 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12887 }
12888
12889 if (getLangOpts().OpenCL) {
12890 Diag(Loc: FD->getLocation(), DiagID: diag::err_opencl_no_main)
12891 << FD->hasAttr<DeviceKernelAttr>();
12892 FD->setInvalidDecl();
12893 return;
12894 }
12895
12896 if (FD->hasAttr<SYCLExternalAttr>()) {
12897 Diag(Loc: FD->getLocation(), DiagID: diag::err_sycl_external_invalid_main)
12898 << FD->getAttr<SYCLExternalAttr>();
12899 FD->setInvalidDecl();
12900 return;
12901 }
12902
12903 // Functions named main in hlsl are default entries, but don't have specific
12904 // signatures they are required to conform to.
12905 if (getLangOpts().HLSL)
12906 return;
12907
12908 QualType T = FD->getType();
12909 assert(T->isFunctionType() && "function decl is not of function type");
12910 const FunctionType* FT = T->castAs<FunctionType>();
12911
12912 // Set default calling convention for main()
12913 if (FT->getCallConv() != CC_C) {
12914 FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12915 FD->setType(QualType(FT, 0));
12916 T = Context.getCanonicalType(T: FD->getType());
12917 }
12918
12919 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12920 // In C with GNU extensions we allow main() to have non-integer return
12921 // type, but we should warn about the extension, and we disable the
12922 // implicit-return-zero rule.
12923
12924 // GCC in C mode accepts qualified 'int'.
12925 if (Context.hasSameUnqualifiedType(T1: FT->getReturnType(), T2: Context.IntTy))
12926 FD->setHasImplicitReturnZero(true);
12927 else {
12928 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::ext_main_returns_nonint);
12929 SourceRange RTRange = FD->getReturnTypeSourceRange();
12930 if (RTRange.isValid())
12931 Diag(Loc: RTRange.getBegin(), DiagID: diag::note_main_change_return_type)
12932 << FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int");
12933 }
12934 } else {
12935 // In C and C++, main magically returns 0 if you fall off the end;
12936 // set the flag which tells us that.
12937 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12938
12939 // All the standards say that main() should return 'int'.
12940 if (Context.hasSameType(T1: FT->getReturnType(), T2: Context.IntTy))
12941 FD->setHasImplicitReturnZero(true);
12942 else {
12943 // Otherwise, this is just a flat-out error.
12944 SourceRange RTRange = FD->getReturnTypeSourceRange();
12945 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::err_main_returns_nonint)
12946 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int")
12947 : FixItHint());
12948 FD->setInvalidDecl(true);
12949 }
12950
12951 // [basic.start.main]p3:
12952 // A program that declares a function main that belongs to the global scope
12953 // and is attached to a named module is ill-formed.
12954 if (FD->isInNamedModule()) {
12955 const SourceLocation start = FD->getTypeSpecStartLoc();
12956 Diag(Loc: start, DiagID: diag::warn_main_in_named_module)
12957 << FixItHint::CreateInsertion(InsertionLoc: start, Code: "extern \"C++\" ", BeforePreviousInsertions: true);
12958 }
12959 }
12960
12961 // Treat protoless main() as nullary.
12962 if (isa<FunctionNoProtoType>(Val: FT)) return;
12963
12964 const FunctionProtoType* FTP = cast<const FunctionProtoType>(Val: FT);
12965 unsigned nparams = FTP->getNumParams();
12966 assert(FD->getNumParams() == nparams);
12967
12968 bool HasExtraParameters = (nparams > 3);
12969
12970 if (FTP->isVariadic()) {
12971 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variadic_main);
12972 // FIXME: if we had information about the location of the ellipsis, we
12973 // could add a FixIt hint to remove it as a parameter.
12974 }
12975
12976 // Darwin passes an undocumented fourth argument of type char**. If
12977 // other platforms start sprouting these, the logic below will start
12978 // getting shifty.
12979 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12980 HasExtraParameters = false;
12981
12982 if (HasExtraParameters) {
12983 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_surplus_args) << nparams;
12984 FD->setInvalidDecl(true);
12985 nparams = 3;
12986 }
12987
12988 // FIXME: a lot of the following diagnostics would be improved
12989 // if we had some location information about types.
12990
12991 QualType CharPP =
12992 Context.getPointerType(T: Context.getPointerType(T: Context.CharTy));
12993 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12994
12995 for (unsigned i = 0; i < nparams; ++i) {
12996 QualType AT = FTP->getParamType(i);
12997
12998 bool mismatch = true;
12999
13000 if (Context.hasSameUnqualifiedType(T1: AT, T2: Expected[i]))
13001 mismatch = false;
13002 else if (Expected[i] == CharPP) {
13003 // As an extension, the following forms are okay:
13004 // char const **
13005 // char const * const *
13006 // char * const *
13007
13008 QualifierCollector qs;
13009 const PointerType* PT;
13010 if ((PT = qs.strip(type: AT)->getAs<PointerType>()) &&
13011 (PT = qs.strip(type: PT->getPointeeType())->getAs<PointerType>()) &&
13012 Context.hasSameType(T1: QualType(qs.strip(type: PT->getPointeeType()), 0),
13013 T2: Context.CharTy)) {
13014 qs.removeConst();
13015 mismatch = !qs.empty();
13016 }
13017 }
13018
13019 if (mismatch) {
13020 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_arg_wrong) << i << Expected[i];
13021 // TODO: suggest replacing given type with expected type
13022 FD->setInvalidDecl(true);
13023 }
13024 }
13025
13026 if (nparams == 1 && !FD->isInvalidDecl()) {
13027 Diag(Loc: FD->getLocation(), DiagID: diag::warn_main_one_arg);
13028 }
13029
13030 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
13031 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
13032 FD->setInvalidDecl();
13033 }
13034}
13035
13036static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
13037
13038 // Default calling convention for main and wmain is __cdecl
13039 if (FD->getName() == "main" || FD->getName() == "wmain")
13040 return false;
13041
13042 // Default calling convention for MinGW and Cygwin is __cdecl
13043 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
13044 if (T.isOSCygMing())
13045 return false;
13046
13047 // Default calling convention for WinMain, wWinMain and DllMain
13048 // is __stdcall on 32 bit Windows
13049 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
13050 return true;
13051
13052 return false;
13053}
13054
13055void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
13056 QualType T = FD->getType();
13057 assert(T->isFunctionType() && "function decl is not of function type");
13058 const FunctionType *FT = T->castAs<FunctionType>();
13059
13060 // Set an implicit return of 'zero' if the function can return some integral,
13061 // enumeration, pointer or nullptr type.
13062 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
13063 FT->getReturnType()->isAnyPointerType() ||
13064 FT->getReturnType()->isNullPtrType())
13065 // DllMain is exempt because a return value of zero means it failed.
13066 if (FD->getName() != "DllMain")
13067 FD->setHasImplicitReturnZero(true);
13068
13069 // Explicitly specified calling conventions are applied to MSVC entry points
13070 if (!hasExplicitCallingConv(T)) {
13071 if (isDefaultStdCall(FD, S&: *this)) {
13072 if (FT->getCallConv() != CC_X86StdCall) {
13073 FT = Context.adjustFunctionType(
13074 Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_X86StdCall));
13075 FD->setType(QualType(FT, 0));
13076 }
13077 } else if (FT->getCallConv() != CC_C) {
13078 FT = Context.adjustFunctionType(Fn: FT,
13079 EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
13080 FD->setType(QualType(FT, 0));
13081 }
13082 }
13083
13084 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
13085 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
13086 FD->setInvalidDecl();
13087 }
13088}
13089
13090bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {
13091 // FIXME: Need strict checking. In C89, we need to check for
13092 // any assignment, increment, decrement, function-calls, or
13093 // commas outside of a sizeof. In C99, it's the same list,
13094 // except that the aforementioned are allowed in unevaluated
13095 // expressions. Everything else falls under the
13096 // "may accept other forms of constant expressions" exception.
13097 //
13098 // Regular C++ code will not end up here (exceptions: language extensions,
13099 // OpenCL C++ etc), so the constant expression rules there don't matter.
13100 if (Init->isValueDependent()) {
13101 assert(Init->containsErrors() &&
13102 "Dependent code should only occur in error-recovery path.");
13103 return true;
13104 }
13105 const Expr *Culprit;
13106 if (Init->isConstantInitializer(Ctx&: Context, /*ForRef=*/false, Culprit: &Culprit))
13107 return false;
13108
13109 // The culprit reported by isConstantInitializer() may be wrapped in implicit
13110 // casts and parentheses that it does not look through: under ARC an
13111 // object-pointer initializer is an `ImplicitCastExpr
13112 // <ARCReclaimReturnedObject>`, an `id`-typed (or otherwise differently-typed)
13113 // variable adds an `ImplicitCastExpr <BitCast>` on top, and a parenthesized
13114 // initializer such as `(@{...})` adds a `ParenExpr`. Strip all of these so
13115 // the ObjC-specific classification and per-element reporting below can see
13116 // the underlying literal regardless of how it is wrapped.
13117 const Expr *CulpritLiteral = Culprit->IgnoreParenImpCasts();
13118
13119 // Emit ObjC-specific diagnostics for non-constant literals at file scope.
13120 if (getLangOpts().ObjCConstantLiterals &&
13121 isa<ObjCObjectLiteral>(Val: CulpritLiteral)) {
13122
13123 // For collection literals, iterate the elements to point at the specific
13124 // offender. These per-element checks mirror the constant-initializer rules
13125 // applied when the literal was built (see SemaObjC::BuildObjCArrayLiteral
13126 // and SemaObjC::BuildObjCDictionaryLiteral): each element must itself be a
13127 // constant object literal, and dictionary keys must additionally be string
13128 // literals. Elements, keys and values are wrapped in an implicit BitCast to
13129 // `id`, so the isa<> classification is done on the unwrapped expression.
13130 if (const auto *ALE = dyn_cast<ObjCArrayLiteral>(Val: CulpritLiteral)) {
13131 for (const Expr *Elm : ALE->elements()) {
13132 if (!isa<ObjCObjectLiteral>(Val: Elm->IgnoreImpCasts()) ||
13133 !Elm->isConstantInitializer(Ctx&: Context)) {
13134 Diag(Loc: Elm->getExprLoc(),
13135 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13136 << ObjC().CheckLiteralKind(FromE: Init) << Elm->getSourceRange();
13137 return true;
13138 }
13139 }
13140 }
13141
13142 if (const auto *DLE = dyn_cast<ObjCDictionaryLiteral>(Val: CulpritLiteral)) {
13143 for (size_t I = 0, N = DLE->getNumElements(); I != N; ++I) {
13144 const ObjCDictionaryElement Elm = DLE->getKeyValueElement(Index: I);
13145
13146 // Keys must be constant string literals.
13147 if (!isa<ObjCStringLiteral>(Val: Elm.Key->IgnoreImpCasts()) ||
13148 !Elm.Key->isConstantInitializer(Ctx&: Context)) {
13149 Diag(Loc: Elm.Key->getExprLoc(),
13150 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13151 << ObjC().CheckLiteralKind(FromE: Init) << Elm.Key->getSourceRange();
13152 return true;
13153 }
13154
13155 // Values must be constant object literals.
13156 if (!isa<ObjCObjectLiteral>(Val: Elm.Value->IgnoreImpCasts()) ||
13157 !Elm.Value->isConstantInitializer(Ctx&: Context)) {
13158 Diag(Loc: Elm.Value->getExprLoc(),
13159 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13160 << ObjC().CheckLiteralKind(FromE: Init) << Elm.Value->getSourceRange();
13161 return true;
13162 }
13163 }
13164 }
13165
13166 Diag(Loc: CulpritLiteral->getExprLoc(),
13167 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13168 << ObjC().CheckLiteralKind(FromE: Init) << CulpritLiteral->getSourceRange();
13169 return true;
13170 }
13171
13172 Diag(Loc: Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
13173 return true;
13174}
13175
13176namespace {
13177 // Visits an initialization expression to see if OrigDecl is evaluated in
13178 // its own initialization and throws a warning if it does.
13179 class SelfReferenceChecker
13180 : public EvaluatedExprVisitor<SelfReferenceChecker> {
13181 Sema &S;
13182 Decl *OrigDecl;
13183 bool isRecordType;
13184 bool isPODType;
13185 bool isReferenceType;
13186 bool isInCXXOperatorCall;
13187
13188 bool isInitList;
13189 llvm::SmallVector<unsigned, 4> InitFieldIndex;
13190
13191 public:
13192 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
13193
13194 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
13195 S(S), OrigDecl(OrigDecl) {
13196 isPODType = false;
13197 isRecordType = false;
13198 isReferenceType = false;
13199 isInCXXOperatorCall = false;
13200 isInitList = false;
13201 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: OrigDecl)) {
13202 isPODType = VD->getType().isPODType(Context: S.Context);
13203 isRecordType = VD->getType()->isRecordType();
13204 isReferenceType = VD->getType()->isReferenceType();
13205 }
13206 }
13207
13208 // For most expressions, just call the visitor. For initializer lists,
13209 // track the index of the field being initialized since fields are
13210 // initialized in order allowing use of previously initialized fields.
13211 void CheckExpr(Expr *E) {
13212 InitListExpr *InitList = dyn_cast<InitListExpr>(Val: E);
13213 if (!InitList) {
13214 Visit(S: E);
13215 return;
13216 }
13217
13218 // Track and increment the index here.
13219 isInitList = true;
13220 InitFieldIndex.push_back(Elt: 0);
13221 for (auto *Child : InitList->children()) {
13222 CheckExpr(E: cast<Expr>(Val: Child));
13223 ++InitFieldIndex.back();
13224 }
13225 InitFieldIndex.pop_back();
13226 }
13227
13228 // Returns true if MemberExpr is checked and no further checking is needed.
13229 // Returns false if additional checking is required.
13230 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
13231 llvm::SmallVector<FieldDecl*, 4> Fields;
13232 Expr *Base = E;
13233 bool ReferenceField = false;
13234
13235 // Get the field members used.
13236 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13237 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
13238 if (!FD)
13239 return false;
13240 Fields.push_back(Elt: FD);
13241 if (FD->getType()->isReferenceType())
13242 ReferenceField = true;
13243 Base = ME->getBase()->IgnoreParenImpCasts();
13244 }
13245
13246 // Keep checking only if the base Decl is the same.
13247 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base);
13248 if (!DRE || DRE->getDecl() != OrigDecl)
13249 return false;
13250
13251 // A reference field can be bound to an unininitialized field.
13252 if (CheckReference && !ReferenceField)
13253 return true;
13254
13255 // Convert FieldDecls to their index number.
13256 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
13257 for (const FieldDecl *I : llvm::reverse(C&: Fields))
13258 UsedFieldIndex.push_back(Elt: I->getFieldIndex());
13259
13260 // See if a warning is needed by checking the first difference in index
13261 // numbers. If field being used has index less than the field being
13262 // initialized, then the use is safe.
13263 for (auto UsedIter = UsedFieldIndex.begin(),
13264 UsedEnd = UsedFieldIndex.end(),
13265 OrigIter = InitFieldIndex.begin(),
13266 OrigEnd = InitFieldIndex.end();
13267 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
13268 if (*UsedIter < *OrigIter)
13269 return true;
13270 if (*UsedIter > *OrigIter)
13271 break;
13272 }
13273
13274 // TODO: Add a different warning which will print the field names.
13275 HandleDeclRefExpr(DRE);
13276 return true;
13277 }
13278
13279 // For most expressions, the cast is directly above the DeclRefExpr.
13280 // For conditional operators, the cast can be outside the conditional
13281 // operator if both expressions are DeclRefExpr's.
13282 void HandleValue(Expr *E) {
13283 E = E->IgnoreParens();
13284 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Val: E)) {
13285 HandleDeclRefExpr(DRE);
13286 return;
13287 }
13288
13289 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
13290 Visit(S: CO->getCond());
13291 HandleValue(E: CO->getTrueExpr());
13292 HandleValue(E: CO->getFalseExpr());
13293 return;
13294 }
13295
13296 if (BinaryConditionalOperator *BCO =
13297 dyn_cast<BinaryConditionalOperator>(Val: E)) {
13298 Visit(S: BCO->getCond());
13299 HandleValue(E: BCO->getFalseExpr());
13300 return;
13301 }
13302
13303 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
13304 if (Expr *SE = OVE->getSourceExpr())
13305 HandleValue(E: SE);
13306 return;
13307 }
13308
13309 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
13310 if (BO->getOpcode() == BO_Comma) {
13311 Visit(S: BO->getLHS());
13312 HandleValue(E: BO->getRHS());
13313 return;
13314 }
13315 }
13316
13317 if (isa<MemberExpr>(Val: E)) {
13318 if (isInitList) {
13319 if (CheckInitListMemberExpr(E: cast<MemberExpr>(Val: E),
13320 CheckReference: false /*CheckReference*/))
13321 return;
13322 }
13323
13324 Expr *Base = E->IgnoreParenImpCasts();
13325 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13326 // Check for static member variables and don't warn on them.
13327 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13328 return;
13329 Base = ME->getBase()->IgnoreParenImpCasts();
13330 }
13331 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base))
13332 HandleDeclRefExpr(DRE);
13333 return;
13334 }
13335
13336 Visit(S: E);
13337 }
13338
13339 // Reference types not handled in HandleValue are handled here since all
13340 // uses of references are bad, not just r-value uses.
13341 void VisitDeclRefExpr(DeclRefExpr *E) {
13342 if (isReferenceType)
13343 HandleDeclRefExpr(DRE: E);
13344 }
13345
13346 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13347 if (E->getCastKind() == CK_LValueToRValue) {
13348 HandleValue(E: E->getSubExpr());
13349 return;
13350 }
13351
13352 Inherited::VisitImplicitCastExpr(S: E);
13353 }
13354
13355 void VisitMemberExpr(MemberExpr *E) {
13356 if (isInitList) {
13357 if (CheckInitListMemberExpr(E, CheckReference: true /*CheckReference*/))
13358 return;
13359 }
13360
13361 // Don't warn on arrays since they can be treated as pointers.
13362 if (E->getType()->canDecayToPointerType()) return;
13363
13364 // Warn when a non-static method call is followed by non-static member
13365 // field accesses, which is followed by a DeclRefExpr.
13366 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl());
13367 bool Warn = (MD && !MD->isStatic());
13368 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13369 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13370 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13371 Warn = false;
13372 Base = ME->getBase()->IgnoreParenImpCasts();
13373 }
13374
13375 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base)) {
13376 if (Warn)
13377 HandleDeclRefExpr(DRE);
13378 return;
13379 }
13380
13381 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13382 // Visit that expression.
13383 Visit(S: Base);
13384 }
13385
13386 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13387 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13388 Expr *Callee = E->getCallee();
13389
13390 if (isa<UnresolvedLookupExpr>(Val: Callee))
13391 return Inherited::VisitCXXOperatorCallExpr(S: E);
13392
13393 Visit(S: Callee);
13394 for (auto Arg: E->arguments())
13395 HandleValue(E: Arg->IgnoreParenImpCasts());
13396 }
13397
13398 void VisitLambdaExpr(LambdaExpr *E) {
13399 if (!isInCXXOperatorCall) {
13400 Inherited::VisitLambdaExpr(LE: E);
13401 return;
13402 }
13403
13404 for (Expr *Init : E->capture_inits())
13405 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: Init))
13406 HandleDeclRefExpr(DRE);
13407 else if (Init)
13408 Visit(S: Init);
13409 }
13410
13411 void VisitUnaryOperator(UnaryOperator *E) {
13412 // For POD record types, addresses of its own members are well-defined.
13413 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13414 isa<MemberExpr>(Val: E->getSubExpr()->IgnoreParens())) {
13415 if (!isPODType)
13416 HandleValue(E: E->getSubExpr());
13417 return;
13418 }
13419
13420 if (E->isIncrementDecrementOp()) {
13421 HandleValue(E: E->getSubExpr());
13422 return;
13423 }
13424
13425 Inherited::VisitUnaryOperator(S: E);
13426 }
13427
13428 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13429
13430 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13431 if (E->getConstructor()->isCopyConstructor()) {
13432 Expr *ArgExpr = E->getArg(Arg: 0);
13433 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
13434 if (ILE->getNumInits() == 1)
13435 ArgExpr = ILE->getInit(Init: 0);
13436 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
13437 if (ICE->getCastKind() == CK_NoOp)
13438 ArgExpr = ICE->getSubExpr();
13439 HandleValue(E: ArgExpr);
13440 return;
13441 }
13442 Inherited::VisitCXXConstructExpr(S: E);
13443 }
13444
13445 void VisitCallExpr(CallExpr *E) {
13446 // Treat std::move as a use.
13447 if (E->isCallToStdMove()) {
13448 HandleValue(E: E->getArg(Arg: 0));
13449 return;
13450 }
13451
13452 Inherited::VisitCallExpr(CE: E);
13453 }
13454
13455 void VisitBinaryOperator(BinaryOperator *E) {
13456 if (E->isCompoundAssignmentOp()) {
13457 HandleValue(E: E->getLHS());
13458 Visit(S: E->getRHS());
13459 return;
13460 }
13461
13462 Inherited::VisitBinaryOperator(S: E);
13463 }
13464
13465 // A custom visitor for BinaryConditionalOperator is needed because the
13466 // regular visitor would check the condition and true expression separately
13467 // but both point to the same place giving duplicate diagnostics.
13468 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13469 Visit(S: E->getCond());
13470 Visit(S: E->getFalseExpr());
13471 }
13472
13473 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13474 Decl* ReferenceDecl = DRE->getDecl();
13475 if (OrigDecl != ReferenceDecl) return;
13476 unsigned diag;
13477 if (isReferenceType) {
13478 diag = diag::warn_uninit_self_reference_in_reference_init;
13479 } else if (cast<VarDecl>(Val: OrigDecl)->isStaticLocal()) {
13480 diag = diag::warn_static_self_reference_in_init;
13481 } else if (isa<TranslationUnitDecl>(Val: OrigDecl->getDeclContext()) ||
13482 isa<NamespaceDecl>(Val: OrigDecl->getDeclContext()) ||
13483 DRE->getDecl()->getType()->isRecordType()) {
13484 diag = diag::warn_uninit_self_reference_in_init;
13485 } else {
13486 // Local variables will be handled by the CFG analysis.
13487 return;
13488 }
13489
13490 S.DiagRuntimeBehavior(Loc: DRE->getBeginLoc(), Statement: DRE,
13491 PD: S.PDiag(DiagID: diag)
13492 << DRE->getDecl() << OrigDecl->getLocation()
13493 << DRE->getSourceRange());
13494 }
13495 };
13496
13497 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13498 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13499 bool DirectInit) {
13500 // Parameters arguments are occassionially constructed with itself,
13501 // for instance, in recursive functions. Skip them.
13502 if (isa<ParmVarDecl>(Val: OrigDecl))
13503 return;
13504
13505 // Skip checking for file-scope constexpr variables - constant evaluation
13506 // will produce appropriate errors without needing runtime diagnostics.
13507 // Local constexpr should still emit runtime warnings.
13508 if (auto *VD = dyn_cast<VarDecl>(Val: OrigDecl);
13509 VD && VD->isConstexpr() && VD->isFileVarDecl())
13510 return;
13511
13512 E = E->IgnoreParens();
13513
13514 // Skip checking T a = a where T is not a record or reference type.
13515 // Doing so is a way to silence uninitialized warnings.
13516 if (!DirectInit && !cast<VarDecl>(Val: OrigDecl)->getType()->isRecordType())
13517 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
13518 if (ICE->getCastKind() == CK_LValueToRValue)
13519 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ICE->getSubExpr()))
13520 if (DRE->getDecl() == OrigDecl)
13521 return;
13522
13523 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13524 }
13525} // end anonymous namespace
13526
13527namespace {
13528 // Simple wrapper to add the name of a variable or (if no variable is
13529 // available) a DeclarationName into a diagnostic.
13530 struct VarDeclOrName {
13531 VarDecl *VDecl;
13532 DeclarationName Name;
13533
13534 friend const Sema::SemaDiagnosticBuilder &
13535 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13536 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13537 }
13538 };
13539} // end anonymous namespace
13540
13541QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
13542 DeclarationName Name, QualType Type,
13543 TypeSourceInfo *TSI,
13544 SourceRange Range, bool DirectInit,
13545 Expr *Init) {
13546 bool IsInitCapture = !VDecl;
13547 assert((!VDecl || !VDecl->isInitCapture()) &&
13548 "init captures are expected to be deduced prior to initialization");
13549
13550 VarDeclOrName VN{.VDecl: VDecl, .Name: Name};
13551
13552 DeducedType *Deduced = Type->getContainedDeducedType();
13553 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13554
13555 // Diagnose auto array declarations in C23, unless it's a supported extension.
13556 if (getLangOpts().C23 && Type->isArrayType() &&
13557 !isa_and_present<StringLiteral, InitListExpr>(Val: Init)) {
13558 Diag(Loc: Range.getBegin(), DiagID: diag::err_auto_not_allowed)
13559 << (int)Deduced->getContainedAutoType()->getKeyword()
13560 << /*in array decl*/ 23 << Range;
13561 return QualType();
13562 }
13563
13564 // C++11 [dcl.spec.auto]p3
13565 if (!Init) {
13566 assert(VDecl && "no init for init capture deduction?");
13567
13568 // Except for class argument deduction, and then for an initializing
13569 // declaration only, i.e. no static at class scope or extern.
13570 if (!isa<DeducedTemplateSpecializationType>(Val: Deduced) ||
13571 VDecl->hasExternalStorage() ||
13572 VDecl->isStaticDataMember()) {
13573 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_auto_var_requires_init)
13574 << VDecl->getDeclName() << Type;
13575 return QualType();
13576 }
13577 }
13578
13579 ArrayRef<Expr*> DeduceInits;
13580 if (Init)
13581 DeduceInits = Init;
13582
13583 auto *PL = dyn_cast_if_present<ParenListExpr>(Val: Init);
13584 if (DirectInit && PL)
13585 DeduceInits = PL->exprs();
13586
13587 if (isa<DeducedTemplateSpecializationType>(Val: Deduced)) {
13588 assert(VDecl && "non-auto type for init capture deduction?");
13589 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13590 InitializationKind Kind = InitializationKind::CreateForInit(
13591 Loc: VDecl->getLocation(), DirectInit, Init);
13592 // FIXME: Initialization should not be taking a mutable list of inits.
13593 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13594 return DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind,
13595 Init: InitsCopy);
13596 }
13597
13598 if (DirectInit) {
13599 if (auto *IL = dyn_cast<InitListExpr>(Val: Init))
13600 DeduceInits = IL->inits();
13601 }
13602
13603 // Deduction only works if we have exactly one source expression.
13604 if (DeduceInits.empty()) {
13605 // It isn't possible to write this directly, but it is possible to
13606 // end up in this situation with "auto x(some_pack...);"
13607 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13608 ? diag::err_init_capture_no_expression
13609 : diag::err_auto_var_init_no_expression)
13610 << VN << Type << Range;
13611 return QualType();
13612 }
13613
13614 if (DeduceInits.size() > 1) {
13615 Diag(Loc: DeduceInits[1]->getBeginLoc(),
13616 DiagID: IsInitCapture ? diag::err_init_capture_multiple_expressions
13617 : diag::err_auto_var_init_multiple_expressions)
13618 << VN << Type << Range;
13619 return QualType();
13620 }
13621
13622 Expr *DeduceInit = DeduceInits[0];
13623 if (DirectInit && isa<InitListExpr>(Val: DeduceInit)) {
13624 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13625 ? diag::err_init_capture_paren_braces
13626 : diag::err_auto_var_init_paren_braces)
13627 << isa<InitListExpr>(Val: Init) << VN << Type << Range;
13628 return QualType();
13629 }
13630
13631 // Expressions default to 'id' when we're in a debugger.
13632 bool DefaultedAnyToId = false;
13633 if (getLangOpts().DebuggerCastResultToId &&
13634 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13635 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13636 if (Result.isInvalid()) {
13637 return QualType();
13638 }
13639 Init = Result.get();
13640 DefaultedAnyToId = true;
13641 }
13642
13643 // C++ [dcl.decomp]p1:
13644 // If the assignment-expression [...] has array type A and no ref-qualifier
13645 // is present, e has type cv A
13646 if (VDecl && isa<DecompositionDecl>(Val: VDecl) &&
13647 Context.hasSameUnqualifiedType(T1: Type, T2: Context.getAutoDeductType()) &&
13648 DeduceInit->getType()->isConstantArrayType())
13649 return Context.getQualifiedType(T: DeduceInit->getType(),
13650 Qs: Type.getQualifiers());
13651
13652 QualType DeducedType;
13653 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13654 TemplateDeductionResult Result =
13655 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeduceInit, Result&: DeducedType, Info);
13656 if (Result != TemplateDeductionResult::Success &&
13657 Result != TemplateDeductionResult::AlreadyDiagnosed) {
13658 if (!IsInitCapture)
13659 DiagnoseAutoDeductionFailure(VDecl, Init: DeduceInit);
13660 else if (isa<InitListExpr>(Val: Init))
13661 Diag(Loc: Range.getBegin(),
13662 DiagID: diag::err_init_capture_deduction_failure_from_init_list)
13663 << VN
13664 << (DeduceInit->getType().isNull() ? TSI->getType()
13665 : DeduceInit->getType())
13666 << DeduceInit->getSourceRange();
13667 else
13668 Diag(Loc: Range.getBegin(), DiagID: diag::err_init_capture_deduction_failure)
13669 << VN << TSI->getType()
13670 << (DeduceInit->getType().isNull() ? TSI->getType()
13671 : DeduceInit->getType())
13672 << DeduceInit->getSourceRange();
13673 }
13674
13675 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13676 // 'id' instead of a specific object type prevents most of our usual
13677 // checks.
13678 // We only want to warn outside of template instantiations, though:
13679 // inside a template, the 'id' could have come from a parameter.
13680 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13681 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13682 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13683 Diag(Loc, DiagID: diag::warn_auto_var_is_id) << VN << Range;
13684 }
13685
13686 return DeducedType;
13687}
13688
13689bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13690 Expr *Init) {
13691 assert(!Init || !Init->containsErrors());
13692 QualType DeducedType = deduceVarTypeFromInitializer(
13693 VDecl, Name: VDecl->getDeclName(), Type: VDecl->getType(), TSI: VDecl->getTypeSourceInfo(),
13694 Range: VDecl->getSourceRange(), DirectInit, Init);
13695 if (DeducedType.isNull()) {
13696 VDecl->setInvalidDecl();
13697 return true;
13698 }
13699
13700 VDecl->setType(DeducedType);
13701 assert(VDecl->isLinkageValid());
13702
13703 // In ARC, infer lifetime.
13704 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: VDecl))
13705 VDecl->setInvalidDecl();
13706
13707 if (getLangOpts().OpenCL)
13708 deduceOpenCLAddressSpace(Var: VDecl);
13709
13710 if (getLangOpts().HLSL)
13711 HLSL().deduceAddressSpace(Decl: VDecl);
13712
13713 // If this is a redeclaration, check that the type we just deduced matches
13714 // the previously declared type.
13715 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13716 // We never need to merge the type, because we cannot form an incomplete
13717 // array of auto, nor deduce such a type.
13718 MergeVarDeclTypes(New: VDecl, Old, /*MergeTypeWithPrevious*/ MergeTypeWithOld: false);
13719 }
13720
13721 // Check the deduced type is valid for a variable declaration.
13722 CheckVariableDeclarationType(NewVD: VDecl);
13723 return VDecl->isInvalidDecl();
13724}
13725
13726void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13727 SourceLocation Loc) {
13728 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Init))
13729 Init = EWC->getSubExpr();
13730
13731 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init))
13732 Init = CE->getSubExpr();
13733
13734 QualType InitType = Init->getType();
13735 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13736 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13737 "shouldn't be called if type doesn't have a non-trivial C struct");
13738 if (auto *ILE = dyn_cast<InitListExpr>(Val: Init)) {
13739 for (auto *I : ILE->inits()) {
13740 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13741 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13742 continue;
13743 SourceLocation SL = I->getExprLoc();
13744 checkNonTrivialCUnionInInitializer(Init: I, Loc: SL.isValid() ? SL : Loc);
13745 }
13746 return;
13747 }
13748
13749 if (isa<ImplicitValueInitExpr>(Val: Init)) {
13750 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13751 checkNonTrivialCUnion(QT: InitType, Loc,
13752 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
13753 NonTrivialKind: NTCUK_Init);
13754 } else {
13755 // Assume all other explicit initializers involving copying some existing
13756 // object.
13757 // TODO: ignore any explicit initializers where we can guarantee
13758 // copy-elision.
13759 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13760 checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NonTrivialCUnionContext::CopyInit,
13761 NonTrivialKind: NTCUK_Copy);
13762 }
13763}
13764
13765namespace {
13766
13767bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13768 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13769 // in the source code or implicitly by the compiler if it is in a union
13770 // defined in a system header and has non-trivial ObjC ownership
13771 // qualifications. We don't want those fields to participate in determining
13772 // whether the containing union is non-trivial.
13773 return FD->hasAttr<UnavailableAttr>();
13774}
13775
13776struct DiagNonTrivalCUnionDefaultInitializeVisitor
13777 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13778 void> {
13779 using Super =
13780 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13781 void>;
13782
13783 DiagNonTrivalCUnionDefaultInitializeVisitor(
13784 QualType OrigTy, SourceLocation OrigLoc,
13785 NonTrivialCUnionContext UseContext, Sema &S)
13786 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13787
13788 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13789 const FieldDecl *FD, bool InNonTrivialUnion) {
13790 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13791 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13792 Args&: InNonTrivialUnion);
13793 return Super::visitWithKind(PDIK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13794 }
13795
13796 void visitARCStrong(QualType QT, const FieldDecl *FD,
13797 bool InNonTrivialUnion) {
13798 if (InNonTrivialUnion)
13799 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13800 << 1 << 0 << QT << FD->getName();
13801 }
13802
13803 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13804 if (InNonTrivialUnion)
13805 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13806 << 1 << 0 << QT << FD->getName();
13807 }
13808
13809 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13810 const auto *RD = QT->castAsRecordDecl();
13811 if (RD->isUnion()) {
13812 if (OrigLoc.isValid()) {
13813 bool IsUnion = false;
13814 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13815 IsUnion = OrigRD->isUnion();
13816 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13817 << 0 << OrigTy << IsUnion << UseContext;
13818 // Reset OrigLoc so that this diagnostic is emitted only once.
13819 OrigLoc = SourceLocation();
13820 }
13821 InNonTrivialUnion = true;
13822 }
13823
13824 if (InNonTrivialUnion)
13825 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13826 << 0 << 0 << QT.getUnqualifiedType() << "";
13827
13828 for (const FieldDecl *FD : RD->fields())
13829 if (!shouldIgnoreForRecordTriviality(FD))
13830 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13831 }
13832
13833 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13834
13835 // The non-trivial C union type or the struct/union type that contains a
13836 // non-trivial C union.
13837 QualType OrigTy;
13838 SourceLocation OrigLoc;
13839 NonTrivialCUnionContext UseContext;
13840 Sema &S;
13841};
13842
13843struct DiagNonTrivalCUnionDestructedTypeVisitor
13844 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13845 using Super =
13846 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13847
13848 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13849 SourceLocation OrigLoc,
13850 NonTrivialCUnionContext UseContext,
13851 Sema &S)
13852 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13853
13854 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13855 const FieldDecl *FD, bool InNonTrivialUnion) {
13856 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13857 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13858 Args&: InNonTrivialUnion);
13859 return Super::visitWithKind(DK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13860 }
13861
13862 void visitARCStrong(QualType QT, const FieldDecl *FD,
13863 bool InNonTrivialUnion) {
13864 if (InNonTrivialUnion)
13865 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13866 << 1 << 1 << QT << FD->getName();
13867 }
13868
13869 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13870 if (InNonTrivialUnion)
13871 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13872 << 1 << 1 << QT << FD->getName();
13873 }
13874
13875 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13876 const auto *RD = QT->castAsRecordDecl();
13877 if (RD->isUnion()) {
13878 if (OrigLoc.isValid()) {
13879 bool IsUnion = false;
13880 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13881 IsUnion = OrigRD->isUnion();
13882 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13883 << 1 << OrigTy << IsUnion << UseContext;
13884 // Reset OrigLoc so that this diagnostic is emitted only once.
13885 OrigLoc = SourceLocation();
13886 }
13887 InNonTrivialUnion = true;
13888 }
13889
13890 if (InNonTrivialUnion)
13891 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13892 << 0 << 1 << QT.getUnqualifiedType() << "";
13893
13894 for (const FieldDecl *FD : RD->fields())
13895 if (!shouldIgnoreForRecordTriviality(FD))
13896 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13897 }
13898
13899 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13900 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13901 bool InNonTrivialUnion) {}
13902
13903 // The non-trivial C union type or the struct/union type that contains a
13904 // non-trivial C union.
13905 QualType OrigTy;
13906 SourceLocation OrigLoc;
13907 NonTrivialCUnionContext UseContext;
13908 Sema &S;
13909};
13910
13911struct DiagNonTrivalCUnionCopyVisitor
13912 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13913 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13914
13915 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13916 NonTrivialCUnionContext UseContext, Sema &S)
13917 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13918
13919 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13920 const FieldDecl *FD, bool InNonTrivialUnion) {
13921 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13922 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13923 Args&: InNonTrivialUnion);
13924 return Super::visitWithKind(PCK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13925 }
13926
13927 void visitARCStrong(QualType QT, const FieldDecl *FD,
13928 bool InNonTrivialUnion) {
13929 if (InNonTrivialUnion)
13930 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13931 << 1 << 2 << QT << FD->getName();
13932 }
13933
13934 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13935 if (InNonTrivialUnion)
13936 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13937 << 1 << 2 << QT << FD->getName();
13938 }
13939
13940 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13941 const auto *RD = QT->castAsRecordDecl();
13942 if (RD->isUnion()) {
13943 if (OrigLoc.isValid()) {
13944 bool IsUnion = false;
13945 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13946 IsUnion = OrigRD->isUnion();
13947 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13948 << 2 << OrigTy << IsUnion << UseContext;
13949 // Reset OrigLoc so that this diagnostic is emitted only once.
13950 OrigLoc = SourceLocation();
13951 }
13952 InNonTrivialUnion = true;
13953 }
13954
13955 if (InNonTrivialUnion)
13956 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13957 << 0 << 2 << QT.getUnqualifiedType() << "";
13958
13959 for (const FieldDecl *FD : RD->fields())
13960 if (!shouldIgnoreForRecordTriviality(FD))
13961 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13962 }
13963
13964 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13965 if (InNonTrivialUnion)
13966 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13967 << 1 << 2 << QT << FD->getName();
13968 }
13969
13970 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13971 const FieldDecl *FD, bool InNonTrivialUnion) {}
13972 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13973 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13974 bool InNonTrivialUnion) {}
13975
13976 // The non-trivial C union type or the struct/union type that contains a
13977 // non-trivial C union.
13978 QualType OrigTy;
13979 SourceLocation OrigLoc;
13980 NonTrivialCUnionContext UseContext;
13981 Sema &S;
13982};
13983
13984} // namespace
13985
13986void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13987 NonTrivialCUnionContext UseContext,
13988 unsigned NonTrivialKind) {
13989 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13990 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13991 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13992 "shouldn't be called if type doesn't have a non-trivial C union");
13993
13994 if ((NonTrivialKind & NTCUK_Init) &&
13995 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13996 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13997 .visit(FT: QT, Args: nullptr, Args: false);
13998 if ((NonTrivialKind & NTCUK_Destruct) &&
13999 QT.hasNonTrivialToPrimitiveDestructCUnion())
14000 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
14001 .visit(FT: QT, Args: nullptr, Args: false);
14002 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
14003 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
14004 .visit(FT: QT, Args: nullptr, Args: false);
14005}
14006
14007bool Sema::GloballyUniqueObjectMightBeAccidentallyDuplicated(
14008 const VarDecl *Dcl) {
14009 if (!getLangOpts().CPlusPlus)
14010 return false;
14011
14012 // We only need to warn if the definition is in a header file, so wait to
14013 // diagnose until we've seen the definition.
14014 if (!Dcl->isThisDeclarationADefinition())
14015 return false;
14016
14017 // If an object is defined in a source file, its definition can't get
14018 // duplicated since it will never appear in more than one TU.
14019 if (Dcl->getASTContext().getSourceManager().isInMainFile(Loc: Dcl->getLocation()))
14020 return false;
14021
14022 // If the variable we're looking at is a static local, then we actually care
14023 // about the properties of the function containing it.
14024 const ValueDecl *Target = Dcl;
14025 // VarDecls and FunctionDecls have different functions for checking
14026 // inline-ness, and whether they were originally templated, so we have to
14027 // call the appropriate functions manually.
14028 bool TargetIsInline = Dcl->isInline();
14029 bool TargetWasTemplated =
14030 Dcl->getTemplateSpecializationKind() != TSK_Undeclared;
14031
14032 // Update the Target and TargetIsInline property if necessary
14033 if (Dcl->isStaticLocal()) {
14034 const DeclContext *Ctx = Dcl->getDeclContext();
14035 if (!Ctx)
14036 return false;
14037
14038 const FunctionDecl *FunDcl =
14039 dyn_cast_if_present<FunctionDecl>(Val: Ctx->getNonClosureAncestor());
14040 if (!FunDcl)
14041 return false;
14042
14043 Target = FunDcl;
14044 // IsInlined() checks for the C++ inline property
14045 TargetIsInline = FunDcl->isInlined();
14046 TargetWasTemplated =
14047 FunDcl->getTemplateSpecializationKind() != TSK_Undeclared;
14048 }
14049
14050 // Non-inline functions/variables can only legally appear in one TU
14051 // unless they were part of a template. Unfortunately, making complex
14052 // template instantiations visible is infeasible in practice, since
14053 // everything the template depends on also has to be visible. To avoid
14054 // giving impractical-to-fix warnings, don't warn if we're inside
14055 // something that was templated, even on inline stuff.
14056 if (!TargetIsInline || TargetWasTemplated)
14057 return false;
14058
14059 // If the object isn't hidden, the dynamic linker will prevent duplication.
14060 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
14061
14062 // The target is "hidden" (from the dynamic linker) if:
14063 // 1. On posix, it has hidden visibility, or
14064 // 2. On windows, it has no import/export annotation, and neither does the
14065 // class which directly contains it.
14066 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
14067 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
14068 return false;
14069
14070 // If the variable isn't directly annotated, check to see if it's a member
14071 // of an annotated class.
14072 const CXXRecordDecl *Ctx =
14073 dyn_cast<CXXRecordDecl>(Val: Target->getDeclContext());
14074 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
14075 return false;
14076
14077 } else if (Lnk.getVisibility() != HiddenVisibility) {
14078 // Posix case
14079 return false;
14080 }
14081
14082 // If the obj doesn't have external linkage, it's supposed to be duplicated.
14083 if (!isExternalFormalLinkage(L: Lnk.getLinkage()))
14084 return false;
14085
14086 return true;
14087}
14088
14089// Determine whether the object seems mutable for the purpose of diagnosing
14090// possible unique object duplication, i.e. non-const-qualified, and
14091// not an always-constant type like a function.
14092// Not perfect: doesn't account for mutable members, for example, or
14093// elements of container types.
14094// For nested pointers, any individual level being non-const is sufficient.
14095static bool looksMutable(QualType T, const ASTContext &Ctx) {
14096 T = T.getNonReferenceType();
14097 if (T->isFunctionType())
14098 return false;
14099 if (!T.isConstant(Ctx))
14100 return true;
14101 if (T->isPointerType())
14102 return looksMutable(T: T->getPointeeType(), Ctx);
14103 return false;
14104}
14105
14106void Sema::DiagnoseUniqueObjectDuplication(const VarDecl *VD) {
14107 // If this object has external linkage and hidden visibility, it might be
14108 // duplicated when built into a shared library, which causes problems if it's
14109 // mutable (since the copies won't be in sync) or its initialization has side
14110 // effects (since it will run once per copy instead of once globally).
14111
14112 // Don't diagnose if we're inside a template, because it's not practical to
14113 // fix the warning in most cases.
14114 if (!VD->isTemplated() &&
14115 GloballyUniqueObjectMightBeAccidentallyDuplicated(Dcl: VD)) {
14116
14117 QualType Type = VD->getType();
14118 if (looksMutable(T: Type, Ctx: VD->getASTContext())) {
14119 Diag(Loc: VD->getLocation(), DiagID: diag::warn_possible_object_duplication_mutable)
14120 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
14121 }
14122
14123 // To keep false positives low, only warn if we're certain that the
14124 // initializer has side effects. Don't warn on operator new, since a mutable
14125 // pointer will trigger the previous warning, and an immutable pointer
14126 // getting duplicated just results in a little extra memory usage.
14127 const Expr *Init = VD->getAnyInitializer();
14128 if (Init &&
14129 Init->HasSideEffects(Ctx: VD->getASTContext(),
14130 /*IncludePossibleEffects=*/false) &&
14131 !isa<CXXNewExpr>(Val: Init->IgnoreParenImpCasts())) {
14132 Diag(Loc: Init->getExprLoc(), DiagID: diag::warn_possible_object_duplication_init)
14133 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
14134 }
14135 }
14136}
14137
14138void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
14139 llvm::scope_exit ResetDeclForInitializer([this]() {
14140 if (!this->ExprEvalContexts.empty())
14141 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
14142 });
14143
14144 // If there is no declaration, there was an error parsing it. Just ignore
14145 // the initializer.
14146 if (!RealDecl) {
14147 return;
14148 }
14149
14150 if (auto *Method = dyn_cast<CXXMethodDecl>(Val: RealDecl)) {
14151 if (!Method->isInvalidDecl()) {
14152 // Pure-specifiers are handled in ActOnPureSpecifier.
14153 Diag(Loc: Method->getLocation(), DiagID: diag::err_member_function_initialization)
14154 << Method->getDeclName() << Init->getSourceRange();
14155 Method->setInvalidDecl();
14156 }
14157 return;
14158 }
14159
14160 VarDecl *VDecl = dyn_cast<VarDecl>(Val: RealDecl);
14161 if (!VDecl) {
14162 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
14163 Diag(Loc: RealDecl->getLocation(), DiagID: diag::err_illegal_initializer);
14164 RealDecl->setInvalidDecl();
14165 return;
14166 }
14167
14168 if (VDecl->isInvalidDecl()) {
14169 ExprResult Recovery =
14170 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init});
14171 if (Expr *E = Recovery.get())
14172 VDecl->setInit(E);
14173 return;
14174 }
14175
14176 // __amdgpu_feature_predicate_t cannot be initialised
14177 if (VDecl->getType().getDesugaredType(Context) ==
14178 Context.AMDGPUFeaturePredicateTy) {
14179 Diag(Loc: VDecl->getLocation(),
14180 DiagID: diag::err_amdgcn_predicate_type_is_not_constructible)
14181 << VDecl;
14182 VDecl->setInvalidDecl();
14183 return;
14184 }
14185
14186 // WebAssembly tables can't be used to initialise a variable.
14187 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
14188 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_wasm_table_art) << 0;
14189 VDecl->setInvalidDecl();
14190 return;
14191 }
14192
14193 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
14194 if (VDecl->getType()->isUndeducedType()) {
14195 if (Init->containsErrors()) {
14196 // Invalidate the decl as we don't know the type for recovery-expr yet.
14197 RealDecl->setInvalidDecl();
14198 VDecl->setInit(Init);
14199 return;
14200 }
14201
14202 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) {
14203 assert(VDecl->isInvalidDecl() &&
14204 "decl should be invalidated when deduce fails");
14205 if (auto *RecoveryExpr =
14206 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init})
14207 .get())
14208 VDecl->setInit(RecoveryExpr);
14209 return;
14210 }
14211 }
14212
14213 this->CheckAttributesOnDeducedType(D: RealDecl);
14214
14215 // we don't initialize groupshared variables so warn and return
14216 if (VDecl->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
14217 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_hlsl_groupshared_init);
14218 return;
14219 }
14220
14221 // dllimport cannot be used on variable definitions.
14222 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
14223 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_attribute_dllimport_data_definition);
14224 VDecl->setInvalidDecl();
14225 return;
14226 }
14227
14228 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
14229 // the identifier has external or internal linkage, the declaration shall
14230 // have no initializer for the identifier.
14231 // C++14 [dcl.init]p5 is the same restriction for C++.
14232 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
14233 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_block_extern_cant_init);
14234 VDecl->setInvalidDecl();
14235 return;
14236 }
14237
14238 if (!VDecl->getType()->isDependentType()) {
14239 // A definition must end up with a complete type, which means it must be
14240 // complete with the restriction that an array type might be completed by
14241 // the initializer; note that later code assumes this restriction.
14242 QualType BaseDeclType = VDecl->getType();
14243 if (const ArrayType *Array = Context.getAsIncompleteArrayType(T: BaseDeclType))
14244 BaseDeclType = Array->getElementType();
14245 if (RequireCompleteType(Loc: VDecl->getLocation(), T: BaseDeclType,
14246 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14247 RealDecl->setInvalidDecl();
14248 return;
14249 }
14250
14251 // The variable can not have an abstract class type.
14252 if (RequireNonAbstractType(Loc: VDecl->getLocation(), T: VDecl->getType(),
14253 DiagID: diag::err_abstract_type_in_decl,
14254 Args: AbstractVariableType))
14255 VDecl->setInvalidDecl();
14256 }
14257
14258 // C++ [module.import/6]
14259 // ...
14260 // A header unit shall not contain a definition of a non-inline function or
14261 // variable whose name has external linkage.
14262 //
14263 // We choose to allow weak & selectany definitions, as they are common in
14264 // headers, and have semantics similar to inline definitions which are allowed
14265 // in header units.
14266 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
14267 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
14268 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
14269 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(Val: VDecl) &&
14270 !VDecl->getInstantiatedFromStaticDataMember() &&
14271 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
14272 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
14273 VDecl->setInvalidDecl();
14274 }
14275
14276 // If adding the initializer will turn this declaration into a definition,
14277 // and we already have a definition for this variable, diagnose or otherwise
14278 // handle the situation.
14279 if (VarDecl *Def = VDecl->getDefinition())
14280 if (Def != VDecl &&
14281 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
14282 !VDecl->isThisDeclarationADemotedDefinition() &&
14283 checkVarDeclRedefinition(Old: Def, New: VDecl))
14284 return;
14285
14286 if (getLangOpts().CPlusPlus) {
14287 // C++ [class.static.data]p4
14288 // If a static data member is of const integral or const
14289 // enumeration type, its declaration in the class definition can
14290 // specify a constant-initializer which shall be an integral
14291 // constant expression (5.19). In that case, the member can appear
14292 // in integral constant expressions. The member shall still be
14293 // defined in a namespace scope if it is used in the program and the
14294 // namespace scope definition shall not contain an initializer.
14295 //
14296 // We already performed a redefinition check above, but for static
14297 // data members we also need to check whether there was an in-class
14298 // declaration with an initializer.
14299 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
14300 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_static_data_member_reinitialization)
14301 << VDecl->getDeclName();
14302 Diag(Loc: VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
14303 DiagID: diag::note_previous_initializer)
14304 << 0;
14305 return;
14306 }
14307
14308 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer)) {
14309 VDecl->setInvalidDecl();
14310 return;
14311 }
14312 }
14313
14314 // If the variable has an initializer and local storage, check whether
14315 // anything jumps over the initialization.
14316 if (VDecl->hasLocalStorage())
14317 setFunctionHasBranchProtectedScope();
14318
14319 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
14320 // a kernel function cannot be initialized."
14321 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
14322 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_local_cant_init);
14323 VDecl->setInvalidDecl();
14324 return;
14325 }
14326
14327 // The LoaderUninitialized attribute acts as a definition (of undef).
14328 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14329 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_loader_uninitialized_cant_init);
14330 VDecl->setInvalidDecl();
14331 return;
14332 }
14333
14334 if (getLangOpts().HLSL)
14335 if (!HLSL().handleInitialization(VDecl, Init))
14336 return;
14337
14338 // Get the decls type and save a reference for later, since
14339 // CheckInitializerTypes may change it.
14340 QualType DclT = VDecl->getType(), SavT = DclT;
14341
14342 // Expressions default to 'id' when we're in a debugger
14343 // and we are assigning it to a variable of Objective-C pointer type.
14344 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14345 Init->getType() == Context.UnknownAnyTy) {
14346 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
14347 if (!Result.isUsable()) {
14348 VDecl->setInvalidDecl();
14349 return;
14350 }
14351 Init = Result.get();
14352 }
14353
14354 // Perform the initialization.
14355 bool InitializedFromParenListExpr = false;
14356 bool IsParenListInit = false;
14357 if (!VDecl->isInvalidDecl()) {
14358 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
14359 InitializationKind Kind = InitializationKind::CreateForInit(
14360 Loc: VDecl->getLocation(), DirectInit, Init);
14361
14362 MultiExprArg Args = Init;
14363 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Val: Init)) {
14364 Args =
14365 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14366 InitializedFromParenListExpr = true;
14367 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Val: Init)) {
14368 Args = CXXDirectInit->getInitExprs();
14369 InitializedFromParenListExpr = true;
14370 }
14371
14372 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14373 /*TopLevelOfInitList=*/false,
14374 /*TreatUnavailableAsInvalid=*/false);
14375 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args, ResultType: &DclT);
14376 if (!Result.isUsable()) {
14377 // If the provided initializer fails to initialize the var decl,
14378 // we attach a recovery expr for better recovery.
14379 auto RecoveryExpr =
14380 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: Args);
14381 if (RecoveryExpr.get())
14382 VDecl->setInit(RecoveryExpr.get());
14383 // In general, for error recovery purposes, the initializer doesn't play
14384 // part in the valid bit of the declaration. There are a few exceptions:
14385 // 1) if the var decl has a deduced auto type, and the type cannot be
14386 // deduced by an invalid initializer;
14387 // 2) if the var decl is a decomposition decl with a non-deduced type,
14388 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14389 // Case 1) was already handled elsewhere.
14390 if (isa<DecompositionDecl>(Val: VDecl)) // Case 2)
14391 VDecl->setInvalidDecl();
14392 return;
14393 }
14394
14395 Init = Result.getAs<Expr>();
14396 IsParenListInit = !InitSeq.steps().empty() &&
14397 InitSeq.step_begin()->Kind ==
14398 InitializationSequence::SK_ParenthesizedListInit;
14399 QualType VDeclType = VDecl->getType();
14400 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14401 !VDeclType->isDependentType() &&
14402 Context.getAsIncompleteArrayType(T: VDeclType) &&
14403 Context.getAsIncompleteArrayType(T: Init->getType())) {
14404 // Bail out if it is not possible to deduce array size from the
14405 // initializer.
14406 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
14407 << VDeclType;
14408 VDecl->setInvalidDecl();
14409 return;
14410 }
14411 }
14412
14413 // Check for self-references within variable initializers.
14414 // Variables declared within a function/method body (except for references)
14415 // are handled by a dataflow analysis.
14416 // This is undefined behavior in C++, but valid in C.
14417 if (getLangOpts().CPlusPlus)
14418 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14419 VDecl->getType()->isReferenceType())
14420 CheckSelfReference(S&: *this, OrigDecl: RealDecl, E: Init, DirectInit);
14421
14422 // If the type changed, it means we had an incomplete type that was
14423 // completed by the initializer. For example:
14424 // int ary[] = { 1, 3, 5 };
14425 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14426 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14427 VDecl->setType(DclT);
14428
14429 if (!VDecl->isInvalidDecl()) {
14430 checkUnsafeAssigns(Loc: VDecl->getLocation(), LHS: VDecl->getType(), RHS: Init);
14431
14432 if (VDecl->hasAttr<BlocksAttr>())
14433 ObjC().checkRetainCycles(Var: VDecl, Init);
14434
14435 // It is safe to assign a weak reference into a strong variable.
14436 // Although this code can still have problems:
14437 // id x = self.weakProp;
14438 // id y = self.weakProp;
14439 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14440 // paths through the function. This should be revisited if
14441 // -Wrepeated-use-of-weak is made flow-sensitive.
14442 if (FunctionScopeInfo *FSI = getCurFunction())
14443 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14444 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
14445 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14446 Loc: Init->getBeginLoc()))
14447 FSI->markSafeWeakUse(E: Init);
14448 }
14449
14450 // The initialization is usually a full-expression.
14451 //
14452 // FIXME: If this is a braced initialization of an aggregate, it is not
14453 // an expression, and each individual field initializer is a separate
14454 // full-expression. For instance, in:
14455 //
14456 // struct Temp { ~Temp(); };
14457 // struct S { S(Temp); };
14458 // struct T { S a, b; } t = { Temp(), Temp() }
14459 //
14460 // we should destroy the first Temp before constructing the second.
14461
14462 // Set context flag for OverflowBehaviorType initialization analysis
14463 llvm::SaveAndRestore OBTAssignmentContext(InOverflowBehaviorAssignmentContext,
14464 true);
14465 ExprResult Result =
14466 ActOnFinishFullExpr(Expr: Init, CC: VDecl->getLocation(),
14467 /*DiscardedValue*/ false, IsConstexpr: VDecl->isConstexpr());
14468 if (!Result.isUsable()) {
14469 VDecl->setInvalidDecl();
14470 return;
14471 }
14472 Init = Result.get();
14473
14474 // Attach the initializer to the decl.
14475 VDecl->setInit(Init);
14476
14477 if (VDecl->isLocalVarDecl()) {
14478 // Don't check the initializer if the declaration is malformed.
14479 if (VDecl->isInvalidDecl()) {
14480 // do nothing
14481
14482 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14483 // This is true even in C++ for OpenCL.
14484 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14485 CheckForConstantInitializer(Init);
14486
14487 // Otherwise, C++ does not restrict the initializer.
14488 } else if (getLangOpts().CPlusPlus) {
14489 // do nothing
14490
14491 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14492 // static storage duration shall be constant expressions or string literals.
14493 } else if (VDecl->getStorageClass() == SC_Static) {
14494 // Avoid evaluating the initializer twice for constexpr variables. It will
14495 // be evaluated later.
14496 if (!VDecl->isConstexpr())
14497 CheckForConstantInitializer(Init);
14498
14499 // C89 is stricter than C99 for aggregate initializers.
14500 // C89 6.5.7p3: All the expressions [...] in an initializer list
14501 // for an object that has aggregate or union type shall be
14502 // constant expressions.
14503 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14504 isa<InitListExpr>(Val: Init)) {
14505 CheckForConstantInitializer(Init, DiagID: diag::ext_aggregate_init_not_constant);
14506 }
14507
14508 if (auto *E = dyn_cast<ExprWithCleanups>(Val: Init))
14509 if (auto *BE = dyn_cast<BlockExpr>(Val: E->getSubExpr()->IgnoreParens()))
14510 if (VDecl->hasLocalStorage())
14511 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14512 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14513 VDecl->getLexicalDeclContext()->isRecord()) {
14514 // This is an in-class initialization for a static data member, e.g.,
14515 //
14516 // struct S {
14517 // static const int value = 17;
14518 // };
14519
14520 // C++ [class.mem]p4:
14521 // A member-declarator can contain a constant-initializer only
14522 // if it declares a static member (9.4) of const integral or
14523 // const enumeration type, see 9.4.2.
14524 //
14525 // C++11 [class.static.data]p3:
14526 // If a non-volatile non-inline const static data member is of integral
14527 // or enumeration type, its declaration in the class definition can
14528 // specify a brace-or-equal-initializer in which every initializer-clause
14529 // that is an assignment-expression is a constant expression. A static
14530 // data member of literal type can be declared in the class definition
14531 // with the constexpr specifier; if so, its declaration shall specify a
14532 // brace-or-equal-initializer in which every initializer-clause that is
14533 // an assignment-expression is a constant expression.
14534
14535 // Do nothing on dependent types.
14536 if (DclT->isDependentType()) {
14537
14538 // Allow any 'static constexpr' members, whether or not they are of literal
14539 // type. We separately check that every constexpr variable is of literal
14540 // type.
14541 } else if (VDecl->isConstexpr()) {
14542
14543 // Require constness.
14544 } else if (!DclT.isConstQualified()) {
14545 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_non_const)
14546 << Init->getSourceRange();
14547 VDecl->setInvalidDecl();
14548
14549 // We allow integer constant expressions in all cases.
14550 } else if (DclT->isIntegralOrEnumerationType()) {
14551 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
14552 // In C++11, a non-constexpr const static data member with an
14553 // in-class initializer cannot be volatile.
14554 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_volatile);
14555
14556 // We allow foldable floating-point constants as an extension.
14557 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14558 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14559 // it anyway and provide a fixit to add the 'constexpr'.
14560 if (getLangOpts().CPlusPlus11) {
14561 Diag(Loc: VDecl->getLocation(),
14562 DiagID: diag::ext_in_class_initializer_float_type_cxx11)
14563 << DclT << Init->getSourceRange();
14564 Diag(Loc: VDecl->getBeginLoc(),
14565 DiagID: diag::note_in_class_initializer_float_type_cxx11)
14566 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14567 } else {
14568 Diag(Loc: VDecl->getLocation(), DiagID: diag::ext_in_class_initializer_float_type)
14569 << DclT << Init->getSourceRange();
14570
14571 if (!Init->isValueDependent() && !Init->isEvaluatable(Ctx: Context)) {
14572 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_in_class_initializer_non_constant)
14573 << Init->getSourceRange();
14574 VDecl->setInvalidDecl();
14575 }
14576 }
14577
14578 // Suggest adding 'constexpr' in C++11 for literal types.
14579 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Ctx: Context)) {
14580 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_literal_type)
14581 << DclT << Init->getSourceRange()
14582 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14583 VDecl->setConstexpr(true);
14584
14585 } else {
14586 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_bad_type)
14587 << DclT << Init->getSourceRange();
14588 VDecl->setInvalidDecl();
14589 }
14590 } else if (VDecl->isFileVarDecl()) {
14591 // In C, extern is typically used to avoid tentative definitions when
14592 // declaring variables in headers, but adding an initializer makes it a
14593 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14594 // In C++, extern is often used to give implicitly static const variables
14595 // external linkage, so don't warn in that case. If selectany is present,
14596 // this might be header code intended for C and C++ inclusion, so apply the
14597 // C++ rules.
14598 if (VDecl->getStorageClass() == SC_Extern &&
14599 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14600 !Context.getBaseElementType(QT: VDecl->getType()).isConstQualified()) &&
14601 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14602 !isTemplateInstantiation(Kind: VDecl->getTemplateSpecializationKind()))
14603 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_extern_init);
14604
14605 // In Microsoft C++ mode, a const variable defined in namespace scope has
14606 // external linkage by default if the variable is declared with
14607 // __declspec(dllexport).
14608 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14609 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
14610 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14611 VDecl->setStorageClass(SC_Extern);
14612
14613 // C99 6.7.8p4. All file scoped initializers need to be constant.
14614 // Avoid duplicate diagnostics for constexpr variables.
14615 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14616 !VDecl->isConstexpr())
14617 CheckForConstantInitializer(Init);
14618 }
14619
14620 QualType InitType = Init->getType();
14621 if (!InitType.isNull() &&
14622 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
14623 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
14624 checkNonTrivialCUnionInInitializer(Init, Loc: Init->getExprLoc());
14625
14626 // We will represent direct-initialization similarly to copy-initialization:
14627 // int x(1); -as-> int x = 1;
14628 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14629 //
14630 // Clients that want to distinguish between the two forms, can check for
14631 // direct initializer using VarDecl::getInitStyle().
14632 // A major benefit is that clients that don't particularly care about which
14633 // exactly form was it (like the CodeGen) can handle both cases without
14634 // special case code.
14635
14636 // C++ 8.5p11:
14637 // The form of initialization (using parentheses or '=') matters
14638 // when the entity being initialized has class type.
14639 if (InitializedFromParenListExpr) {
14640 assert(DirectInit && "Call-style initializer must be direct init.");
14641 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14642 : VarDecl::CallInit);
14643 } else if (DirectInit) {
14644 // This must be list-initialization. No other way is direct-initialization.
14645 VDecl->setInitStyle(VarDecl::ListInit);
14646 }
14647
14648 if (LangOpts.OpenMP &&
14649 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14650 VDecl->isFileVarDecl())
14651 DeclsToCheckForDeferredDiags.insert(X: VDecl);
14652 CheckCompleteVariableDeclaration(VD: VDecl);
14653
14654 if (LangOpts.OpenACC && !InitType.isNull())
14655 OpenACC().ActOnVariableInit(VD: VDecl, InitType);
14656}
14657
14658void Sema::ActOnInitializerError(Decl *D) {
14659 // Our main concern here is re-establishing invariants like "a
14660 // variable's type is either dependent or complete".
14661 if (!D || D->isInvalidDecl()) return;
14662
14663 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14664 if (!VD) return;
14665
14666 // Bindings are not usable if we can't make sense of the initializer.
14667 if (auto *DD = dyn_cast<DecompositionDecl>(Val: D))
14668 for (auto *BD : DD->bindings())
14669 BD->setInvalidDecl();
14670
14671 // Auto types are meaningless if we can't make sense of the initializer.
14672 if (VD->getType()->isUndeducedType()) {
14673 D->setInvalidDecl();
14674 return;
14675 }
14676
14677 QualType Ty = VD->getType();
14678 if (Ty->isDependentType()) return;
14679
14680 // Require a complete type.
14681 if (RequireCompleteType(Loc: VD->getLocation(),
14682 T: Context.getBaseElementType(QT: Ty),
14683 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14684 VD->setInvalidDecl();
14685 return;
14686 }
14687
14688 // Require a non-abstract type.
14689 if (RequireNonAbstractType(Loc: VD->getLocation(), T: Ty,
14690 DiagID: diag::err_abstract_type_in_decl,
14691 Args: AbstractVariableType)) {
14692 VD->setInvalidDecl();
14693 return;
14694 }
14695
14696 // Don't bother complaining about constructors or destructors,
14697 // though.
14698}
14699
14700void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
14701 // If there is no declaration, there was an error parsing it. Just ignore it.
14702 if (!RealDecl)
14703 return;
14704
14705 if (VarDecl *Var = dyn_cast<VarDecl>(Val: RealDecl)) {
14706 QualType Type = Var->getType();
14707
14708 if (Type.getDesugaredType(Context) == Context.AMDGPUFeaturePredicateTy) {
14709 Diag(Loc: Var->getLocation(),
14710 DiagID: diag::err_amdgcn_predicate_type_is_not_constructible)
14711 << Var;
14712 Var->setInvalidDecl();
14713 return;
14714 }
14715 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14716 if (isa<DecompositionDecl>(Val: RealDecl)) {
14717 // Point the caret to the token immediately after the closing bracket if
14718 // it can be found; otherwise fall back to the declaration's location.
14719 SourceLocation Loc = Var->getLocation();
14720 SourceLocation RSquareLoc =
14721 dyn_cast<DecompositionDecl>(Val: RealDecl)->getRSquareLoc();
14722 if (std::optional<Token> Next = Lexer::findNextToken(
14723 Loc: RSquareLoc, SM: PP.getSourceManager(), LangOpts: PP.getLangOpts()))
14724 Loc = Next->getLocation();
14725 Diag(Loc, DiagID: diag::err_decomp_decl_requires_init) << Var;
14726 Var->setInvalidDecl();
14727 return;
14728 }
14729
14730 if (Type->isUndeducedType() &&
14731 DeduceVariableDeclarationType(VDecl: Var, DirectInit: false, Init: nullptr))
14732 return;
14733
14734 this->CheckAttributesOnDeducedType(D: RealDecl);
14735
14736 // C++11 [class.static.data]p3: A static data member can be declared with
14737 // the constexpr specifier; if so, its declaration shall specify
14738 // a brace-or-equal-initializer.
14739 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14740 // the definition of a variable [...] or the declaration of a static data
14741 // member.
14742 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14743 !Var->isThisDeclarationADemotedDefinition()) {
14744 if (Var->isStaticDataMember()) {
14745 // C++1z removes the relevant rule; the in-class declaration is always
14746 // a definition there.
14747 if (!getLangOpts().CPlusPlus17 &&
14748 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14749 Diag(Loc: Var->getLocation(),
14750 DiagID: diag::err_constexpr_static_mem_var_requires_init)
14751 << Var;
14752 Var->setInvalidDecl();
14753 return;
14754 }
14755 } else {
14756 Diag(Loc: Var->getLocation(), DiagID: diag::err_invalid_constexpr_var_decl);
14757 Var->setInvalidDecl();
14758 return;
14759 }
14760 }
14761
14762 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14763 // be initialized.
14764 if (!Var->isInvalidDecl() &&
14765 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14766 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14767 bool HasConstExprDefaultConstructor = false;
14768 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14769 for (auto *Ctor : RD->ctors()) {
14770 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14771 Ctor->getMethodQualifiers().getAddressSpace() ==
14772 LangAS::opencl_constant) {
14773 HasConstExprDefaultConstructor = true;
14774 }
14775 }
14776 }
14777 if (!HasConstExprDefaultConstructor) {
14778 Diag(Loc: Var->getLocation(), DiagID: diag::err_opencl_constant_no_init);
14779 Var->setInvalidDecl();
14780 return;
14781 }
14782 }
14783
14784 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14785 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14786 Diag(Loc: Var->getLocation(), DiagID: diag::err_specialization_const);
14787 Var->setInvalidDecl();
14788 return;
14789 }
14790
14791 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14792 if (Var->getStorageClass() == SC_Extern) {
14793 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_extern_decl)
14794 << Var;
14795 Var->setInvalidDecl();
14796 return;
14797 }
14798 if (RequireCompleteType(Loc: Var->getLocation(), T: Var->getType(),
14799 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14800 Var->setInvalidDecl();
14801 return;
14802 }
14803 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14804 if (!RD->hasTrivialDefaultConstructor()) {
14805 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_trivial_ctor);
14806 Var->setInvalidDecl();
14807 return;
14808 }
14809 }
14810 // The declaration is uninitialized, no need for further checks.
14811 return;
14812 }
14813
14814 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14815 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14816 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14817 checkNonTrivialCUnion(QT: Var->getType(), Loc: Var->getLocation(),
14818 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
14819 NonTrivialKind: NTCUK_Init);
14820
14821 switch (DefKind) {
14822 case VarDecl::Definition:
14823 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14824 break;
14825
14826 // We have an out-of-line definition of a static data member
14827 // that has an in-class initializer, so we type-check this like
14828 // a declaration.
14829 //
14830 [[fallthrough]];
14831
14832 case VarDecl::DeclarationOnly:
14833 // It's only a declaration.
14834
14835 // Block scope. C99 6.7p7: If an identifier for an object is
14836 // declared with no linkage (C99 6.2.2p6), the type for the
14837 // object shall be complete.
14838 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14839 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14840 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14841 DiagID: diag::err_typecheck_decl_incomplete_type))
14842 Var->setInvalidDecl();
14843
14844 // Make sure that the type is not abstract.
14845 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14846 RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14847 DiagID: diag::err_abstract_type_in_decl,
14848 Args: AbstractVariableType))
14849 Var->setInvalidDecl();
14850 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14851 Var->getStorageClass() == SC_PrivateExtern) {
14852 Diag(Loc: Var->getLocation(), DiagID: diag::warn_private_extern);
14853 Diag(Loc: Var->getLocation(), DiagID: diag::note_private_extern);
14854 }
14855
14856 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14857 !Var->isInvalidDecl())
14858 ExternalDeclarations.push_back(Elt: Var);
14859
14860 return;
14861
14862 case VarDecl::TentativeDefinition:
14863 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14864 // object that has file scope without an initializer, and without a
14865 // storage-class specifier or with the storage-class specifier "static",
14866 // constitutes a tentative definition. Note: A tentative definition with
14867 // external linkage is valid (C99 6.2.2p5).
14868 if (!Var->isInvalidDecl()) {
14869 if (const IncompleteArrayType *ArrayT
14870 = Context.getAsIncompleteArrayType(T: Type)) {
14871 if (RequireCompleteSizedType(
14872 Loc: Var->getLocation(), T: ArrayT->getElementType(),
14873 DiagID: diag::err_array_incomplete_or_sizeless_type))
14874 Var->setInvalidDecl();
14875 }
14876 if (Var->getStorageClass() == SC_Static) {
14877 // C99 6.9.2p3: If the declaration of an identifier for an object is
14878 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14879 // declared type shall not be an incomplete type.
14880 // NOTE: code such as the following
14881 // static struct s;
14882 // struct s { int a; };
14883 // is accepted by gcc. Hence here we issue a warning instead of
14884 // an error and we do not invalidate the static declaration.
14885 // NOTE: to avoid multiple warnings, only check the first declaration.
14886 if (Var->isFirstDecl())
14887 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14888 DiagID: diag::ext_typecheck_decl_incomplete_type,
14889 Args: Type->isArrayType());
14890 }
14891 }
14892
14893 // Record the tentative definition; we're done.
14894 if (!Var->isInvalidDecl())
14895 TentativeDefinitions.push_back(LocalValue: Var);
14896 return;
14897 }
14898
14899 // Provide a specific diagnostic for uninitialized variable definitions
14900 // with incomplete array type, unless it is a global unbounded HLSL resource
14901 // array.
14902 if (Type->isIncompleteArrayType() &&
14903 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14904 Type->isHLSLResourceRecordArray())) {
14905 if (Var->isConstexpr())
14906 Diag(Loc: Var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
14907 << Var;
14908 else
14909 Diag(Loc: Var->getLocation(),
14910 DiagID: diag::err_typecheck_incomplete_array_needs_initializer);
14911 Var->setInvalidDecl();
14912 return;
14913 }
14914
14915 // Provide a specific diagnostic for uninitialized variable
14916 // definitions with reference type.
14917 if (Type->isReferenceType()) {
14918 Diag(Loc: Var->getLocation(), DiagID: diag::err_reference_var_requires_init)
14919 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14920 return;
14921 }
14922
14923 // Do not attempt to type-check the default initializer for a
14924 // variable with dependent type.
14925 if (Type->isDependentType())
14926 return;
14927
14928 if (Var->isInvalidDecl())
14929 return;
14930
14931 if (!Var->hasAttr<AliasAttr>()) {
14932 if (RequireCompleteType(Loc: Var->getLocation(),
14933 T: Context.getBaseElementType(QT: Type),
14934 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14935 Var->setInvalidDecl();
14936 return;
14937 }
14938 } else {
14939 return;
14940 }
14941
14942 // The variable can not have an abstract class type.
14943 if (RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14944 DiagID: diag::err_abstract_type_in_decl,
14945 Args: AbstractVariableType)) {
14946 Var->setInvalidDecl();
14947 return;
14948 }
14949
14950 // In C, if the definition is const-qualified and has no initializer, it
14951 // is left uninitialized unless it has static or thread storage duration.
14952 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14953 unsigned DiagID = diag::warn_default_init_const_unsafe;
14954 if (Var->getStorageDuration() == SD_Static ||
14955 Var->getStorageDuration() == SD_Thread)
14956 DiagID = diag::warn_default_init_const;
14957
14958 bool EmitCppCompat = !Diags.isIgnored(
14959 DiagID: diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14960 Loc: Var->getLocation());
14961
14962 Diag(Loc: Var->getLocation(), DiagID) << Type << EmitCppCompat;
14963 }
14964
14965 // Check for jumps past the implicit initializer. C++0x
14966 // clarifies that this applies to a "variable with automatic
14967 // storage duration", not a "local variable".
14968 // C++11 [stmt.dcl]p3
14969 // A program that jumps from a point where a variable with automatic
14970 // storage duration is not in scope to a point where it is in scope is
14971 // ill-formed unless the variable has scalar type, class type with a
14972 // trivial default constructor and a trivial destructor, a cv-qualified
14973 // version of one of these types, or an array of one of the preceding
14974 // types and is declared without an initializer.
14975 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14976 if (const auto *CXXRecord =
14977 Context.getBaseElementType(QT: Type)->getAsCXXRecordDecl()) {
14978 // Mark the function (if we're in one) for further checking even if the
14979 // looser rules of C++11 do not require such checks, so that we can
14980 // diagnose incompatibilities with C++98.
14981 if (!CXXRecord->isPOD())
14982 setFunctionHasBranchProtectedScope();
14983 }
14984 }
14985 // In OpenCL, we can't initialize objects in the __local address space,
14986 // even implicitly, so don't synthesize an implicit initializer.
14987 if (getLangOpts().OpenCL &&
14988 Var->getType().getAddressSpace() == LangAS::opencl_local)
14989 return;
14990
14991 // Handle HLSL uninitialized decls
14992 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(D: Var))
14993 return;
14994
14995 // HLSL input & push-constant variables are expected to be externally
14996 // initialized, even when marked `static`.
14997 if (getLangOpts().HLSL &&
14998 hlsl::isInitializedByPipeline(AS: Var->getType().getAddressSpace()))
14999 return;
15000
15001 // C++03 [dcl.init]p9:
15002 // If no initializer is specified for an object, and the
15003 // object is of (possibly cv-qualified) non-POD class type (or
15004 // array thereof), the object shall be default-initialized; if
15005 // the object is of const-qualified type, the underlying class
15006 // type shall have a user-declared default
15007 // constructor. Otherwise, if no initializer is specified for
15008 // a non- static object, the object and its subobjects, if
15009 // any, have an indeterminate initial value); if the object
15010 // or any of its subobjects are of const-qualified type, the
15011 // program is ill-formed.
15012 // C++0x [dcl.init]p11:
15013 // If no initializer is specified for an object, the object is
15014 // default-initialized; [...].
15015 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
15016 InitializationKind Kind
15017 = InitializationKind::CreateDefault(InitLoc: Var->getLocation());
15018
15019 InitializationSequence InitSeq(*this, Entity, Kind, {});
15020 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: {});
15021
15022 if (Init.get()) {
15023 Var->setInit(MaybeCreateExprWithCleanups(SubExpr: Init.get()));
15024 // This is important for template substitution.
15025 Var->setInitStyle(VarDecl::CallInit);
15026 } else if (Init.isInvalid()) {
15027 // If default-init fails, attach a recovery-expr initializer to track
15028 // that initialization was attempted and failed.
15029 auto RecoveryExpr =
15030 CreateRecoveryExpr(Begin: Var->getLocation(), End: Var->getLocation(), SubExprs: {});
15031 if (RecoveryExpr.get())
15032 Var->setInit(RecoveryExpr.get());
15033 }
15034
15035 CheckCompleteVariableDeclaration(VD: Var);
15036 }
15037}
15038
15039void Sema::ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt) {
15040 // If there is no declaration, there was an error parsing it. Ignore it.
15041 if (!D)
15042 return;
15043
15044 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
15045 if (!VD) {
15046 Diag(Loc: D->getLocation(), DiagID: diag::err_for_range_decl_must_be_var)
15047 << InExpansionStmt;
15048 D->setInvalidDecl();
15049 return;
15050 }
15051
15052 VD->setCXXForRangeDecl(true);
15053
15054 // for-range-declaration cannot be given a storage class specifier.
15055 int Error = -1;
15056 switch (VD->getStorageClass()) {
15057 case SC_None:
15058 break;
15059 case SC_Extern:
15060 Error = 0;
15061 break;
15062 case SC_Static:
15063 Error = 1;
15064 break;
15065 case SC_PrivateExtern:
15066 Error = 2;
15067 break;
15068 case SC_Auto:
15069 Error = 3;
15070 break;
15071 case SC_Register:
15072 Error = 4;
15073 break;
15074 }
15075
15076 // for-range-declaration cannot be given a storage class specifier con't.
15077 switch (VD->getTSCSpec()) {
15078 case TSCS_thread_local:
15079 Error = 6;
15080 break;
15081 case TSCS___thread:
15082 case TSCS__Thread_local:
15083 case TSCS_unspecified:
15084 break;
15085 }
15086
15087 if (Error != -1) {
15088 Diag(Loc: VD->getOuterLocStart(), DiagID: diag::err_for_range_storage_class)
15089 << InExpansionStmt << VD << Error;
15090 D->setInvalidDecl();
15091 }
15092}
15093
15094StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
15095 IdentifierInfo *Ident,
15096 ParsedAttributes &Attrs) {
15097 // C++1y [stmt.iter]p1:
15098 // A range-based for statement of the form
15099 // for ( for-range-identifier : for-range-initializer ) statement
15100 // is equivalent to
15101 // for ( auto&& for-range-identifier : for-range-initializer ) statement
15102 DeclSpec DS(Attrs.getPool().getFactory());
15103
15104 const char *PrevSpec;
15105 unsigned DiagID;
15106 DS.SetTypeSpecType(T: DeclSpec::TST_auto, Loc: IdentLoc, PrevSpec, DiagID,
15107 Policy: getPrintingPolicy());
15108
15109 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
15110 D.SetIdentifier(Id: Ident, IdLoc: IdentLoc);
15111 D.takeAttributesAppending(attrs&: Attrs);
15112
15113 D.AddTypeInfo(TI: DeclaratorChunk::getReference(TypeQuals: 0, Loc: IdentLoc, /*lvalue*/ false),
15114 EndLoc: IdentLoc);
15115 Decl *Var = ActOnDeclarator(S, D);
15116 cast<VarDecl>(Val: Var)->setCXXForRangeDecl(true);
15117 FinalizeDeclaration(D: Var);
15118 return ActOnDeclStmt(Decl: FinalizeDeclaratorGroup(S, DS, Group: Var), StartLoc: IdentLoc,
15119 EndLoc: Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
15120 : IdentLoc);
15121}
15122
15123void Sema::addLifetimeBoundToImplicitThis(CXXMethodDecl *MD) {
15124 if (!MD || lifetimes::implicitObjectParamIsLifetimeBound(FD: MD))
15125 return;
15126 auto *Attr = LifetimeBoundAttr::CreateImplicit(Ctx&: Context, Range: MD->getLocation());
15127 QualType MethodType = MD->getType();
15128 QualType AttributedType =
15129 Context.getAttributedType(attr: Attr, modifiedType: MethodType, equivalentType: MethodType);
15130 TypeLocBuilder TLB;
15131 TypeSourceInfo *TSI = MD->getTypeSourceInfo();
15132 if (TSI && TSI->getTypeLoc().getType() == MethodType) {
15133 TLB.pushFullCopy(L: TSI->getTypeLoc());
15134 } else {
15135 // The written type-source info can disagree with the method's type. For
15136 // example, a deduced 'auto' return type in a template instantiation keeps
15137 // the 'auto' placeholder in its TypeSourceInfo while the method's type has
15138 // already been resolved to the deduced type. Pushing the stale TypeLoc
15139 // would make the wrapping AttributedTypeLoc's inner type inconsistent with
15140 // MethodType. Build a trivial TypeLoc that matches MethodType instead.
15141 TLB.pushTrivial(Context, T: MethodType, Loc: MD->getLocation());
15142 }
15143 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(T: AttributedType);
15144 TyLoc.setAttr(Attr);
15145 MD->setType(AttributedType);
15146 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, T: AttributedType));
15147}
15148
15149void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
15150 if (var->isInvalidDecl()) return;
15151
15152 CUDA().MaybeAddConstantAttr(VD: var);
15153
15154 if (getLangOpts().OpenCL) {
15155 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
15156 // initialiser
15157 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
15158 !var->hasInit()) {
15159 Diag(Loc: var->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
15160 << 1 /*Init*/;
15161 var->setInvalidDecl();
15162 return;
15163 }
15164 }
15165
15166 // In Objective-C, don't allow jumps past the implicit initialization of a
15167 // local retaining variable.
15168 if (getLangOpts().ObjC &&
15169 var->hasLocalStorage()) {
15170 switch (var->getType().getObjCLifetime()) {
15171 case Qualifiers::OCL_None:
15172 case Qualifiers::OCL_ExplicitNone:
15173 case Qualifiers::OCL_Autoreleasing:
15174 break;
15175
15176 case Qualifiers::OCL_Weak:
15177 case Qualifiers::OCL_Strong:
15178 setFunctionHasBranchProtectedScope();
15179 break;
15180 }
15181 }
15182
15183 if (var->hasLocalStorage() &&
15184 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
15185 setFunctionHasBranchProtectedScope();
15186
15187 // Warn about externally-visible variables being defined without a
15188 // prior declaration. We only want to do this for global
15189 // declarations, but we also specifically need to avoid doing it for
15190 // class members because the linkage of an anonymous class can
15191 // change if it's later given a typedef name.
15192 if (var->isThisDeclarationADefinition() &&
15193 var->getDeclContext()->getRedeclContext()->isFileContext() &&
15194 var->isExternallyVisible() && var->hasLinkage() &&
15195 !var->isInline() && !var->getDescribedVarTemplate() &&
15196 var->getStorageClass() != SC_Register &&
15197 !isa<VarTemplatePartialSpecializationDecl>(Val: var) &&
15198 !isTemplateInstantiation(Kind: var->getTemplateSpecializationKind()) &&
15199 !getDiagnostics().isIgnored(DiagID: diag::warn_missing_variable_declarations,
15200 Loc: var->getLocation())) {
15201 // Find a previous declaration that's not a definition.
15202 VarDecl *prev = var->getPreviousDecl();
15203 while (prev && prev->isThisDeclarationADefinition())
15204 prev = prev->getPreviousDecl();
15205
15206 if (!prev) {
15207 Diag(Loc: var->getLocation(), DiagID: diag::warn_missing_variable_declarations) << var;
15208 Diag(Loc: var->getTypeSpecStartLoc(), DiagID: diag::note_static_for_internal_linkage)
15209 << /* variable */ 0;
15210 }
15211 }
15212
15213 // Cache the result of checking for constant initialization.
15214 std::optional<bool> CacheHasConstInit;
15215 const Expr *CacheCulprit = nullptr;
15216 auto checkConstInit = [&]() mutable {
15217 const Expr *Init = var->getInit();
15218 if (Init->isInstantiationDependent())
15219 return true;
15220
15221 if (!CacheHasConstInit)
15222 CacheHasConstInit = var->getInit()->isConstantInitializer(
15223 Ctx&: Context, ForRef: var->getType()->isReferenceType(), Culprit: &CacheCulprit);
15224 return *CacheHasConstInit;
15225 };
15226
15227 if (var->getTLSKind() == VarDecl::TLS_Static) {
15228 if (var->getType().isDestructedType()) {
15229 // GNU C++98 edits for __thread, [basic.start.term]p3:
15230 // The type of an object with thread storage duration shall not
15231 // have a non-trivial destructor.
15232 Diag(Loc: var->getLocation(), DiagID: diag::err_thread_nontrivial_dtor);
15233 if (getLangOpts().CPlusPlus11)
15234 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
15235 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
15236 if (!checkConstInit()) {
15237 // GNU C++98 edits for __thread, [basic.start.init]p4:
15238 // An object of thread storage duration shall not require dynamic
15239 // initialization.
15240 // FIXME: Need strict checking here.
15241 Diag(Loc: CacheCulprit->getExprLoc(), DiagID: diag::err_thread_dynamic_init)
15242 << CacheCulprit->getSourceRange();
15243 if (getLangOpts().CPlusPlus11)
15244 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
15245 }
15246 }
15247 }
15248
15249
15250 if (!var->getType()->isStructureType() && var->hasInit() &&
15251 isa<InitListExpr>(Val: var->getInit())) {
15252 const auto *ILE = cast<InitListExpr>(Val: var->getInit());
15253 unsigned NumInits = ILE->getNumInits();
15254 if (NumInits > 2)
15255 for (unsigned I = 0; I < NumInits; ++I) {
15256 const auto *Init = ILE->getInit(Init: I);
15257 if (!Init)
15258 break;
15259 const auto *SL = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
15260 if (!SL)
15261 break;
15262
15263 unsigned NumConcat = SL->getNumConcatenated();
15264 // Diagnose missing comma in string array initialization.
15265 // Do not warn when all the elements in the initializer are concatenated
15266 // together. Do not warn for macros too.
15267 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
15268 bool OnlyOneMissingComma = true;
15269 for (unsigned J = I + 1; J < NumInits; ++J) {
15270 const auto *Init = ILE->getInit(Init: J);
15271 if (!Init)
15272 break;
15273 const auto *SLJ = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
15274 if (!SLJ || SLJ->getNumConcatenated() > 1) {
15275 OnlyOneMissingComma = false;
15276 break;
15277 }
15278 }
15279
15280 if (OnlyOneMissingComma) {
15281 SmallVector<FixItHint, 1> Hints;
15282 for (unsigned i = 0; i < NumConcat - 1; ++i)
15283 Hints.push_back(Elt: FixItHint::CreateInsertion(
15284 InsertionLoc: PP.getLocForEndOfToken(Loc: SL->getStrTokenLoc(TokNum: i)), Code: ","));
15285
15286 Diag(Loc: SL->getStrTokenLoc(TokNum: 1),
15287 DiagID: diag::warn_concatenated_literal_array_init)
15288 << Hints;
15289 Diag(Loc: SL->getBeginLoc(),
15290 DiagID: diag::note_concatenated_string_literal_silence);
15291 }
15292 // In any case, stop now.
15293 break;
15294 }
15295 }
15296 }
15297
15298
15299 QualType type = var->getType();
15300
15301 if (var->hasAttr<BlocksAttr>())
15302 getCurFunction()->addByrefBlockVar(VD: var);
15303
15304 Expr *Init = var->getInit();
15305 bool GlobalStorage = var->hasGlobalStorage();
15306 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
15307 QualType baseType = Context.getBaseElementType(QT: type);
15308 bool HasConstInit = true;
15309
15310 if (getLangOpts().C23 && var->isConstexpr() && !Init)
15311 Diag(Loc: var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
15312 << var;
15313
15314 // Check whether the initializer is sufficiently constant.
15315 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
15316 !type->isDependentType() && Init && !Init->isValueDependent() &&
15317 (GlobalStorage || var->isConstexpr() ||
15318 var->mightBeUsableInConstantExpressions(C: Context))) {
15319 // If this variable might have a constant initializer or might be usable in
15320 // constant expressions, check whether or not it actually is now. We can't
15321 // do this lazily, because the result might depend on things that change
15322 // later, such as which constexpr functions happen to be defined.
15323 SmallVector<PartialDiagnosticAt, 8> Notes;
15324 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
15325 // Prior to C++11, in contexts where a constant initializer is required,
15326 // the set of valid constant initializers is described by syntactic rules
15327 // in [expr.const]p2-6.
15328 // FIXME: Stricter checking for these rules would be useful for constinit /
15329 // -Wglobal-constructors.
15330 HasConstInit = checkConstInit();
15331
15332 // Compute and cache the constant value, and remember that we have a
15333 // constant initializer.
15334 if (HasConstInit) {
15335 if (var->isStaticDataMember() && !var->isInline() &&
15336 var->getLexicalDeclContext()->isRecord() &&
15337 type->isIntegralOrEnumerationType()) {
15338 // In C++98, in-class initialization for a static data member must
15339 // be an integer constant expression.
15340 if (!Init->isIntegerConstantExpr(Ctx: Context)) {
15341 Diag(Loc: Init->getExprLoc(),
15342 DiagID: diag::ext_in_class_initializer_non_constant)
15343 << Init->getSourceRange();
15344 }
15345 }
15346 (void)var->checkForConstantInitialization(Notes);
15347 Notes.clear();
15348 } else if (CacheCulprit) {
15349 Notes.emplace_back(Args: CacheCulprit->getExprLoc(),
15350 Args: PDiag(DiagID: diag::note_invalid_subexpr_in_const_expr));
15351 Notes.back().second << CacheCulprit->getSourceRange();
15352 }
15353 } else {
15354 // Evaluate the initializer to see if it's a constant initializer.
15355 HasConstInit = var->checkForConstantInitialization(Notes);
15356 }
15357
15358 if (HasConstInit) {
15359 // FIXME: Consider replacing the initializer with a ConstantExpr.
15360 } else if (var->isConstexpr()) {
15361 SourceLocation DiagLoc = var->getLocation();
15362 // If the note doesn't add any useful information other than a source
15363 // location, fold it into the primary diagnostic.
15364 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15365 diag::note_invalid_subexpr_in_const_expr) {
15366 DiagLoc = Notes[0].first;
15367 Notes.clear();
15368 }
15369 Diag(Loc: DiagLoc, DiagID: diag::err_constexpr_var_requires_const_init)
15370 << var << Init->getSourceRange();
15371 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15372 Diag(Loc: Notes[I].first, PD: Notes[I].second);
15373 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15374 auto *Attr = var->getAttr<ConstInitAttr>();
15375 Diag(Loc: var->getLocation(), DiagID: diag::err_require_constant_init_failed)
15376 << Init->getSourceRange();
15377 Diag(Loc: Attr->getLocation(), DiagID: diag::note_declared_required_constant_init_here)
15378 << Attr->getRange() << Attr->isConstinit();
15379 for (auto &it : Notes)
15380 Diag(Loc: it.first, PD: it.second);
15381 } else if (var->isStaticDataMember() && !var->isInline() &&
15382 var->getLexicalDeclContext()->isRecord()) {
15383 Diag(Loc: var->getLocation(), DiagID: diag::err_in_class_initializer_non_constant)
15384 << Init->getSourceRange();
15385 for (auto &it : Notes)
15386 Diag(Loc: it.first, PD: it.second);
15387 var->setInvalidDecl();
15388 } else if (IsGlobal &&
15389 !getDiagnostics().isIgnored(DiagID: diag::warn_global_constructor,
15390 Loc: var->getLocation())) {
15391 // Warn about globals which don't have a constant initializer. Don't
15392 // warn about globals with a non-trivial destructor because we already
15393 // warned about them.
15394 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15395 if (!(RD && !RD->hasTrivialDestructor())) {
15396 // checkConstInit() here permits trivial default initialization even in
15397 // C++11 onwards, where such an initializer is not a constant initializer
15398 // but nonetheless doesn't require a global constructor.
15399 if (!checkConstInit())
15400 Diag(Loc: var->getLocation(), DiagID: diag::warn_global_constructor)
15401 << Init->getSourceRange();
15402 }
15403 }
15404 }
15405
15406 // Apply section attributes and pragmas to global variables.
15407 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15408 !inTemplateInstantiation()) {
15409 PragmaStack<StringLiteral *> *Stack = nullptr;
15410 int SectionFlags = ASTContext::PSF_Read;
15411 bool MSVCEnv =
15412 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15413 std::optional<QualType::NonConstantStorageReason> Reason;
15414 if (HasConstInit &&
15415 !(Reason = var->getType().isNonConstantStorage(Ctx: Context, ExcludeCtor: true, ExcludeDtor: false))) {
15416 Stack = &ConstSegStack;
15417 } else {
15418 SectionFlags |= ASTContext::PSF_Write;
15419 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15420 }
15421 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15422 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15423 SectionFlags |= ASTContext::PSF_Implicit;
15424 UnifySection(SectionName: SA->getName(), SectionFlags, TheDecl: var);
15425 } else if (Stack->CurrentValue) {
15426 if (Stack != &ConstSegStack && MSVCEnv &&
15427 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15428 var->getType().isConstQualified()) {
15429 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15430 NonConstNonReferenceType) &&
15431 "This case should've already been handled elsewhere");
15432 Diag(Loc: var->getLocation(), DiagID: diag::warn_section_msvc_compat)
15433 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15434 ? QualType::NonConstantStorageReason::NonTrivialCtor
15435 : *Reason);
15436 }
15437 SectionFlags |= ASTContext::PSF_Implicit;
15438 auto SectionName = Stack->CurrentValue->getString();
15439 var->addAttr(A: SectionAttr::CreateImplicit(Ctx&: Context, Name: SectionName,
15440 Range: Stack->CurrentPragmaLocation,
15441 S: SectionAttr::Declspec_allocate));
15442 if (UnifySection(SectionName, SectionFlags, TheDecl: var))
15443 var->dropAttr<SectionAttr>();
15444 }
15445
15446 // Apply the init_seg attribute if this has an initializer. If the
15447 // initializer turns out to not be dynamic, we'll end up ignoring this
15448 // attribute.
15449 if (CurInitSeg && var->getInit())
15450 var->addAttr(A: InitSegAttr::CreateImplicit(Ctx&: Context, Section: CurInitSeg->getString(),
15451 Range: CurInitSegLoc));
15452 }
15453
15454 // All the following checks are C++ only.
15455 if (!getLangOpts().CPlusPlus) {
15456 // If this variable must be emitted, add it as an initializer for the
15457 // current module.
15458 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty())
15459 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15460 return;
15461 }
15462
15463 DiagnoseUniqueObjectDuplication(VD: var);
15464
15465 // Require the destructor.
15466 if (!type->isDependentType())
15467 if (auto *RD = baseType->getAsCXXRecordDecl())
15468 FinalizeVarWithDestructor(VD: var, DeclInit: RD);
15469
15470 // If this variable must be emitted, add it as an initializer for the current
15471 // module. For named modules, discardable inline variables may be deferred
15472 // until they are odr-used. Non-inline variables that must be emitted,
15473 // including those with side-effecting initialization, must still be emitted
15474 // even if they have internal linkage.
15475 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty()) {
15476 GVALinkage Linkage = Context.GetGVALinkageForVariable(VD: var);
15477 if (ModuleScopes.back().Module->isHeaderLikeModule() ||
15478 !isDiscardableGVALinkage(L: Linkage) ||
15479 (Linkage == GVA_Internal && !var->isInline()))
15480 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15481 }
15482
15483 // Build the bindings if this is a structured binding declaration.
15484 if (auto *DD = dyn_cast<DecompositionDecl>(Val: var))
15485 CheckCompleteDecompositionDeclaration(DD);
15486}
15487
15488void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
15489 assert(VD->isStaticLocal());
15490
15491 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15492
15493 // Find outermost function when VD is in lambda function.
15494 while (FD && !getDLLAttr(D: FD) &&
15495 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15496 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15497 FD = dyn_cast_or_null<FunctionDecl>(Val: FD->getParentFunctionOrMethod());
15498 }
15499
15500 if (!FD)
15501 return;
15502
15503 // Static locals inherit dll attributes from their function.
15504 if (Attr *A = getDLLAttr(D: FD)) {
15505 auto *NewAttr = cast<InheritableAttr>(Val: A->clone(C&: getASTContext()));
15506 NewAttr->setInherited(true);
15507 VD->addAttr(A: NewAttr);
15508 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15509 auto *NewAttr = DLLExportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15510 NewAttr->setInherited(true);
15511 VD->addAttr(A: NewAttr);
15512
15513 // Export this function to enforce exporting this static variable even
15514 // if it is not used in this compilation unit.
15515 if (!FD->hasAttr<DLLExportAttr>())
15516 FD->addAttr(A: NewAttr);
15517
15518 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15519 auto *NewAttr = DLLImportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15520 NewAttr->setInherited(true);
15521 VD->addAttr(A: NewAttr);
15522 }
15523}
15524
15525void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
15526 assert(VD->getTLSKind());
15527
15528 // Perform TLS alignment check here after attributes attached to the variable
15529 // which may affect the alignment have been processed. Only perform the check
15530 // if the target has a maximum TLS alignment (zero means no constraints).
15531 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15532 // Protect the check so that it's not performed on dependent types and
15533 // dependent alignments (we can't determine the alignment in that case).
15534 if (!VD->hasDependentAlignment()) {
15535 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(BitSize: MaxAlign);
15536 if (Context.getDeclAlign(D: VD) > MaxAlignChars) {
15537 Diag(Loc: VD->getLocation(), DiagID: diag::err_tls_var_aligned_over_maximum)
15538 << (unsigned)Context.getDeclAlign(D: VD).getQuantity() << VD
15539 << (unsigned)MaxAlignChars.getQuantity();
15540 }
15541 }
15542 }
15543}
15544
15545void Sema::FinalizeDeclaration(Decl *ThisDecl) {
15546 // Note that we are no longer parsing the initializer for this declaration.
15547 ParsingInitForAutoVars.erase(Ptr: ThisDecl);
15548
15549 VarDecl *VD = dyn_cast_or_null<VarDecl>(Val: ThisDecl);
15550 if (!VD)
15551 return;
15552
15553 // Emit any deferred warnings for the variable's initializer, even if the
15554 // variable is invalid
15555 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15556
15557 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15558 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
15559 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15560 if (PragmaClangBSSSection.Valid)
15561 VD->addAttr(A: PragmaClangBSSSectionAttr::CreateImplicit(
15562 Ctx&: Context, Name: PragmaClangBSSSection.SectionName,
15563 Range: PragmaClangBSSSection.PragmaLocation));
15564 if (PragmaClangDataSection.Valid)
15565 VD->addAttr(A: PragmaClangDataSectionAttr::CreateImplicit(
15566 Ctx&: Context, Name: PragmaClangDataSection.SectionName,
15567 Range: PragmaClangDataSection.PragmaLocation));
15568 if (PragmaClangRodataSection.Valid)
15569 VD->addAttr(A: PragmaClangRodataSectionAttr::CreateImplicit(
15570 Ctx&: Context, Name: PragmaClangRodataSection.SectionName,
15571 Range: PragmaClangRodataSection.PragmaLocation));
15572 if (PragmaClangRelroSection.Valid)
15573 VD->addAttr(A: PragmaClangRelroSectionAttr::CreateImplicit(
15574 Ctx&: Context, Name: PragmaClangRelroSection.SectionName,
15575 Range: PragmaClangRelroSection.PragmaLocation));
15576 }
15577
15578 if (auto *DD = dyn_cast<DecompositionDecl>(Val: ThisDecl)) {
15579 for (auto *BD : DD->bindings()) {
15580 FinalizeDeclaration(ThisDecl: BD);
15581 }
15582 }
15583
15584 CheckInvalidBuiltinCountedByRef(E: VD->getInit(),
15585 K: BuiltinCountedByRefKind::Initializer);
15586
15587 checkAttributesAfterMerging(S&: *this, ND&: *VD);
15588
15589 if (VD->isStaticLocal())
15590 CheckStaticLocalForDllExport(VD);
15591
15592 if (VD->getTLSKind())
15593 CheckThreadLocalForLargeAlignment(VD);
15594
15595 // Perform check for initializers of device-side global variables.
15596 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15597 // 7.5). We must also apply the same checks to all __shared__
15598 // variables whether they are local or not. CUDA also allows
15599 // constant initializers for __constant__ and __device__ variables.
15600 if (getLangOpts().CUDA)
15601 CUDA().checkAllowedInitializer(VD);
15602
15603 // Grab the dllimport or dllexport attribute off of the VarDecl.
15604 const InheritableAttr *DLLAttr = getDLLAttr(D: VD);
15605
15606 // Imported static data members cannot be defined out-of-line.
15607 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(Val: DLLAttr)) {
15608 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15609 VD->isThisDeclarationADefinition()) {
15610 // We allow definitions of dllimport class template static data members
15611 // with a warning.
15612 CXXRecordDecl *Context =
15613 cast<CXXRecordDecl>(Val: VD->getFirstDecl()->getDeclContext());
15614 bool IsClassTemplateMember =
15615 isa<ClassTemplatePartialSpecializationDecl>(Val: Context) ||
15616 Context->getDescribedClassTemplate();
15617
15618 Diag(Loc: VD->getLocation(),
15619 DiagID: IsClassTemplateMember
15620 ? diag::warn_attribute_dllimport_static_field_definition
15621 : diag::err_attribute_dllimport_static_field_definition);
15622 Diag(Loc: IA->getLocation(), DiagID: diag::note_attribute);
15623 if (!IsClassTemplateMember)
15624 VD->setInvalidDecl();
15625 }
15626 }
15627
15628 // dllimport/dllexport variables cannot be thread local, their TLS index
15629 // isn't exported with the variable.
15630 if (DLLAttr && VD->getTLSKind()) {
15631 auto *F = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15632 if (F && getDLLAttr(D: F)) {
15633 assert(VD->isStaticLocal());
15634 // But if this is a static local in a dlimport/dllexport function, the
15635 // function will never be inlined, which means the var would never be
15636 // imported, so having it marked import/export is safe.
15637 } else {
15638 Diag(Loc: VD->getLocation(), DiagID: diag::err_attribute_dll_thread_local) << VD
15639 << DLLAttr;
15640 VD->setInvalidDecl();
15641 }
15642 }
15643
15644 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15645 if (!Attr->isInherited() && !Attr->isImplicit() &&
15646 !VD->isThisDeclarationADefinition()) {
15647 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15648 << Attr;
15649 VD->dropAttr<UsedAttr>();
15650 }
15651 }
15652 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15653 if (!Attr->isInherited() && !Attr->isImplicit() &&
15654 !VD->isThisDeclarationADefinition()) {
15655 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15656 << Attr;
15657 VD->dropAttr<RetainAttr>();
15658 }
15659 }
15660
15661 const DeclContext *DC = VD->getDeclContext();
15662 // If there's a #pragma GCC visibility in scope, and this isn't a class
15663 // member, set the visibility of this variable.
15664 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
15665 AddPushedVisibilityAttribute(RD: VD);
15666
15667 // FIXME: Warn on unused var template partial specializations.
15668 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(Val: VD))
15669 MarkUnusedFileScopedDecl(D: VD);
15670
15671 // Now we have parsed the initializer and can update the table of magic
15672 // tag values.
15673 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15674 !VD->getType()->isIntegralOrEnumerationType())
15675 return;
15676
15677 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15678 const Expr *MagicValueExpr = VD->getInit();
15679 if (!MagicValueExpr) {
15680 continue;
15681 }
15682 std::optional<llvm::APSInt> MagicValueInt;
15683 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Ctx: Context))) {
15684 Diag(Loc: I->getRange().getBegin(),
15685 DiagID: diag::err_type_tag_for_datatype_not_ice)
15686 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15687 continue;
15688 }
15689 if (MagicValueInt->getActiveBits() > 64) {
15690 Diag(Loc: I->getRange().getBegin(),
15691 DiagID: diag::err_type_tag_for_datatype_too_large)
15692 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15693 continue;
15694 }
15695 uint64_t MagicValue = MagicValueInt->getZExtValue();
15696 RegisterTypeTagForDatatype(ArgumentKind: I->getArgumentKind(),
15697 MagicValue,
15698 Type: I->getMatchingCType(),
15699 LayoutCompatible: I->getLayoutCompatible(),
15700 MustBeNull: I->getMustBeNull());
15701 }
15702}
15703
15704static bool hasDeducedAuto(DeclaratorDecl *DD) {
15705 auto *VD = dyn_cast<VarDecl>(Val: DD);
15706 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15707}
15708
15709Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
15710 ArrayRef<Decl *> Group) {
15711 SmallVector<Decl*, 8> Decls;
15712
15713 if (DS.isTypeSpecOwned())
15714 Decls.push_back(Elt: DS.getRepAsDecl());
15715
15716 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15717 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15718 bool DiagnosedMultipleDecomps = false;
15719 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15720 bool DiagnosedNonDeducedAuto = false;
15721
15722 for (Decl *D : Group) {
15723 if (!D)
15724 continue;
15725 // Check if the Decl has been declared in '#pragma omp declare target'
15726 // directive and has static storage duration.
15727 if (auto *VD = dyn_cast<VarDecl>(Val: D);
15728 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15729 VD->hasGlobalStorage())
15730 OpenMP().ActOnOpenMPDeclareTargetInitializer(D);
15731 // For declarators, there are some additional syntactic-ish checks we need
15732 // to perform.
15733 if (auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
15734 if (!FirstDeclaratorInGroup)
15735 FirstDeclaratorInGroup = DD;
15736 if (!FirstDecompDeclaratorInGroup)
15737 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(Val: D);
15738 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15739 !hasDeducedAuto(DD))
15740 FirstNonDeducedAutoInGroup = DD;
15741
15742 if (FirstDeclaratorInGroup != DD) {
15743 // A decomposition declaration cannot be combined with any other
15744 // declaration in the same group.
15745 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15746 Diag(Loc: FirstDecompDeclaratorInGroup->getLocation(),
15747 DiagID: diag::err_decomp_decl_not_alone)
15748 << FirstDeclaratorInGroup->getSourceRange()
15749 << DD->getSourceRange();
15750 DiagnosedMultipleDecomps = true;
15751 }
15752
15753 // A declarator that uses 'auto' in any way other than to declare a
15754 // variable with a deduced type cannot be combined with any other
15755 // declarator in the same group.
15756 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15757 Diag(Loc: FirstNonDeducedAutoInGroup->getLocation(),
15758 DiagID: diag::err_auto_non_deduced_not_alone)
15759 << FirstNonDeducedAutoInGroup->getType()
15760 ->hasAutoForTrailingReturnType()
15761 << FirstDeclaratorInGroup->getSourceRange()
15762 << DD->getSourceRange();
15763 DiagnosedNonDeducedAuto = true;
15764 }
15765 }
15766 }
15767
15768 Decls.push_back(Elt: D);
15769 }
15770
15771 if (DeclSpec::isDeclRep(T: DS.getTypeSpecType())) {
15772 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl())) {
15773 handleTagNumbering(Tag, TagScope: S);
15774 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15775 getLangOpts().CPlusPlus)
15776 Context.addDeclaratorForUnnamedTagDecl(TD: Tag, DD: FirstDeclaratorInGroup);
15777 }
15778 }
15779
15780 return BuildDeclaratorGroup(Group: Decls);
15781}
15782
15783Sema::DeclGroupPtrTy
15784Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
15785 // C++14 [dcl.spec.auto]p7: (DR1347)
15786 // If the type that replaces the placeholder type is not the same in each
15787 // deduction, the program is ill-formed.
15788 if (Group.size() > 1) {
15789 QualType Deduced;
15790 VarDecl *DeducedDecl = nullptr;
15791 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15792 VarDecl *D = dyn_cast<VarDecl>(Val: Group[i]);
15793 if (!D || D->isInvalidDecl())
15794 break;
15795 DeducedType *DT = D->getType()->getContainedDeducedType();
15796 if (!DT || DT->getDeducedType().isNull())
15797 continue;
15798 if (Deduced.isNull()) {
15799 Deduced = DT->getDeducedType();
15800 DeducedDecl = D;
15801 } else if (!Context.hasSameType(T1: DT->getDeducedType(), T2: Deduced)) {
15802 auto *AT = dyn_cast<AutoType>(Val: DT);
15803 auto Dia = Diag(Loc: D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15804 DiagID: diag::err_auto_different_deductions)
15805 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15806 << DeducedDecl->getDeclName() << DT->getDeducedType()
15807 << D->getDeclName();
15808 if (DeducedDecl->hasInit())
15809 Dia << DeducedDecl->getInit()->getSourceRange();
15810 if (D->getInit())
15811 Dia << D->getInit()->getSourceRange();
15812 D->setInvalidDecl();
15813 break;
15814 }
15815 }
15816 }
15817
15818 ActOnDocumentableDecls(Group);
15819
15820 return DeclGroupPtrTy::make(
15821 P: DeclGroupRef::Create(C&: Context, Decls: Group.data(), NumDecls: Group.size()));
15822}
15823
15824void Sema::ActOnDocumentableDecl(Decl *D) {
15825 ActOnDocumentableDecls(Group: D);
15826}
15827
15828void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
15829 // Don't parse the comment if Doxygen diagnostics are ignored.
15830 if (Group.empty() || !Group[0])
15831 return;
15832
15833 if (!areDocumentationDiagsEnabled(Loc: Group[0]->getLocation()))
15834 return;
15835
15836 if (Group.size() >= 2) {
15837 // This is a decl group. Normally it will contain only declarations
15838 // produced from declarator list. But in case we have any definitions or
15839 // additional declaration references:
15840 // 'typedef struct S {} S;'
15841 // 'typedef struct S *S;'
15842 // 'struct S *pS;'
15843 // FinalizeDeclaratorGroup adds these as separate declarations.
15844 Decl *MaybeTagDecl = Group[0];
15845 if (MaybeTagDecl && isa<TagDecl>(Val: MaybeTagDecl)) {
15846 Group = Group.slice(N: 1);
15847 }
15848 }
15849
15850 // FIXME: We assume every Decl in the group is in the same file.
15851 // This is false when preprocessor constructs the group from decls in
15852 // different files (e. g. macros or #include).
15853 Context.attachCommentsToJustParsedDecls(Decls: Group, PP: &getPreprocessor());
15854}
15855
15856void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
15857 // Check that there are no default arguments inside the type of this
15858 // parameter.
15859 if (getLangOpts().CPlusPlus)
15860 CheckExtraCXXDefaultArguments(D);
15861
15862 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15863 if (D.getCXXScopeSpec().isSet()) {
15864 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_param_declarator)
15865 << D.getCXXScopeSpec().getRange();
15866 }
15867
15868 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15869 // simple identifier except [...irrelevant cases...].
15870 switch (D.getName().getKind()) {
15871 case UnqualifiedIdKind::IK_Identifier:
15872 break;
15873
15874 case UnqualifiedIdKind::IK_OperatorFunctionId:
15875 case UnqualifiedIdKind::IK_ConversionFunctionId:
15876 case UnqualifiedIdKind::IK_LiteralOperatorId:
15877 case UnqualifiedIdKind::IK_ConstructorName:
15878 case UnqualifiedIdKind::IK_DestructorName:
15879 case UnqualifiedIdKind::IK_ImplicitSelfParam:
15880 case UnqualifiedIdKind::IK_DeductionGuideName:
15881 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name)
15882 << GetNameForDeclarator(D).getName();
15883 break;
15884
15885 case UnqualifiedIdKind::IK_TemplateId:
15886 case UnqualifiedIdKind::IK_ConstructorTemplateId:
15887 // GetNameForDeclarator would not produce a useful name in this case.
15888 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name_template_id);
15889 break;
15890 }
15891}
15892
15893void Sema::warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D) {
15894 // This only matters in C.
15895 if (getLangOpts().CPlusPlus)
15896 return;
15897
15898 // This only matters if the declaration has a type.
15899 const auto *VD = dyn_cast<ValueDecl>(Val: D);
15900 if (!VD)
15901 return;
15902
15903 // Get the type, this only matters for tag types.
15904 QualType QT = VD->getType();
15905 const auto *TD = QT->getAsTagDecl();
15906 if (!TD)
15907 return;
15908
15909 // Check if the tag declaration is lexically declared somewhere different
15910 // from the lexical declaration of the given object, then it will be hidden
15911 // in C++ and we should warn on it.
15912 if (!TD->getLexicalParent()->LexicallyEncloses(DC: D->getLexicalDeclContext())) {
15913 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15914 Diag(Loc: D->getLocation(), DiagID: diag::warn_decl_hidden_in_cpp) << Kind;
15915 Diag(Loc: TD->getLocation(), DiagID: diag::note_declared_at);
15916 }
15917}
15918
15919static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
15920 SourceLocation ExplicitThisLoc) {
15921 if (!ExplicitThisLoc.isValid())
15922 return;
15923 assert(S.getLangOpts().CPlusPlus &&
15924 "explicit parameter in non-cplusplus mode");
15925 if (!S.getLangOpts().CPlusPlus23)
15926 S.Diag(Loc: ExplicitThisLoc, DiagID: diag::err_cxx20_deducing_this)
15927 << P->getSourceRange();
15928
15929 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15930 // parameter pack.
15931 if (P->isParameterPack()) {
15932 S.Diag(Loc: P->getBeginLoc(), DiagID: diag::err_explicit_object_parameter_pack)
15933 << P->getSourceRange();
15934 return;
15935 }
15936 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15937 if (LambdaScopeInfo *LSI = S.getCurLambda())
15938 LSI->ExplicitObjectParameter = P;
15939}
15940
15941Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15942 SourceLocation ExplicitThisLoc) {
15943 const DeclSpec &DS = D.getDeclSpec();
15944
15945 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15946 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15947 // except for the special case of a single unnamed parameter of type void
15948 // with no storage class specifier, no type qualifier, and no following
15949 // ellipsis terminator.
15950 // Clang applies the C2y rules for 'register void' in all C language modes,
15951 // same as GCC, because it's questionable what that could possibly mean.
15952
15953 // C++03 [dcl.stc]p2 also permits 'auto'.
15954 StorageClass SC = SC_None;
15955 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15956 SC = SC_Register;
15957 // In C++11, the 'register' storage class specifier is deprecated.
15958 // In C++17, it is not allowed, but we tolerate it as an extension.
15959 if (getLangOpts().CPlusPlus11) {
15960 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus17
15961 ? diag::ext_register_storage_class
15962 : diag::warn_deprecated_register)
15963 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15964 } else if (!getLangOpts().CPlusPlus &&
15965 DS.getTypeSpecType() == DeclSpec::TST_void &&
15966 D.getNumTypeObjects() == 0) {
15967 Diag(Loc: DS.getStorageClassSpecLoc(),
15968 DiagID: diag::err_invalid_storage_class_in_func_decl)
15969 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15970 D.getMutableDeclSpec().ClearStorageClassSpecs();
15971 }
15972 } else if (getLangOpts().CPlusPlus &&
15973 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
15974 SC = SC_Auto;
15975 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15976 Diag(Loc: DS.getStorageClassSpecLoc(),
15977 DiagID: diag::err_invalid_storage_class_in_func_decl);
15978 D.getMutableDeclSpec().ClearStorageClassSpecs();
15979 }
15980
15981 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15982 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID: diag::err_invalid_thread)
15983 << DeclSpec::getSpecifierName(S: TSCS);
15984 if (DS.isInlineSpecified())
15985 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
15986 << getLangOpts().CPlusPlus17;
15987 if (DS.hasConstexprSpecifier())
15988 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
15989 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15990
15991 DiagnoseFunctionSpecifiers(DS);
15992
15993 CheckFunctionOrTemplateParamDeclarator(S, D);
15994
15995 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
15996 QualType parmDeclType = TInfo->getType();
15997
15998 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15999 const IdentifierInfo *II = D.getIdentifier();
16000 if (II) {
16001 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
16002 RedeclarationKind::ForVisibleRedeclaration);
16003 LookupName(R, S);
16004 if (!R.empty()) {
16005 NamedDecl *PrevDecl = *R.begin();
16006 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
16007 // Maybe we will complain about the shadowed template parameter.
16008 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
16009 // Just pretend that we didn't see the previous declaration.
16010 PrevDecl = nullptr;
16011 }
16012 if (PrevDecl && S->isDeclScope(D: PrevDecl)) {
16013 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_param_redefinition) << II;
16014 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
16015 // Recover by removing the name
16016 II = nullptr;
16017 D.SetIdentifier(Id: nullptr, IdLoc: D.getIdentifierLoc());
16018 D.setInvalidType(true);
16019 }
16020 }
16021 }
16022
16023 // Incomplete resource arrays are not allowed as function parameters in HLSL
16024 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType()) {
16025 QualType EltTy = Context.getBaseElementType(QT: parmDeclType);
16026 // `isCompleteType` forces completion of the element type so the resource
16027 // check is valid.
16028 if (!EltTy->isDependentType() &&
16029 isCompleteType(Loc: D.getIdentifierLoc(), T: EltTy) &&
16030 parmDeclType->isHLSLResourceRecordArray()) {
16031 Diag(Loc: D.getIdentifierLoc(),
16032 DiagID: diag::err_hlsl_incomplete_resource_array_in_function_param);
16033 D.setInvalidType(true);
16034 }
16035 }
16036
16037 // Temporarily put parameter variables in the translation unit, not
16038 // the enclosing context. This prevents them from accidentally
16039 // looking like class members in C++.
16040 ParmVarDecl *New =
16041 CheckParameter(DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
16042 NameLoc: D.getIdentifierLoc(), Name: II, T: parmDeclType, TSInfo: TInfo, SC);
16043
16044 if (D.isInvalidType())
16045 New->setInvalidDecl();
16046
16047 CheckExplicitObjectParameter(S&: *this, P: New, ExplicitThisLoc);
16048
16049 assert(S->isFunctionPrototypeScope());
16050 assert(S->getFunctionPrototypeDepth() >= 1);
16051 New->setScopeInfo(scopeDepth: S->getFunctionPrototypeDepth() - 1,
16052 parameterIndex: S->getNextFunctionPrototypeIndex());
16053
16054 warnOnCTypeHiddenInCPlusPlus(D: New);
16055
16056 // Add the parameter declaration into this scope.
16057 S->AddDecl(D: New);
16058 if (II)
16059 IdResolver.AddDecl(D: New);
16060
16061 ProcessDeclAttributes(S, D: New, PD: D);
16062
16063 if (D.getDeclSpec().isModulePrivateSpecified())
16064 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_local)
16065 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16066 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
16067
16068 if (New->hasAttr<BlocksAttr>())
16069 Diag(Loc: New->getLocation(), DiagID: diag::err_block_not_allowed_on)
16070 << diag::NotAllowedBlockVarReason::NonlocalVariable;
16071
16072 New->deduceParmAddressSpace(Ctxt: Context);
16073
16074 return New;
16075}
16076
16077ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
16078 SourceLocation Loc,
16079 QualType T) {
16080 /* FIXME: setting StartLoc == Loc.
16081 Would it be worth to modify callers so as to provide proper source
16082 location for the unnamed parameters, embedding the parameter's type? */
16083 ParmVarDecl *Param = ParmVarDecl::Create(C&: Context, DC, StartLoc: Loc, IdLoc: Loc, Id: nullptr,
16084 T, TInfo: Context.getTrivialTypeSourceInfo(T, Loc),
16085 S: SC_None, DefArg: nullptr);
16086 Param->setImplicit();
16087 return Param;
16088}
16089
16090void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
16091 // Don't diagnose unused-parameter errors in template instantiations; we
16092 // will already have done so in the template itself.
16093 if (inTemplateInstantiation())
16094 return;
16095
16096 for (const ParmVarDecl *Parameter : Parameters) {
16097 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
16098 !Parameter->hasAttr<UnusedAttr>() &&
16099 !Parameter->getIdentifier()->isPlaceholder()) {
16100 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_unused_parameter)
16101 << Parameter->getDeclName();
16102 }
16103 }
16104}
16105
16106void Sema::DiagnoseSizeOfParametersAndReturnValue(
16107 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
16108 if (LangOpts.NumLargeByValueCopy == 0) // No check.
16109 return;
16110
16111 // Warn if the return value is pass-by-value and larger than the specified
16112 // threshold.
16113 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
16114 unsigned Size = Context.getTypeSizeInChars(T: ReturnTy).getQuantity();
16115 if (Size > LangOpts.NumLargeByValueCopy)
16116 Diag(Loc: D->getLocation(), DiagID: diag::warn_return_value_size) << D << Size;
16117 }
16118
16119 // Warn if any parameter is pass-by-value and larger than the specified
16120 // threshold.
16121 for (const ParmVarDecl *Parameter : Parameters) {
16122 QualType T = Parameter->getType();
16123 if (T->isDependentType() || !T.isPODType(Context))
16124 continue;
16125 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
16126 if (Size > LangOpts.NumLargeByValueCopy)
16127 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_parameter_size)
16128 << Parameter << Size;
16129 }
16130}
16131
16132ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
16133 SourceLocation NameLoc,
16134 const IdentifierInfo *Name, QualType T,
16135 TypeSourceInfo *TSInfo, StorageClass SC) {
16136 // In ARC, infer a lifetime qualifier for appropriate parameter types.
16137 if (getLangOpts().ObjCAutoRefCount &&
16138 T.getObjCLifetime() == Qualifiers::OCL_None &&
16139 T->isObjCLifetimeType()) {
16140
16141 Qualifiers::ObjCLifetime lifetime;
16142
16143 // Special cases for arrays:
16144 // - if it's const, use __unsafe_unretained
16145 // - otherwise, it's an error
16146 if (T->isArrayType()) {
16147 if (!T.isConstQualified()) {
16148 if (DelayedDiagnostics.shouldDelayDiagnostics())
16149 DelayedDiagnostics.add(
16150 diag: sema::DelayedDiagnostic::makeForbiddenType(
16151 loc: NameLoc, diagnostic: diag::err_arc_array_param_no_ownership, type: T, argument: false));
16152 else
16153 Diag(Loc: NameLoc, DiagID: diag::err_arc_array_param_no_ownership)
16154 << TSInfo->getTypeLoc().getSourceRange();
16155 }
16156 lifetime = Qualifiers::OCL_ExplicitNone;
16157 } else {
16158 lifetime = T->getObjCARCImplicitLifetime();
16159 }
16160 T = Context.getLifetimeQualifiedType(type: T, lifetime);
16161 }
16162
16163 if (getLangOpts().OpenCL) {
16164 assert(!isa<DecayedType>(T));
16165 if (T->isArrayType() && !T.hasAddressSpace()) {
16166 QualType ET = Context.getAsArrayType(T)->getElementType();
16167 if (!ET.hasAddressSpace()) {
16168 // Add the private address space to the contents of the pointer when a
16169 // pointer parameter is declared as an array and not declared.
16170 LangAS ImplAS = LangAS::opencl_private;
16171 T = Context.getAddrSpaceQualType(T, AddressSpace: ImplAS);
16172 T = QualType(Context.getAsArrayType(T), 0);
16173 }
16174 }
16175 }
16176
16177 ParmVarDecl *New = ParmVarDecl::Create(C&: Context, DC, StartLoc, IdLoc: NameLoc, Id: Name,
16178 T: Context.getAdjustedParameterType(T),
16179 TInfo: TSInfo, S: SC, DefArg: nullptr);
16180
16181 // Make a note if we created a new pack in the scope of a lambda, so that
16182 // we know that references to that pack must also be expanded within the
16183 // lambda scope.
16184 if (New->isParameterPack())
16185 if (auto *CSI = getEnclosingLambdaOrBlock())
16186 CSI->LocalPacks.push_back(Elt: New);
16187
16188 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
16189 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
16190 checkNonTrivialCUnion(QT: New->getType(), Loc: New->getLocation(),
16191 UseContext: NonTrivialCUnionContext::FunctionParam,
16192 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
16193
16194 // Parameter declarators cannot be interface types. All ObjC objects are
16195 // passed by reference.
16196 if (T->isObjCObjectType()) {
16197 SourceLocation TypeEndLoc =
16198 getLocForEndOfToken(Loc: TSInfo->getTypeLoc().getEndLoc());
16199 Diag(Loc: NameLoc,
16200 DiagID: diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
16201 << FixItHint::CreateInsertion(InsertionLoc: TypeEndLoc, Code: "*");
16202 T = Context.getObjCObjectPointerType(OIT: T);
16203 New->setType(T);
16204 }
16205
16206 // __ptrauth is forbidden on parameters.
16207 if (T.getPointerAuth()) {
16208 Diag(Loc: NameLoc, DiagID: diag::err_ptrauth_qualifier_invalid) << T << 1;
16209 New->setInvalidDecl();
16210 }
16211
16212 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
16213 // duration shall not be qualified by an address-space qualifier."
16214 // Since all parameters have automatic store duration, they can not have
16215 // an address space.
16216 if (T.getAddressSpace() != LangAS::Default &&
16217 // OpenCL allows function arguments declared to be an array of a type
16218 // to be qualified with an address space.
16219 !(getLangOpts().OpenCL &&
16220 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
16221 // WebAssembly allows reference types as parameters. Funcref in particular
16222 // lives in a different address space.
16223 !(T->isFunctionPointerType() &&
16224 T.getAddressSpace() == LangAS::wasm_funcref) &&
16225 // HLSL allows function arguments to be qualified with an address space
16226 // if the groupshared annotation is used.
16227 !(getLangOpts().HLSL &&
16228 T.getAddressSpace() == LangAS::hlsl_groupshared)) {
16229 Diag(Loc: NameLoc, DiagID: diag::err_arg_with_address_space);
16230 New->setInvalidDecl();
16231 }
16232
16233 // PPC MMA non-pointer types are not allowed as function argument types.
16234 if (Context.getTargetInfo().getTriple().isPPC64() &&
16235 PPC().CheckPPCMMAType(Type: New->getOriginalType(), TypeLoc: New->getLocation())) {
16236 New->setInvalidDecl();
16237 }
16238
16239 return New;
16240}
16241
16242void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
16243 SourceLocation LocAfterDecls) {
16244 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
16245
16246 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
16247 // in the declaration list shall have at least one declarator, those
16248 // declarators shall only declare identifiers from the identifier list, and
16249 // every identifier in the identifier list shall be declared.
16250 //
16251 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
16252 // identifiers it names shall be declared in the declaration list."
16253 //
16254 // This is why we only diagnose in C99 and later. Note, the other conditions
16255 // listed are checked elsewhere.
16256 if (!FTI.hasPrototype) {
16257 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
16258 --i;
16259 if (FTI.Params[i].Param == nullptr) {
16260 if (getLangOpts().C99) {
16261 SmallString<256> Code;
16262 llvm::raw_svector_ostream(Code)
16263 << " int " << FTI.Params[i].Ident->getName() << ";\n";
16264 Diag(Loc: FTI.Params[i].IdentLoc, DiagID: diag::ext_param_not_declared)
16265 << FTI.Params[i].Ident
16266 << FixItHint::CreateInsertion(InsertionLoc: LocAfterDecls, Code);
16267 }
16268
16269 // Implicitly declare the argument as type 'int' for lack of a better
16270 // type.
16271 AttributeFactory attrs;
16272 DeclSpec DS(attrs);
16273 const char* PrevSpec; // unused
16274 unsigned DiagID; // unused
16275 DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc: FTI.Params[i].IdentLoc, PrevSpec,
16276 DiagID, Policy: Context.getPrintingPolicy());
16277 // Use the identifier location for the type source range.
16278 DS.SetRangeStart(FTI.Params[i].IdentLoc);
16279 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
16280 Declarator ParamD(DS, ParsedAttributesView::none(),
16281 DeclaratorContext::KNRTypeList);
16282 ParamD.SetIdentifier(Id: FTI.Params[i].Ident, IdLoc: FTI.Params[i].IdentLoc);
16283 FTI.Params[i].Param = ActOnParamDeclarator(S, D&: ParamD);
16284 }
16285 }
16286 }
16287}
16288
16289Decl *
16290Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
16291 MultiTemplateParamsArg TemplateParameterLists,
16292 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
16293 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
16294 assert(D.isFunctionDeclarator() && "Not a function declarator!");
16295 Scope *ParentScope = FnBodyScope->getParent();
16296
16297 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
16298 // we define a non-templated function definition, we will create a declaration
16299 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
16300 // The base function declaration will have the equivalent of an `omp declare
16301 // variant` annotation which specifies the mangled definition as a
16302 // specialization function under the OpenMP context defined as part of the
16303 // `omp begin declare variant`.
16304 SmallVector<FunctionDecl *, 4> Bases;
16305 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
16306 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
16307 S: ParentScope, D, TemplateParameterLists, Bases);
16308
16309 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
16310 Decl *DP = HandleDeclarator(S: ParentScope, D, TemplateParamLists: TemplateParameterLists);
16311 Decl *Dcl = ActOnStartOfFunctionDef(S: FnBodyScope, D: DP, SkipBody, BodyKind);
16312
16313 if (!Bases.empty())
16314 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
16315 Bases);
16316
16317 return Dcl;
16318}
16319
16320void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
16321 Consumer.HandleInlineFunctionDefinition(D);
16322}
16323
16324static bool FindPossiblePrototype(const FunctionDecl *FD,
16325 const FunctionDecl *&PossiblePrototype) {
16326 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
16327 Prev = Prev->getPreviousDecl()) {
16328 // Ignore any declarations that occur in function or method
16329 // scope, because they aren't visible from the header.
16330 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
16331 continue;
16332
16333 PossiblePrototype = Prev;
16334 return Prev->getType()->isFunctionProtoType();
16335 }
16336 return false;
16337}
16338
16339static bool
16340ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
16341 const FunctionDecl *&PossiblePrototype) {
16342 // Don't warn about invalid declarations.
16343 if (FD->isInvalidDecl())
16344 return false;
16345
16346 // Or declarations that aren't global.
16347 if (!FD->isGlobal())
16348 return false;
16349
16350 // Don't warn about C++ member functions.
16351 if (isa<CXXMethodDecl>(Val: FD))
16352 return false;
16353
16354 // Don't warn about 'main'.
16355 if (isa<TranslationUnitDecl>(Val: FD->getDeclContext()->getRedeclContext()))
16356 if (IdentifierInfo *II = FD->getIdentifier())
16357 if (II->isStr(Str: "main") || II->isStr(Str: "efi_main"))
16358 return false;
16359
16360 if (FD->isMSVCRTEntryPoint())
16361 return false;
16362
16363 // Don't warn about inline functions.
16364 if (FD->isInlined())
16365 return false;
16366
16367 // Don't warn about function templates.
16368 if (FD->getDescribedFunctionTemplate())
16369 return false;
16370
16371 // Don't warn about function template specializations.
16372 if (FD->isFunctionTemplateSpecialization())
16373 return false;
16374
16375 // Don't warn for OpenCL kernels.
16376 if (FD->hasAttr<DeviceKernelAttr>())
16377 return false;
16378
16379 // Don't warn on explicitly deleted functions.
16380 if (FD->isDeleted())
16381 return false;
16382
16383 // Don't warn on implicitly local functions (such as having local-typed
16384 // parameters).
16385 if (!FD->isExternallyVisible())
16386 return false;
16387
16388 // If we were able to find a potential prototype, don't warn.
16389 if (FindPossiblePrototype(FD, PossiblePrototype))
16390 return false;
16391
16392 return true;
16393}
16394
16395void
16396Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
16397 const FunctionDecl *EffectiveDefinition,
16398 SkipBodyInfo *SkipBody) {
16399 const FunctionDecl *Definition = EffectiveDefinition;
16400 if (!Definition &&
16401 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16402 return;
16403
16404 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16405 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16406 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16407 // A merged copy of the same function, instantiated as a member of
16408 // the same class, is OK.
16409 if (declaresSameEntity(D1: OrigFD, D2: OrigDef) &&
16410 declaresSameEntity(D1: cast<Decl>(Val: Definition->getLexicalDeclContext()),
16411 D2: cast<Decl>(Val: FD->getLexicalDeclContext())))
16412 return;
16413 }
16414 }
16415 }
16416
16417 if (canRedefineFunction(FD: Definition, LangOpts: getLangOpts()))
16418 return;
16419
16420 // Don't emit an error when this is redefinition of a typo-corrected
16421 // definition.
16422 if (TypoCorrectedFunctionDefinitions.count(Ptr: Definition))
16423 return;
16424
16425 bool DefinitionVisible = false;
16426 if (SkipBody &&
16427 isRedefinitionAllowedFor(D: Definition, NewLoc: FD->getLocation(),
16428 Visible&: DefinitionVisible) &&
16429 (Definition->getFormalLinkage() == Linkage::Internal ||
16430 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16431 !Definition->getTemplateParameterLists().empty())) {
16432 SkipBody->ShouldSkip = true;
16433 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16434 if (!DefinitionVisible) {
16435 if (auto *TD = Definition->getDescribedFunctionTemplate())
16436 makeMergedDefinitionVisible(ND: TD);
16437 makeMergedDefinitionVisible(ND: const_cast<FunctionDecl *>(Definition));
16438 }
16439 return;
16440 }
16441
16442 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16443 Definition->getStorageClass() == SC_Extern)
16444 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition_extern_inline)
16445 << FD << getLangOpts().CPlusPlus;
16446 else
16447 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition) << FD;
16448
16449 Diag(Loc: Definition->getLocation(), DiagID: diag::note_previous_definition);
16450 FD->setInvalidDecl();
16451}
16452
16453LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
16454 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16455
16456 LambdaScopeInfo *LSI = PushLambdaScope();
16457 LSI->CallOperator = CallOperator;
16458 LSI->Lambda = LambdaClass;
16459 LSI->ReturnType = CallOperator->getReturnType();
16460 // When this function is called in situation where the context of the call
16461 // operator is not entered, we set AfterParameterList to false, so that
16462 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16463 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16464 // where we would set the CurContext to the lambda operator before
16465 // substituting into it. In this case the flag needs to be true such that
16466 // tryCaptureVariable can correctly handle potential captures thereof.
16467 LSI->AfterParameterList = CurContext == CallOperator;
16468 LSI->BeforeCompoundStatement = false;
16469
16470 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16471 // used at the point of dealing with potential captures.
16472 //
16473 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16474 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16475 // associated. (Technically, we could recover that list from their
16476 // instantiation patterns, but for now, the GLTemplateParameterList seems
16477 // unnecessary in these cases.)
16478 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16479 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16480 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16481
16482 if (LCD == LCD_None)
16483 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
16484 else if (LCD == LCD_ByCopy)
16485 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
16486 else if (LCD == LCD_ByRef)
16487 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
16488 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16489
16490 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
16491 LSI->Mutable = !CallOperator->isConst();
16492 if (CallOperator->isExplicitObjectMemberFunction())
16493 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(i: 0);
16494
16495 // Add the captures to the LSI so they can be noted as already
16496 // captured within tryCaptureVar.
16497 auto I = LambdaClass->field_begin();
16498 for (const auto &C : LambdaClass->captures()) {
16499 if (C.capturesVariable()) {
16500 ValueDecl *VD = C.getCapturedVar();
16501 if (VD->isInitCapture())
16502 CurrentInstantiationScope->InstantiatedLocal(D: VD, Inst: VD);
16503 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16504 LSI->addCapture(Var: VD, /*IsBlock*/isBlock: false, isByref: ByRef,
16505 /*RefersToEnclosingVariableOrCapture*/isNested: true, Loc: C.getLocation(),
16506 /*EllipsisLoc*/C.isPackExpansion()
16507 ? C.getEllipsisLoc() : SourceLocation(),
16508 CaptureType: I->getType(), /*Invalid*/false);
16509
16510 } else if (C.capturesThis()) {
16511 LSI->addThisCapture(/*Nested*/ isNested: false, Loc: C.getLocation(), CaptureType: I->getType(),
16512 ByCopy: C.getCaptureKind() == LCK_StarThis);
16513 } else {
16514 LSI->addVLATypeCapture(Loc: C.getLocation(), VLAType: I->getCapturedVLAType(),
16515 CaptureType: I->getType());
16516 }
16517 ++I;
16518 }
16519 return LSI;
16520}
16521
16522Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
16523 SkipBodyInfo *SkipBody,
16524 FnBodyKind BodyKind) {
16525 if (!D) {
16526 // Parsing the function declaration failed in some way. Push on a fake scope
16527 // anyway so we can try to parse the function body.
16528 PushFunctionScope();
16529 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16530 return D;
16531 }
16532
16533 FunctionDecl *FD = nullptr;
16534
16535 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D))
16536 FD = FunTmpl->getTemplatedDecl();
16537 else
16538 FD = cast<FunctionDecl>(Val: D);
16539
16540 // Do not push if it is a lambda because one is already pushed when building
16541 // the lambda in ActOnStartOfLambdaDefinition().
16542 if (!isLambdaCallOperator(DC: FD))
16543 PushExpressionEvaluationContextForFunction(NewContext: ExprEvalContexts.back().Context,
16544 FD);
16545
16546 // Check for defining attributes before the check for redefinition.
16547 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16548 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 0;
16549 FD->dropAttr<AliasAttr>();
16550 FD->setInvalidDecl();
16551 }
16552 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16553 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 1;
16554 FD->dropAttr<IFuncAttr>();
16555 FD->setInvalidDecl();
16556 }
16557 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16558 if (Context.getTargetInfo().getTriple().isAArch64() &&
16559 !Context.getTargetInfo().hasFeature(Feature: "fmv") &&
16560 !Attr->isDefaultVersion()) {
16561 // If function multi versioning disabled skip parsing function body
16562 // defined with non-default target_version attribute
16563 if (SkipBody)
16564 SkipBody->ShouldSkip = true;
16565 return nullptr;
16566 }
16567 }
16568
16569 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
16570 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16571 Ctor->isDefaultConstructor() &&
16572 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16573 // If this is an MS ABI dllexport default constructor, instantiate any
16574 // default arguments.
16575 if (DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>())
16576 BuildCtorClosureDefaultArgs(Loc: Attr->getLocation(), Ctor);
16577 }
16578 }
16579
16580 // See if this is a redefinition. If 'will have body' (or similar) is already
16581 // set, then these checks were already performed when it was set.
16582 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16583 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
16584 CheckForFunctionRedefinition(FD, EffectiveDefinition: nullptr, SkipBody);
16585
16586 // If we're skipping the body, we're done. Don't enter the scope.
16587 if (SkipBody && SkipBody->ShouldSkip)
16588 return D;
16589 }
16590
16591 // Mark this function as "will have a body eventually". This lets users to
16592 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16593 // this function.
16594 FD->setWillHaveBody();
16595
16596 // If we are instantiating a generic lambda call operator, push
16597 // a LambdaScopeInfo onto the function stack. But use the information
16598 // that's already been calculated (ActOnLambdaExpr) to prime the current
16599 // LambdaScopeInfo.
16600 // When the template operator is being specialized, the LambdaScopeInfo,
16601 // has to be properly restored so that tryCaptureVariable doesn't try
16602 // and capture any new variables. In addition when calculating potential
16603 // captures during transformation of nested lambdas, it is necessary to
16604 // have the LSI properly restored.
16605 if (isGenericLambdaCallOperatorSpecialization(DC: FD)) {
16606 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16607 // specialized.
16608 if (FD->getTemplateSpecializationInfo()->isExplicitSpecialization()) {
16609 Diag(Loc: FD->getLocation(), DiagID: diag::err_lambda_explicit_temp_spec)
16610 << /*specialization*/ 0;
16611 CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: FD->getParent());
16612 Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here) << RD;
16613
16614 FD->setInvalidDecl();
16615 PushFunctionScope();
16616 } else {
16617 assert(inTemplateInstantiation() &&
16618 "There should be an active template instantiation on the stack "
16619 "when instantiating a generic lambda!");
16620 RebuildLambdaScopeInfo(CallOperator: cast<CXXMethodDecl>(Val: D));
16621 }
16622 } else {
16623 // Enter a new function scope
16624 PushFunctionScope();
16625 }
16626
16627 // Builtin functions cannot be defined.
16628 if (unsigned BuiltinID = FD->getBuiltinID()) {
16629 if (!Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID) &&
16630 !Context.BuiltinInfo.isPredefinedRuntimeFunction(ID: BuiltinID)) {
16631 Diag(Loc: FD->getLocation(), DiagID: diag::err_builtin_definition) << FD;
16632 FD->setInvalidDecl();
16633 }
16634 }
16635
16636 // The return type of a function definition must be complete (C99 6.9.1p3).
16637 // C++23 [dcl.fct.def.general]/p2
16638 // The type of [...] the return for a function definition
16639 // shall not be a (possibly cv-qualified) class type that is incomplete
16640 // or abstract within the function body unless the function is deleted.
16641 QualType ResultType = FD->getReturnType();
16642 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16643 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16644 (RequireCompleteType(Loc: FD->getLocation(), T: ResultType,
16645 DiagID: diag::err_func_def_incomplete_result) ||
16646 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getReturnType(),
16647 DiagID: diag::err_abstract_type_in_decl,
16648 Args: AbstractReturnType)))
16649 FD->setInvalidDecl();
16650
16651 if (FnBodyScope)
16652 PushDeclContext(S: FnBodyScope, DC: FD);
16653
16654 // Check the validity of our function parameters
16655 if (BodyKind != FnBodyKind::Delete)
16656 CheckParmsForFunctionDef(Parameters: FD->parameters(),
16657 /*CheckParameterNames=*/true);
16658
16659 // Add non-parameter declarations already in the function to the current
16660 // scope.
16661 if (FnBodyScope) {
16662 for (Decl *NPD : FD->decls()) {
16663 auto *NonParmDecl = dyn_cast<NamedDecl>(Val: NPD);
16664 if (!NonParmDecl)
16665 continue;
16666 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16667 "parameters should not be in newly created FD yet");
16668
16669 // If the decl has a name, make it accessible in the current scope.
16670 if (NonParmDecl->getDeclName())
16671 PushOnScopeChains(D: NonParmDecl, S: FnBodyScope, /*AddToContext=*/false);
16672
16673 // Similarly, dive into enums and fish their constants out, making them
16674 // accessible in this scope.
16675 if (auto *ED = dyn_cast<EnumDecl>(Val: NonParmDecl)) {
16676 for (auto *EI : ED->enumerators())
16677 PushOnScopeChains(D: EI, S: FnBodyScope, /*AddToContext=*/false);
16678 }
16679 }
16680 }
16681
16682 // Introduce our parameters into the function scope
16683 for (auto *Param : FD->parameters()) {
16684 Param->setOwningFunction(FD);
16685
16686 // If this has an identifier, add it to the scope stack.
16687 if (Param->getIdentifier() && FnBodyScope) {
16688 CheckShadow(S: FnBodyScope, D: Param);
16689
16690 PushOnScopeChains(D: Param, S: FnBodyScope);
16691 }
16692 }
16693
16694 // C++ [module.import/6]
16695 // ...
16696 // A header unit shall not contain a definition of a non-inline function or
16697 // variable whose name has external linkage.
16698 //
16699 // Deleted and Defaulted functions are implicitly inline (but the
16700 // inline state is not set at this point, so check the BodyKind explicitly).
16701 // We choose to allow weak & selectany definitions, as they are common in
16702 // headers, and have semantics similar to inline definitions which are allowed
16703 // in header units.
16704 // FIXME: Consider an alternate location for the test where the inlined()
16705 // state is complete.
16706 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16707 !FD->isInvalidDecl() && !FD->isInlined() &&
16708 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16709 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16710 !FD->isTemplateInstantiation() &&
16711 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16712 assert(FD->isThisDeclarationADefinition());
16713 Diag(Loc: FD->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
16714 FD->setInvalidDecl();
16715 }
16716
16717 // Ensure that the function's exception specification is instantiated.
16718 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16719 ResolveExceptionSpec(Loc: D->getLocation(), FPT);
16720
16721 // dllimport cannot be applied to non-inline function definitions.
16722 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16723 !FD->isTemplateInstantiation()) {
16724 assert(!FD->hasAttr<DLLExportAttr>());
16725 Diag(Loc: FD->getLocation(), DiagID: diag::err_attribute_dllimport_function_definition);
16726 FD->setInvalidDecl();
16727 return D;
16728 }
16729
16730 // Some function attributes (like OptimizeNoneAttr) need actions before
16731 // parsing body started.
16732 applyFunctionAttributesBeforeParsingBody(FD: D);
16733
16734 // We want to attach documentation to original Decl (which might be
16735 // a function template).
16736 ActOnDocumentableDecl(D);
16737 if (getCurLexicalContext()->isObjCContainer() &&
16738 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16739 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16740 Diag(Loc: FD->getLocation(), DiagID: diag::warn_function_def_in_objc_container);
16741
16742 maybeAddDeclWithEffects(D: FD);
16743
16744 if (!FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>() &&
16745 FnBodyScope) {
16746 // An implicit call expression is synthesized for functions declared with
16747 // the sycl_kernel_entry_point attribute. The call may resolve to a
16748 // function template, a member function template, or a call operator
16749 // of a variable template depending on the results of unqualified lookup
16750 // for 'sycl_kernel_launch' from the beginning of the function body.
16751 // Performing that lookup requires the stack of parsing scopes active
16752 // when the definition is parsed and is thus done here; the result is
16753 // cached in FunctionScopeInfo and used to synthesize the (possibly
16754 // unresolved) call expression after the function body has been parsed.
16755 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
16756 if (!SKEPAttr->isInvalidAttr()) {
16757 ExprResult LaunchIdExpr =
16758 SYCL().BuildSYCLKernelLaunchIdExpr(FD, KernelName: SKEPAttr->getKernelName());
16759 // Do not mark 'FD' as invalid if construction of `LaunchIDExpr` produces
16760 // an invalid result. Name lookup failure for 'sycl_kernel_launch' is
16761 // treated as an error in the definition of 'FD'; treating it as an error
16762 // of the declaration would affect overload resolution which would
16763 // potentially result in additional errors. If construction of
16764 // 'LaunchIDExpr' failed, then 'SYCLKernelLaunchIdExpr' will be assigned
16765 // a null pointer value below; that is expected.
16766 getCurFunction()->SYCLKernelLaunchIdExpr = LaunchIdExpr.get();
16767 }
16768 }
16769
16770 return D;
16771}
16772
16773void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {
16774 if (!FD || FD->isInvalidDecl())
16775 return;
16776 if (auto *TD = dyn_cast<FunctionTemplateDecl>(Val: FD))
16777 FD = TD->getTemplatedDecl();
16778 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16779 FPOptionsOverride FPO;
16780 FPO.setDisallowOptimizations();
16781 CurFPFeatures.applyChanges(FPO);
16782 FpPragmaStack.CurrentValue =
16783 CurFPFeatures.getChangesFrom(Base: FPOptions(LangOpts));
16784 }
16785}
16786
16787void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
16788 ReturnStmt **Returns = Scope->Returns.data();
16789
16790 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16791 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16792 if (!NRVOCandidate->isNRVOVariable()) {
16793 Diag(Loc: Returns[I]->getRetValue()->getExprLoc(),
16794 DiagID: diag::warn_not_eliding_copy_on_return);
16795 Returns[I]->setNRVOCandidate(nullptr);
16796 }
16797 }
16798 }
16799}
16800
16801bool Sema::canDelayFunctionBody(const Declarator &D) {
16802 // We can't delay parsing the body of a constexpr function template (yet).
16803 if (D.getDeclSpec().hasConstexprSpecifier())
16804 return false;
16805
16806 // We can't delay parsing the body of a function template with a deduced
16807 // return type (yet).
16808 if (D.getDeclSpec().hasAutoTypeSpec()) {
16809 // If the placeholder introduces a non-deduced trailing return type,
16810 // we can still delay parsing it.
16811 if (D.getNumTypeObjects()) {
16812 const auto &Outer = D.getTypeObject(i: D.getNumTypeObjects() - 1);
16813 if (Outer.Kind == DeclaratorChunk::Function &&
16814 Outer.Fun.hasTrailingReturnType()) {
16815 QualType Ty = GetTypeFromParser(Ty: Outer.Fun.getTrailingReturnType());
16816 return Ty.isNull() || !Ty->isUndeducedType();
16817 }
16818 }
16819 return false;
16820 }
16821
16822 return true;
16823}
16824
16825bool Sema::canSkipFunctionBody(Decl *D) {
16826 // We cannot skip the body of a function (or function template) which is
16827 // constexpr, since we may need to evaluate its body in order to parse the
16828 // rest of the file.
16829 // We cannot skip the body of a function with an undeduced return type,
16830 // because any callers of that function need to know the type.
16831 if (const FunctionDecl *FD = D->getAsFunction()) {
16832 if (FD->isConstexpr())
16833 return false;
16834 // We can't simply call Type::isUndeducedType here, because inside template
16835 // auto can be deduced to a dependent type, which is not considered
16836 // "undeduced".
16837 if (FD->getReturnType()->getContainedDeducedType())
16838 return false;
16839 }
16840 return Consumer.shouldSkipFunctionBody(D);
16841}
16842
16843Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
16844 if (!Decl)
16845 return nullptr;
16846 if (FunctionDecl *FD = Decl->getAsFunction())
16847 FD->setHasSkippedBody();
16848 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: Decl))
16849 MD->setHasSkippedBody();
16850 return Decl;
16851}
16852
16853/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16854/// body.
16855class ExitFunctionBodyRAII {
16856public:
16857 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16858 ~ExitFunctionBodyRAII() {
16859 if (!IsLambda)
16860 S.PopExpressionEvaluationContext();
16861 }
16862
16863private:
16864 Sema &S;
16865 bool IsLambda = false;
16866};
16867
16868static void diagnoseImplicitlyRetainedSelf(Sema &S) {
16869 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16870
16871 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16872 auto [It, Inserted] = EscapeInfo.try_emplace(Key: BD);
16873 if (!Inserted)
16874 return It->second;
16875
16876 bool R = false;
16877 const BlockDecl *CurBD = BD;
16878
16879 do {
16880 R = !CurBD->doesNotEscape();
16881 if (R)
16882 break;
16883 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16884 } while (CurBD);
16885
16886 return It->second = R;
16887 };
16888
16889 // If the location where 'self' is implicitly retained is inside a escaping
16890 // block, emit a diagnostic.
16891 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16892 S.ImplicitlyRetainedSelfLocs)
16893 if (IsOrNestedInEscapingBlock(P.second))
16894 S.Diag(Loc: P.first, DiagID: diag::warn_implicitly_retains_self)
16895 << FixItHint::CreateInsertion(InsertionLoc: P.first, Code: "self->");
16896}
16897
16898static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16899 return isa<CXXMethodDecl>(Val: FD) && FD->param_empty() &&
16900 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16901}
16902
16903bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {
16904 return methodHasName(FD, Name: "get_return_object");
16905}
16906
16907bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {
16908 return FD->isStatic() &&
16909 methodHasName(FD, Name: "get_return_object_on_allocation_failure");
16910}
16911
16912void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
16913 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
16914 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16915 return;
16916 // Allow some_promise_type::get_return_object().
16917 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
16918 return;
16919 if (!FD->hasAttr<CoroWrapperAttr>())
16920 Diag(Loc: FD->getLocation(), DiagID: diag::err_coroutine_return_type) << RD;
16921}
16922
16923Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16924 bool RetainFunctionScopeInfo) {
16925 FunctionScopeInfo *FSI = getCurFunction();
16926 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16927
16928 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16929 FD->addAttr(A: StrictFPAttr::CreateImplicit(Ctx&: Context));
16930
16931 SourceLocation AnalysisLoc;
16932 if (Body)
16933 AnalysisLoc = Body->getEndLoc();
16934 else if (FD)
16935 AnalysisLoc = FD->getEndLoc();
16936 sema::AnalysisBasedWarnings::Policy WP =
16937 AnalysisWarnings.getPolicyInEffectAt(Loc: AnalysisLoc);
16938 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16939
16940 // If we skip function body, we can't tell if a function is a coroutine.
16941 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16942 if (FSI->isCoroutine())
16943 CheckCompletedCoroutineBody(FD, Body);
16944 else
16945 CheckCoroutineWrapper(FD);
16946 }
16947
16948 // Diagnose invalid SYCL kernel entry point function declarations
16949 // and build SYCLKernelCallStmts for valid ones.
16950 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16951 SYCLKernelEntryPointAttr *SKEPAttr =
16952 FD->getAttr<SYCLKernelEntryPointAttr>();
16953 if (FD->isDefaulted()) {
16954 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16955 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16956 SKEPAttr->setInvalidAttr();
16957 } else if (FD->isDeleted()) {
16958 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16959 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16960 SKEPAttr->setInvalidAttr();
16961 } else if (FSI->isCoroutine()) {
16962 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16963 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16964 SKEPAttr->setInvalidAttr();
16965 } else if (Body && isa<CXXTryStmt>(Val: Body)) {
16966 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16967 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16968 SKEPAttr->setInvalidAttr();
16969 }
16970
16971 // Build an unresolved SYCL kernel call statement for a function template,
16972 // validate that a SYCL kernel call statement was instantiated for an
16973 // (implicit or explicit) instantiation of a function template, or otherwise
16974 // build a (resolved) SYCL kernel call statement for a non-templated
16975 // function or an explicit specialization.
16976 if (Body && !SKEPAttr->isInvalidAttr()) {
16977 StmtResult SR;
16978 if (FD->isTemplateInstantiation()) {
16979 // The function body should already be a SYCLKernelCallStmt in this
16980 // case, but might not be if there were previous errors.
16981 SR = Body;
16982 } else if (!getCurFunction()->SYCLKernelLaunchIdExpr) {
16983 // If name lookup for a template named sycl_kernel_launch failed
16984 // earlier, don't try to build a SYCL kernel call statement as that
16985 // would cause additional errors to be issued; just proceed with the
16986 // original function body.
16987 SR = Body;
16988 } else if (FD->isTemplated()) {
16989 SR = SYCL().BuildUnresolvedSYCLKernelCallStmt(
16990 Body: cast<CompoundStmt>(Val: Body), LaunchIdExpr: getCurFunction()->SYCLKernelLaunchIdExpr);
16991 } else {
16992 SR = SYCL().BuildSYCLKernelCallStmt(
16993 FD, Body: cast<CompoundStmt>(Val: Body),
16994 LaunchIdExpr: getCurFunction()->SYCLKernelLaunchIdExpr);
16995 }
16996 // If construction of the replacement body fails, just continue with the
16997 // original function body. An early error return here is not valid; the
16998 // current declaration context and function scopes must be popped before
16999 // returning.
17000 if (SR.isUsable())
17001 Body = SR.get();
17002 }
17003 }
17004
17005 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
17006 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
17007 if (FD->isDeletedAsWritten())
17008 Diag(Loc: SEAttr->getLocation(),
17009 DiagID: diag::err_sycl_external_invalid_deleted_function)
17010 << SEAttr;
17011 }
17012
17013 {
17014 // Do not call PopExpressionEvaluationContext() if it is a lambda because
17015 // one is already popped when finishing the lambda in BuildLambdaExpr().
17016 // This is meant to pop the context added in ActOnStartOfFunctionDef().
17017 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(DC: FD));
17018 if (FD) {
17019 // The function body and the DefaultedOrDeletedInfo, if present, use
17020 // the same storage; don't overwrite the latter if the former is null
17021 // (the body is initialised to null anyway, so even if the latter isn't
17022 // present, this would still be a no-op).
17023 if (Body)
17024 FD->setBody(Body);
17025 FD->setWillHaveBody(false);
17026
17027 if (getLangOpts().CPlusPlus14) {
17028 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
17029 FD->getReturnType()->isUndeducedType()) {
17030 // For a function with a deduced result type to return void,
17031 // the result type as written must be 'auto' or 'decltype(auto)',
17032 // possibly cv-qualified or constrained, but not ref-qualified.
17033 if (!FD->getReturnType()->getAs<AutoType>()) {
17034 Diag(Loc: dcl->getLocation(), DiagID: diag::err_auto_fn_no_return_but_not_auto)
17035 << FD->getReturnType();
17036 FD->setInvalidDecl();
17037 } else {
17038 // Falling off the end of the function is the same as 'return;'.
17039 Expr *Dummy = nullptr;
17040 if (DeduceFunctionTypeFromReturnExpr(
17041 FD, ReturnLoc: dcl->getLocation(), RetExpr: Dummy,
17042 AT: FD->getReturnType()->getAs<AutoType>()))
17043 FD->setInvalidDecl();
17044 }
17045 }
17046 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(DC: FD)) {
17047 // In C++11, we don't use 'auto' deduction rules for lambda call
17048 // operators because we don't support return type deduction.
17049 auto *LSI = getCurLambda();
17050 if (LSI->HasImplicitReturnType) {
17051 deduceClosureReturnType(CSI&: *LSI);
17052
17053 // C++11 [expr.prim.lambda]p4:
17054 // [...] if there are no return statements in the compound-statement
17055 // [the deduced type is] the type void
17056 QualType RetType =
17057 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
17058
17059 // Update the return type to the deduced type.
17060 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
17061 FD->setType(Context.getFunctionType(ResultTy: RetType, Args: Proto->getParamTypes(),
17062 EPI: Proto->getExtProtoInfo()));
17063 }
17064 }
17065
17066 // If the function implicitly returns zero (like 'main') or is naked,
17067 // don't complain about missing return statements.
17068 // Clang implicitly returns 0 in C89 mode, but that's considered an
17069 // extension. The check is necessary to ensure the expected extension
17070 // warning is emitted in C89 mode.
17071 if ((FD->hasImplicitReturnZero() &&
17072 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
17073 FD->hasAttr<NakedAttr>())
17074 WP.disableCheckFallThrough();
17075
17076 // MSVC permits the use of pure specifier (=0) on function definition,
17077 // defined at class scope, warn about this non-standard construct.
17078 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
17079 !FD->isOutOfLine())
17080 Diag(Loc: FD->getLocation(), DiagID: diag::ext_pure_function_definition);
17081
17082 if (!FD->isInvalidDecl()) {
17083 // Don't diagnose unused parameters of defaulted, deleted or naked
17084 // functions.
17085 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
17086 !FD->hasAttr<NakedAttr>())
17087 DiagnoseUnusedParameters(Parameters: FD->parameters());
17088 DiagnoseSizeOfParametersAndReturnValue(Parameters: FD->parameters(),
17089 ReturnTy: FD->getReturnType(), D: FD);
17090
17091 // If this is a structor, we need a vtable.
17092 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: FD))
17093 MarkVTableUsed(Loc: FD->getLocation(), Class: Constructor->getParent());
17094 else if (CXXDestructorDecl *Destructor =
17095 dyn_cast<CXXDestructorDecl>(Val: FD))
17096 MarkVTableUsed(Loc: FD->getLocation(), Class: Destructor->getParent());
17097
17098 // Try to apply the named return value optimization. We have to check
17099 // if we can do this here because lambdas keep return statements around
17100 // to deduce an implicit return type.
17101 if (FD->getReturnType()->isRecordType() &&
17102 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
17103 computeNRVO(Body, Scope: FSI);
17104 }
17105
17106 // GNU warning -Wmissing-prototypes:
17107 // Warn if a global function is defined without a previous
17108 // prototype declaration. This warning is issued even if the
17109 // definition itself provides a prototype. The aim is to detect
17110 // global functions that fail to be declared in header files.
17111 const FunctionDecl *PossiblePrototype = nullptr;
17112 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
17113 Diag(Loc: FD->getLocation(), DiagID: diag::warn_missing_prototype) << FD;
17114
17115 if (PossiblePrototype) {
17116 // We found a declaration that is not a prototype,
17117 // but that could be a zero-parameter prototype
17118 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
17119 TypeLoc TL = TI->getTypeLoc();
17120 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
17121 Diag(Loc: PossiblePrototype->getLocation(),
17122 DiagID: diag::note_declaration_not_a_prototype)
17123 << (FD->getNumParams() != 0)
17124 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
17125 InsertionLoc: FTL.getRParenLoc(), Code: "void")
17126 : FixItHint{});
17127 }
17128 } else {
17129 // Returns true if the token beginning at this Loc is `const`.
17130 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
17131 const LangOptions &LangOpts) {
17132 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
17133 if (LocInfo.first.isInvalid())
17134 return false;
17135
17136 bool Invalid = false;
17137 StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid);
17138 if (Invalid)
17139 return false;
17140
17141 if (LocInfo.second > Buffer.size())
17142 return false;
17143
17144 const char *LexStart = Buffer.data() + LocInfo.second;
17145 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
17146
17147 return StartTok.consume_front(Prefix: "const") &&
17148 (StartTok.empty() || isWhitespace(c: StartTok[0]) ||
17149 StartTok.starts_with(Prefix: "/*") || StartTok.starts_with(Prefix: "//"));
17150 };
17151
17152 auto findBeginLoc = [&]() {
17153 // If the return type has `const` qualifier, we want to insert
17154 // `static` before `const` (and not before the typename).
17155 if ((FD->getReturnType()->isAnyPointerType() &&
17156 FD->getReturnType()->getPointeeType().isConstQualified()) ||
17157 FD->getReturnType().isConstQualified()) {
17158 // But only do this if we can determine where the `const` is.
17159
17160 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
17161 getLangOpts()))
17162
17163 return FD->getBeginLoc();
17164 }
17165 return FD->getTypeSpecStartLoc();
17166 };
17167 Diag(Loc: FD->getTypeSpecStartLoc(),
17168 DiagID: diag::note_static_for_internal_linkage)
17169 << /* function */ 1
17170 << (FD->getStorageClass() == SC_None
17171 ? FixItHint::CreateInsertion(InsertionLoc: findBeginLoc(), Code: "static ")
17172 : FixItHint{});
17173 }
17174 }
17175
17176 // We might not have found a prototype because we didn't wish to warn on
17177 // the lack of a missing prototype. Try again without the checks for
17178 // whether we want to warn on the missing prototype.
17179 if (!PossiblePrototype)
17180 (void)FindPossiblePrototype(FD, PossiblePrototype);
17181
17182 // If the function being defined does not have a prototype, then we may
17183 // need to diagnose it as changing behavior in C23 because we now know
17184 // whether the function accepts arguments or not. This only handles the
17185 // case where the definition has no prototype but does have parameters
17186 // and either there is no previous potential prototype, or the previous
17187 // potential prototype also has no actual prototype. This handles cases
17188 // like:
17189 // void f(); void f(a) int a; {}
17190 // void g(a) int a; {}
17191 // See MergeFunctionDecl() for other cases of the behavior change
17192 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
17193 // type without a prototype.
17194 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
17195 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
17196 !PossiblePrototype->isImplicit()))) {
17197 // The function definition has parameters, so this will change behavior
17198 // in C23. If there is a possible prototype, it comes before the
17199 // function definition.
17200 // FIXME: The declaration may have already been diagnosed as being
17201 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
17202 // there's no way to test for the "changes behavior" condition in
17203 // SemaType.cpp when forming the declaration's function type. So, we do
17204 // this awkward dance instead.
17205 //
17206 // If we have a possible prototype and it declares a function with a
17207 // prototype, we don't want to diagnose it; if we have a possible
17208 // prototype and it has no prototype, it may have already been
17209 // diagnosed in SemaType.cpp as deprecated depending on whether
17210 // -Wstrict-prototypes is enabled. If we already warned about it being
17211 // deprecated, add a note that it also changes behavior. If we didn't
17212 // warn about it being deprecated (because the diagnostic is not
17213 // enabled), warn now that it is deprecated and changes behavior.
17214
17215 // This K&R C function definition definitely changes behavior in C23,
17216 // so diagnose it.
17217 Diag(Loc: FD->getLocation(), DiagID: diag::warn_non_prototype_changes_behavior)
17218 << /*definition*/ 1 << /* not supported in C23 */ 0;
17219
17220 // If we have a possible prototype for the function which is a user-
17221 // visible declaration, we already tested that it has no prototype.
17222 // This will change behavior in C23. This gets a warning rather than a
17223 // note because it's the same behavior-changing problem as with the
17224 // definition.
17225 if (PossiblePrototype)
17226 Diag(Loc: PossiblePrototype->getLocation(),
17227 DiagID: diag::warn_non_prototype_changes_behavior)
17228 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
17229 << /*definition*/ 1;
17230 }
17231
17232 // Warn on CPUDispatch with an actual body.
17233 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
17234 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Val: Body))
17235 if (!CmpndBody->body_empty())
17236 Diag(Loc: CmpndBody->body_front()->getBeginLoc(),
17237 DiagID: diag::warn_dispatch_body_ignored);
17238
17239 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
17240 const CXXMethodDecl *KeyFunction;
17241 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
17242 MD->isVirtual() &&
17243 (KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent())) &&
17244 MD == KeyFunction->getCanonicalDecl()) {
17245 // Update the key-function state if necessary for this ABI.
17246 if (FD->isInlined() &&
17247 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
17248 Context.setNonKeyFunction(MD);
17249
17250 // If the newly-chosen key function is already defined, then we
17251 // need to mark the vtable as used retroactively.
17252 KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent());
17253 const FunctionDecl *Definition;
17254 if (KeyFunction && KeyFunction->isDefined(Definition))
17255 MarkVTableUsed(Loc: Definition->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
17256 } else {
17257 // We just defined they key function; mark the vtable as used.
17258 MarkVTableUsed(Loc: FD->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
17259 }
17260 }
17261 }
17262
17263 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
17264 "Function parsing confused");
17265 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Val: dcl)) {
17266 assert(MD == getCurMethodDecl() && "Method parsing confused");
17267 MD->setBody(Body);
17268 if (!MD->isInvalidDecl()) {
17269 DiagnoseSizeOfParametersAndReturnValue(Parameters: MD->parameters(),
17270 ReturnTy: MD->getReturnType(), D: MD);
17271
17272 if (Body)
17273 computeNRVO(Body, Scope: FSI);
17274 }
17275 if (FSI->ObjCShouldCallSuper) {
17276 Diag(Loc: MD->getEndLoc(), DiagID: diag::warn_objc_missing_super_call)
17277 << MD->getSelector().getAsString();
17278 FSI->ObjCShouldCallSuper = false;
17279 }
17280 if (FSI->ObjCWarnForNoDesignatedInitChain) {
17281 const ObjCMethodDecl *InitMethod = nullptr;
17282 bool isDesignated =
17283 MD->isDesignatedInitializerForTheInterface(InitMethod: &InitMethod);
17284 assert(isDesignated && InitMethod);
17285 (void)isDesignated;
17286
17287 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
17288 auto IFace = MD->getClassInterface();
17289 if (!IFace)
17290 return false;
17291 auto SuperD = IFace->getSuperClass();
17292 if (!SuperD)
17293 return false;
17294 return SuperD->getIdentifier() ==
17295 ObjC().NSAPIObj->getNSClassId(K: NSAPI::ClassId_NSObject);
17296 };
17297 // Don't issue this warning for unavailable inits or direct subclasses
17298 // of NSObject.
17299 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
17300 Diag(Loc: MD->getLocation(),
17301 DiagID: diag::warn_objc_designated_init_missing_super_call);
17302 Diag(Loc: InitMethod->getLocation(),
17303 DiagID: diag::note_objc_designated_init_marked_here);
17304 }
17305 FSI->ObjCWarnForNoDesignatedInitChain = false;
17306 }
17307 if (FSI->ObjCWarnForNoInitDelegation) {
17308 // Don't issue this warning for unavailable inits.
17309 if (!MD->isUnavailable())
17310 Diag(Loc: MD->getLocation(),
17311 DiagID: diag::warn_objc_secondary_init_missing_init_call);
17312 FSI->ObjCWarnForNoInitDelegation = false;
17313 }
17314
17315 diagnoseImplicitlyRetainedSelf(S&: *this);
17316 } else {
17317 // Parsing the function declaration failed in some way. Pop the fake scope
17318 // we pushed on.
17319 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
17320 return nullptr;
17321 }
17322
17323 if (Body) {
17324 if (FSI->HasPotentialAvailabilityViolations)
17325 DiagnoseUnguardedAvailabilityViolations(FD: dcl);
17326 else if (AMDGPU().HasPotentiallyUnguardedBuiltinUsage(FD))
17327 AMDGPU().DiagnoseUnguardedBuiltinUsage(FD);
17328 }
17329
17330 assert(!FSI->ObjCShouldCallSuper &&
17331 "This should only be set for ObjC methods, which should have been "
17332 "handled in the block above.");
17333
17334 // Verify and clean out per-function state.
17335 if (Body && (!FD || !FD->isDefaulted())) {
17336 // C++ constructors that have function-try-blocks can't have return
17337 // statements in the handlers of that block. (C++ [except.handle]p14)
17338 // Verify this.
17339 if (FD && isa<CXXConstructorDecl>(Val: FD) && isa<CXXTryStmt>(Val: Body))
17340 DiagnoseReturnInConstructorExceptionHandler(TryBlock: cast<CXXTryStmt>(Val: Body));
17341
17342 // Verify that gotos and switch cases don't jump into scopes illegally.
17343 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
17344 DiagnoseInvalidJumps(Body);
17345
17346 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: dcl)) {
17347 if (!Destructor->getParent()->isDependentType())
17348 CheckDestructor(Destructor);
17349
17350 MarkBaseAndMemberDestructorsReferenced(Loc: Destructor->getLocation(),
17351 Record: Destructor->getParent());
17352 }
17353
17354 // If any errors have occurred, clear out any temporaries that may have
17355 // been leftover. This ensures that these temporaries won't be picked up
17356 // for deletion in some later function.
17357 if (hasUncompilableErrorOccurred() ||
17358 hasAnyUnrecoverableErrorsInThisFunction() ||
17359 getDiagnostics().getSuppressAllDiagnostics()) {
17360 DiscardCleanupsInEvaluationContext();
17361 }
17362 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(Val: dcl)) {
17363 // Since the body is valid, issue any analysis-based warnings that are
17364 // enabled.
17365 ActivePolicy = &WP;
17366 }
17367
17368 if (!IsInstantiation && FD &&
17369 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
17370 !FD->isInvalidDecl() &&
17371 !CheckConstexprFunctionDefinition(FD, Kind: CheckConstexprKind::Diagnose))
17372 FD->setInvalidDecl();
17373
17374 if (FD && FD->hasAttr<NakedAttr>()) {
17375 for (const Stmt *S : Body->children()) {
17376 // Allow local register variables without initializer as they don't
17377 // require prologue.
17378 bool RegisterVariables = false;
17379 if (auto *DS = dyn_cast<DeclStmt>(Val: S)) {
17380 for (const auto *Decl : DS->decls()) {
17381 if (const auto *Var = dyn_cast<VarDecl>(Val: Decl)) {
17382 RegisterVariables =
17383 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
17384 if (!RegisterVariables)
17385 break;
17386 }
17387 }
17388 }
17389 if (RegisterVariables)
17390 continue;
17391 if (!isa<AsmStmt>(Val: S) && !isa<NullStmt>(Val: S)) {
17392 Diag(Loc: S->getBeginLoc(), DiagID: diag::err_non_asm_stmt_in_naked_function);
17393 Diag(Loc: FD->getAttr<NakedAttr>()->getLocation(), DiagID: diag::note_attribute);
17394 FD->setInvalidDecl();
17395 break;
17396 }
17397 }
17398 }
17399
17400 assert(ExprCleanupObjects.size() ==
17401 ExprEvalContexts.back().NumCleanupObjects &&
17402 "Leftover temporaries in function");
17403 assert(!Cleanup.exprNeedsCleanups() &&
17404 "Unaccounted cleanups in function");
17405 assert(MaybeODRUseExprs.empty() &&
17406 "Leftover expressions for odr-use checking");
17407 }
17408 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
17409 // the declaration context below. Otherwise, we're unable to transform
17410 // 'this' expressions when transforming immediate context functions.
17411
17412 if (FD)
17413 CheckImmediateEscalatingFunctionDefinition(FD, FSI: getCurFunction());
17414
17415 if (!IsInstantiation)
17416 PopDeclContext();
17417
17418 if (!RetainFunctionScopeInfo)
17419 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
17420 // If any errors have occurred, clear out any temporaries that may have
17421 // been leftover. This ensures that these temporaries won't be picked up for
17422 // deletion in some later function.
17423 if (hasUncompilableErrorOccurred()) {
17424 DiscardCleanupsInEvaluationContext();
17425 }
17426
17427 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
17428 (LangOpts.OpenMP && !LangOpts.OpenMPSimd) ||
17429 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
17430 auto ES = getEmissionStatus(Decl: FD);
17431 if (ES == Sema::FunctionEmissionStatus::Emitted ||
17432 ES == Sema::FunctionEmissionStatus::Unknown)
17433 DeclsToCheckForDeferredDiags.insert(X: FD);
17434 }
17435
17436 if (FD && !FD->isDeleted())
17437 checkTypeSupport(Ty: FD->getType(), Loc: FD->getLocation(), D: FD);
17438
17439 return dcl;
17440}
17441
17442/// When we finish delayed parsing of an attribute, we must attach it to the
17443/// relevant Decl.
17444void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
17445 ParsedAttributes &Attrs) {
17446 // Always attach attributes to the underlying decl.
17447 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D))
17448 D = TD->getTemplatedDecl();
17449 ProcessDeclAttributeList(S, D, AttrList: Attrs);
17450 ProcessAPINotes(D);
17451
17452 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: D))
17453 if (Method->isStatic())
17454 checkThisInStaticMemberFunctionAttributes(Method);
17455}
17456
17457NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
17458 IdentifierInfo &II, Scope *S) {
17459 // It is not valid to implicitly define a function in C23.
17460 assert(LangOpts.implicitFunctionsAllowed() &&
17461 "Implicit function declarations aren't allowed in this language mode");
17462
17463 // Find the scope in which the identifier is injected and the corresponding
17464 // DeclContext.
17465 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17466 // In that case, we inject the declaration into the translation unit scope
17467 // instead.
17468 Scope *BlockScope = S;
17469 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17470 BlockScope = BlockScope->getParent();
17471
17472 // Loop until we find a DeclContext that is either a function/method or the
17473 // translation unit, which are the only two valid places to implicitly define
17474 // a function. This avoids accidentally defining the function within a tag
17475 // declaration, for example.
17476 Scope *ContextScope = BlockScope;
17477 while (!ContextScope->getEntity() ||
17478 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17479 !ContextScope->getEntity()->isTranslationUnit()))
17480 ContextScope = ContextScope->getParent();
17481 ContextRAII SavedContext(*this, ContextScope->getEntity());
17482
17483 // Before we produce a declaration for an implicitly defined
17484 // function, see whether there was a locally-scoped declaration of
17485 // this name as a function or variable. If so, use that
17486 // (non-visible) declaration, and complain about it.
17487 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(Name: &II);
17488 if (ExternCPrev) {
17489 // We still need to inject the function into the enclosing block scope so
17490 // that later (non-call) uses can see it.
17491 PushOnScopeChains(D: ExternCPrev, S: BlockScope, /*AddToContext*/false);
17492
17493 // C89 footnote 38:
17494 // If in fact it is not defined as having type "function returning int",
17495 // the behavior is undefined.
17496 if (!isa<FunctionDecl>(Val: ExternCPrev) ||
17497 !Context.typesAreCompatible(
17498 T1: cast<FunctionDecl>(Val: ExternCPrev)->getType(),
17499 T2: Context.getFunctionNoProtoType(ResultTy: Context.IntTy))) {
17500 Diag(Loc, DiagID: diag::ext_use_out_of_scope_declaration)
17501 << ExternCPrev << !getLangOpts().C99;
17502 Diag(Loc: ExternCPrev->getLocation(), DiagID: diag::note_previous_declaration);
17503 return ExternCPrev;
17504 }
17505 }
17506
17507 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17508 unsigned diag_id;
17509 if (II.getName().starts_with(Prefix: "__builtin_"))
17510 diag_id = diag::warn_builtin_unknown;
17511 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17512 else if (getLangOpts().C99)
17513 diag_id = diag::ext_implicit_function_decl_c99;
17514 else
17515 diag_id = diag::warn_implicit_function_decl;
17516
17517 TypoCorrection Corrected;
17518 // Because typo correction is expensive, only do it if the implicit
17519 // function declaration is going to be treated as an error.
17520 //
17521 // Perform the correction before issuing the main diagnostic, as some
17522 // consumers use typo-correction callbacks to enhance the main diagnostic.
17523 if (S && !ExternCPrev &&
17524 (Diags.getDiagnosticLevel(DiagID: diag_id, Loc) >= DiagnosticsEngine::Error)) {
17525 DeclFilterCCC<FunctionDecl> CCC{};
17526 Corrected = CorrectTypo(Typo: DeclarationNameInfo(&II, Loc), LookupKind: LookupOrdinaryName,
17527 S, SS: nullptr, CCC, Mode: CorrectTypoKind::NonError);
17528 }
17529
17530 Diag(Loc, DiagID: diag_id) << &II;
17531 if (Corrected) {
17532 // If the correction is going to suggest an implicitly defined function,
17533 // skip the correction as not being a particularly good idea.
17534 bool Diagnose = true;
17535 if (const auto *D = Corrected.getCorrectionDecl())
17536 Diagnose = !D->isImplicit();
17537 if (Diagnose)
17538 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::note_function_suggestion),
17539 /*ErrorRecovery*/ false);
17540 }
17541
17542 // If we found a prior declaration of this function, don't bother building
17543 // another one. We've already pushed that one into scope, so there's nothing
17544 // more to do.
17545 if (ExternCPrev)
17546 return ExternCPrev;
17547
17548 // Set a Declarator for the implicit definition: int foo();
17549 const char *Dummy;
17550 AttributeFactory attrFactory;
17551 DeclSpec DS(attrFactory);
17552 unsigned DiagID;
17553 bool Error = DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc, PrevSpec&: Dummy, DiagID,
17554 Policy: Context.getPrintingPolicy());
17555 (void)Error; // Silence warning.
17556 assert(!Error && "Error setting up implicit decl!");
17557 SourceLocation NoLoc;
17558 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
17559 D.AddTypeInfo(TI: DeclaratorChunk::getFunction(/*HasProto=*/false,
17560 /*IsAmbiguous=*/false,
17561 /*LParenLoc=*/NoLoc,
17562 /*Params=*/nullptr,
17563 /*NumParams=*/0,
17564 /*EllipsisLoc=*/NoLoc,
17565 /*RParenLoc=*/NoLoc,
17566 /*RefQualifierIsLvalueRef=*/true,
17567 /*RefQualifierLoc=*/NoLoc,
17568 /*MutableLoc=*/NoLoc, ESpecType: EST_None,
17569 /*ESpecRange=*/SourceRange(),
17570 /*Exceptions=*/nullptr,
17571 /*ExceptionRanges=*/nullptr,
17572 /*NumExceptions=*/0,
17573 /*NoexceptExpr=*/nullptr,
17574 /*ExceptionSpecTokens=*/nullptr,
17575 /*DeclsInPrototype=*/{}, LocalRangeBegin: Loc, LocalRangeEnd: Loc,
17576 TheDeclarator&: D),
17577 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
17578 D.SetIdentifier(Id: &II, IdLoc: Loc);
17579
17580 // Insert this function into the enclosing block scope.
17581 FunctionDecl *FD = cast<FunctionDecl>(Val: ActOnDeclarator(S: BlockScope, D));
17582 FD->setImplicit();
17583
17584 AddKnownFunctionAttributes(FD);
17585
17586 return FD;
17587}
17588
17589void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
17590 FunctionDecl *FD) {
17591 if (FD->isInvalidDecl())
17592 return;
17593
17594 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17595 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17596 return;
17597
17598 UnsignedOrNone AlignmentParam = std::nullopt;
17599 bool IsNothrow = false;
17600 if (!FD->isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam, IsNothrow: &IsNothrow))
17601 return;
17602
17603 // C++2a [basic.stc.dynamic.allocation]p4:
17604 // An allocation function that has a non-throwing exception specification
17605 // indicates failure by returning a null pointer value. Any other allocation
17606 // function never returns a null pointer value and indicates failure only by
17607 // throwing an exception [...]
17608 //
17609 // However, -fcheck-new invalidates this possible assumption, so don't add
17610 // NonNull when that is enabled.
17611 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17612 !getLangOpts().CheckNew)
17613 FD->addAttr(A: ReturnsNonNullAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17614
17615 // C++2a [basic.stc.dynamic.allocation]p2:
17616 // An allocation function attempts to allocate the requested amount of
17617 // storage. [...] If the request succeeds, the value returned by a
17618 // replaceable allocation function is a [...] pointer value p0 different
17619 // from any previously returned value p1 [...]
17620 //
17621 // However, this particular information is being added in codegen,
17622 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17623
17624 // C++2a [basic.stc.dynamic.allocation]p2:
17625 // An allocation function attempts to allocate the requested amount of
17626 // storage. If it is successful, it returns the address of the start of a
17627 // block of storage whose length in bytes is at least as large as the
17628 // requested size.
17629 if (!FD->hasAttr<AllocSizeAttr>()) {
17630 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17631 Ctx&: Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17632 /*NumElemsParam=*/ParamIdx(), Range: FD->getLocation()));
17633 }
17634
17635 // C++2a [basic.stc.dynamic.allocation]p3:
17636 // For an allocation function [...], the pointer returned on a successful
17637 // call shall represent the address of storage that is aligned as follows:
17638 // (3.1) If the allocation function takes an argument of type
17639 // std​::​align_­val_­t, the storage will have the alignment
17640 // specified by the value of this argument.
17641 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17642 FD->addAttr(A: AllocAlignAttr::CreateImplicit(
17643 Ctx&: Context, ParamIndex: ParamIdx(*AlignmentParam, FD), Range: FD->getLocation()));
17644 }
17645
17646 // FIXME:
17647 // C++2a [basic.stc.dynamic.allocation]p3:
17648 // For an allocation function [...], the pointer returned on a successful
17649 // call shall represent the address of storage that is aligned as follows:
17650 // (3.2) Otherwise, if the allocation function is named operator new[],
17651 // the storage is aligned for any object that does not have
17652 // new-extended alignment ([basic.align]) and is no larger than the
17653 // requested size.
17654 // (3.3) Otherwise, the storage is aligned for any object that does not
17655 // have new-extended alignment and is of the requested size.
17656}
17657
17658void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
17659 if (FD->isInvalidDecl())
17660 return;
17661
17662 // If this is a built-in function, map its builtin attributes to
17663 // actual attributes.
17664 if (unsigned BuiltinID = FD->getBuiltinID()) {
17665 // Handle printf-formatting attributes.
17666 unsigned FormatIdx;
17667 bool HasVAListArg;
17668 if (Context.BuiltinInfo.isPrintfLike(ID: BuiltinID, FormatIdx, HasVAListArg)) {
17669 if (!FD->hasAttr<FormatAttr>()) {
17670 const char *fmt = "printf";
17671 unsigned int NumParams = FD->getNumParams();
17672 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17673 FD->getParamDecl(i: FormatIdx)->getType()->isObjCObjectPointerType())
17674 fmt = "NSString";
17675 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17676 Type: &Context.Idents.get(Name: fmt),
17677 FormatIdx: FormatIdx+1,
17678 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17679 Range: FD->getLocation()));
17680 }
17681 }
17682 if (Context.BuiltinInfo.isScanfLike(ID: BuiltinID, FormatIdx,
17683 HasVAListArg)) {
17684 if (!FD->hasAttr<FormatAttr>())
17685 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17686 Type: &Context.Idents.get(Name: "scanf"),
17687 FormatIdx: FormatIdx+1,
17688 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17689 Range: FD->getLocation()));
17690 }
17691
17692 // Handle automatically recognized callbacks.
17693 SmallVector<int, 4> Encoding;
17694 if (!FD->hasAttr<CallbackAttr>() &&
17695 Context.BuiltinInfo.performsCallback(ID: BuiltinID, Encoding))
17696 FD->addAttr(A: CallbackAttr::CreateImplicit(
17697 Ctx&: Context, Encoding: Encoding.data(), EncodingSize: Encoding.size(), Range: FD->getLocation()));
17698
17699 // Mark const if we don't care about errno and/or floating point exceptions
17700 // that are the only thing preventing the function from being const. This
17701 // allows IRgen to use LLVM intrinsics for such functions.
17702 bool NoExceptions =
17703 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
17704 bool ConstWithoutErrnoAndExceptions =
17705 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(ID: BuiltinID);
17706 bool ConstWithoutExceptions =
17707 Context.BuiltinInfo.isConstWithoutExceptions(ID: BuiltinID);
17708 if (!FD->hasAttr<ConstAttr>() &&
17709 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17710 (!ConstWithoutErrnoAndExceptions ||
17711 (!getLangOpts().MathErrno && NoExceptions)) &&
17712 (!ConstWithoutExceptions || NoExceptions))
17713 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17714
17715 // We make "fma" on GNU or Windows const because we know it does not set
17716 // errno in those environments even though it could set errno based on the
17717 // C standard.
17718 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17719 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17720 !FD->hasAttr<ConstAttr>()) {
17721 switch (BuiltinID) {
17722 case Builtin::BI__builtin_fma:
17723 case Builtin::BI__builtin_fmaf:
17724 case Builtin::BI__builtin_fmal:
17725 case Builtin::BIfma:
17726 case Builtin::BIfmaf:
17727 case Builtin::BIfmal:
17728 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17729 break;
17730 default:
17731 break;
17732 }
17733 }
17734
17735 SmallVector<int, 4> Indxs;
17736 Builtin::Info::NonNullMode OptMode;
17737 if (Context.BuiltinInfo.isNonNull(ID: BuiltinID, Indxs, Mode&: OptMode) &&
17738 !FD->hasAttr<NonNullAttr>()) {
17739 if (OptMode == Builtin::Info::NonNullMode::NonOptimizing) {
17740 for (int I : Indxs) {
17741 ParmVarDecl *PVD = FD->getParamDecl(i: I);
17742 QualType T = PVD->getType();
17743 T = Context.getAttributedType(attrKind: attr::TypeNonNull, modifiedType: T, equivalentType: T);
17744 PVD->setType(T);
17745 }
17746 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17747 llvm::SmallVector<ParamIdx, 4> ParamIndxs;
17748 for (int I : Indxs)
17749 ParamIndxs.push_back(Elt: ParamIdx(I + 1, FD));
17750 FD->addAttr(A: NonNullAttr::CreateImplicit(Ctx&: Context, Args: ParamIndxs.data(),
17751 ArgsSize: ParamIndxs.size()));
17752 }
17753 }
17754 if (Context.BuiltinInfo.isReturnsTwice(ID: BuiltinID) &&
17755 !FD->hasAttr<ReturnsTwiceAttr>())
17756 FD->addAttr(A: ReturnsTwiceAttr::CreateImplicit(Ctx&: Context,
17757 Range: FD->getLocation()));
17758 if (Context.BuiltinInfo.isNoThrow(ID: BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17759 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17760 if (Context.BuiltinInfo.isPure(ID: BuiltinID) && !FD->hasAttr<PureAttr>())
17761 FD->addAttr(A: PureAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17762 if (Context.BuiltinInfo.isConst(ID: BuiltinID) && !FD->hasAttr<ConstAttr>())
17763 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17764 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID) &&
17765 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17766 // Add the appropriate attribute, depending on the CUDA compilation mode
17767 // and which target the builtin belongs to. For example, during host
17768 // compilation, aux builtins are __device__, while the rest are __host__.
17769 if (getLangOpts().CUDAIsDevice !=
17770 Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID))
17771 FD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17772 else
17773 FD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17774 }
17775
17776 // Add known guaranteed alignment for allocation functions.
17777 switch (BuiltinID) {
17778 case Builtin::BImemalign:
17779 case Builtin::BIaligned_alloc:
17780 if (!FD->hasAttr<AllocAlignAttr>())
17781 FD->addAttr(A: AllocAlignAttr::CreateImplicit(Ctx&: Context, ParamIndex: ParamIdx(1, FD),
17782 Range: FD->getLocation()));
17783 break;
17784 default:
17785 break;
17786 }
17787
17788 // Add allocsize attribute for allocation functions.
17789 switch (BuiltinID) {
17790 case Builtin::BIcalloc:
17791 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17792 Ctx&: Context, ElemSizeParam: ParamIdx(1, FD), NumElemsParam: ParamIdx(2, FD), Range: FD->getLocation()));
17793 break;
17794 case Builtin::BImemalign:
17795 case Builtin::BIaligned_alloc:
17796 case Builtin::BIrealloc:
17797 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(2, FD),
17798 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17799 break;
17800 case Builtin::BImalloc:
17801 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(1, FD),
17802 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17803 break;
17804 default:
17805 break;
17806 }
17807 }
17808
17809 LazyProcessLifetimeCaptureByParams(FD);
17810 inferLifetimeBoundAttribute(FD);
17811 inferLifetimeCaptureByAttribute(FD);
17812 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
17813
17814 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17815 // throw, add an implicit nothrow attribute to any extern "C" function we come
17816 // across.
17817 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17818 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17819 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17820 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17821 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17822 }
17823
17824 IdentifierInfo *Name = FD->getIdentifier();
17825 if (!Name)
17826 return;
17827 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
17828 (isa<LinkageSpecDecl>(Val: FD->getDeclContext()) &&
17829 cast<LinkageSpecDecl>(Val: FD->getDeclContext())->getLanguage() ==
17830 LinkageSpecLanguageIDs::C)) {
17831 // Okay: this could be a libc/libm/Objective-C function we know
17832 // about.
17833 } else
17834 return;
17835
17836 if (Name->isStr(Str: "asprintf") || Name->isStr(Str: "vasprintf")) {
17837 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17838 // target-specific builtins, perhaps?
17839 if (!FD->hasAttr<FormatAttr>())
17840 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17841 Type: &Context.Idents.get(Name: "printf"), FormatIdx: 2,
17842 FirstArg: Name->isStr(Str: "vasprintf") ? 0 : 3,
17843 Range: FD->getLocation()));
17844 }
17845
17846 if (Name->isStr(Str: "__CFStringMakeConstantString")) {
17847 // We already have a __builtin___CFStringMakeConstantString,
17848 // but builds that use -fno-constant-cfstrings don't go through that.
17849 if (!FD->hasAttr<FormatArgAttr>())
17850 FD->addAttr(A: FormatArgAttr::CreateImplicit(Ctx&: Context, FormatIdx: ParamIdx(1, FD),
17851 Range: FD->getLocation()));
17852 }
17853}
17854
17855TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
17856 TypeSourceInfo *TInfo) {
17857 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17858 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17859
17860 if (!TInfo) {
17861 assert(D.isInvalidType() && "no declarator info for valid type");
17862 TInfo = Context.getTrivialTypeSourceInfo(T);
17863 }
17864
17865 // Scope manipulation handled by caller.
17866 TypedefDecl *NewTD =
17867 TypedefDecl::Create(C&: Context, DC: CurContext, StartLoc: D.getBeginLoc(),
17868 IdLoc: D.getIdentifierLoc(), Id: D.getIdentifier(), TInfo);
17869
17870 // Bail out immediately if we have an invalid declaration.
17871 if (D.isInvalidType()) {
17872 NewTD->setInvalidDecl();
17873 return NewTD;
17874 }
17875
17876 if (D.getDeclSpec().isModulePrivateSpecified()) {
17877 if (CurContext->isFunctionOrMethod())
17878 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_module_private_local)
17879 << 2 << NewTD
17880 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
17881 << FixItHint::CreateRemoval(
17882 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
17883 else
17884 NewTD->setModulePrivate();
17885 }
17886
17887 // C++ [dcl.typedef]p8:
17888 // If the typedef declaration defines an unnamed class (or
17889 // enum), the first typedef-name declared by the declaration
17890 // to be that class type (or enum type) is used to denote the
17891 // class type (or enum type) for linkage purposes only.
17892 // We need to check whether the type was declared in the declaration.
17893 switch (D.getDeclSpec().getTypeSpecType()) {
17894 case TST_enum:
17895 case TST_struct:
17896 case TST_interface:
17897 case TST_union:
17898 case TST_class: {
17899 TagDecl *tagFromDeclSpec = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
17900 setTagNameForLinkagePurposes(TagFromDeclSpec: tagFromDeclSpec, NewTD);
17901 break;
17902 }
17903
17904 default:
17905 break;
17906 }
17907
17908 return NewTD;
17909}
17910
17911bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
17912 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17913 QualType T = TI->getType();
17914
17915 if (T->isDependentType())
17916 return false;
17917
17918 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17919 // integral type; any cv-qualification is ignored.
17920 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17921 // non-atomic version of the type specified by the type specifiers in the
17922 // specifier qualifier list.
17923 // Because of how odd C's rule is, we'll let the user know that operations
17924 // involving the enumeration type will be non-atomic.
17925 if (T->isAtomicType())
17926 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_atomic_stripped_in_enum);
17927
17928 Qualifiers Q = T.getQualifiers();
17929 std::optional<unsigned> QualSelect;
17930 if (Q.hasConst() && Q.hasVolatile())
17931 QualSelect = diag::CVQualList::Both;
17932 else if (Q.hasConst())
17933 QualSelect = diag::CVQualList::Const;
17934 else if (Q.hasVolatile())
17935 QualSelect = diag::CVQualList::Volatile;
17936
17937 if (QualSelect)
17938 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_cv_stripped_in_enum) << *QualSelect;
17939
17940 T = T.getAtomicUnqualifiedType();
17941
17942 // This doesn't use 'isIntegralType' despite the error message mentioning
17943 // integral type because isIntegralType would also allow enum types in C.
17944 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17945 if (BT->isInteger())
17946 return false;
17947
17948 return Diag(Loc: UnderlyingLoc, DiagID: diag::err_enum_invalid_underlying)
17949 << T << T->isBitIntType();
17950}
17951
17952bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
17953 QualType EnumUnderlyingTy, bool IsFixed,
17954 const EnumDecl *Prev) {
17955 if (IsScoped != Prev->isScoped()) {
17956 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_scoped_mismatch)
17957 << Prev->isScoped();
17958 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17959 return true;
17960 }
17961
17962 if (IsFixed && Prev->isFixed()) {
17963 if (!EnumUnderlyingTy->isDependentType() &&
17964 !Prev->getIntegerType()->isDependentType() &&
17965 !Context.hasSameUnqualifiedType(T1: EnumUnderlyingTy,
17966 T2: Prev->getIntegerType())) {
17967 // TODO: Highlight the underlying type of the redeclaration.
17968 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_type_mismatch)
17969 << EnumUnderlyingTy << Prev->getIntegerType();
17970 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration)
17971 << Prev->getIntegerTypeRange();
17972 return true;
17973 }
17974 } else if (IsFixed != Prev->isFixed()) {
17975 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_fixed_mismatch)
17976 << Prev->isFixed();
17977 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17978 return true;
17979 }
17980
17981 return false;
17982}
17983
17984/// Get diagnostic %select index for tag kind for
17985/// redeclaration diagnostic message.
17986/// WARNING: Indexes apply to particular diagnostics only!
17987///
17988/// \returns diagnostic %select index.
17989static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
17990 switch (Tag) {
17991 case TagTypeKind::Struct:
17992 return 0;
17993 case TagTypeKind::Interface:
17994 return 1;
17995 case TagTypeKind::Class:
17996 return 2;
17997 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17998 }
17999}
18000
18001/// Determine if tag kind is a class-key compatible with
18002/// class for redeclaration (class, struct, or __interface).
18003///
18004/// \returns true iff the tag kind is compatible.
18005static bool isClassCompatTagKind(TagTypeKind Tag)
18006{
18007 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
18008 Tag == TagTypeKind::Interface;
18009}
18010
18011NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, TagTypeKind TTK) {
18012 if (isa<TypedefDecl>(Val: PrevDecl))
18013 return NonTagKind::Typedef;
18014 else if (isa<TypeAliasDecl>(Val: PrevDecl))
18015 return NonTagKind::TypeAlias;
18016 else if (isa<ClassTemplateDecl>(Val: PrevDecl))
18017 return NonTagKind::Template;
18018 else if (isa<TypeAliasTemplateDecl>(Val: PrevDecl))
18019 return NonTagKind::TypeAliasTemplate;
18020 else if (isa<TemplateTemplateParmDecl>(Val: PrevDecl))
18021 return NonTagKind::TemplateTemplateArgument;
18022 switch (TTK) {
18023 case TagTypeKind::Struct:
18024 case TagTypeKind::Interface:
18025 case TagTypeKind::Class:
18026 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
18027 : NonTagKind::NonStruct;
18028 case TagTypeKind::Union:
18029 return NonTagKind::NonUnion;
18030 case TagTypeKind::Enum:
18031 return NonTagKind::NonEnum;
18032 }
18033 llvm_unreachable("invalid TTK");
18034}
18035
18036bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
18037 TagTypeKind NewTag, bool isDefinition,
18038 SourceLocation NewTagLoc,
18039 const IdentifierInfo *Name) {
18040 // C++ [dcl.type.elab]p3:
18041 // The class-key or enum keyword present in the
18042 // elaborated-type-specifier shall agree in kind with the
18043 // declaration to which the name in the elaborated-type-specifier
18044 // refers. This rule also applies to the form of
18045 // elaborated-type-specifier that declares a class-name or
18046 // friend class since it can be construed as referring to the
18047 // definition of the class. Thus, in any
18048 // elaborated-type-specifier, the enum keyword shall be used to
18049 // refer to an enumeration (7.2), the union class-key shall be
18050 // used to refer to a union (clause 9), and either the class or
18051 // struct class-key shall be used to refer to a class (clause 9)
18052 // declared using the class or struct class-key.
18053 TagTypeKind OldTag = Previous->getTagKind();
18054 if (OldTag != NewTag &&
18055 !(isClassCompatTagKind(Tag: OldTag) && isClassCompatTagKind(Tag: NewTag)))
18056 return false;
18057
18058 // Tags are compatible, but we might still want to warn on mismatched tags.
18059 // Non-class tags can't be mismatched at this point.
18060 if (!isClassCompatTagKind(Tag: NewTag))
18061 return true;
18062
18063 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
18064 // by our warning analysis. We don't want to warn about mismatches with (eg)
18065 // declarations in system headers that are designed to be specialized, but if
18066 // a user asks us to warn, we should warn if their code contains mismatched
18067 // declarations.
18068 auto IsIgnoredLoc = [&](SourceLocation Loc) {
18069 return getDiagnostics().isIgnored(DiagID: diag::warn_struct_class_tag_mismatch,
18070 Loc);
18071 };
18072 if (IsIgnoredLoc(NewTagLoc))
18073 return true;
18074
18075 auto IsIgnored = [&](const TagDecl *Tag) {
18076 return IsIgnoredLoc(Tag->getLocation());
18077 };
18078 while (IsIgnored(Previous)) {
18079 Previous = Previous->getPreviousDecl();
18080 if (!Previous)
18081 return true;
18082 OldTag = Previous->getTagKind();
18083 }
18084
18085 bool isTemplate = false;
18086 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Previous))
18087 isTemplate = Record->getDescribedClassTemplate();
18088
18089 if (inTemplateInstantiation()) {
18090 if (OldTag != NewTag) {
18091 // In a template instantiation, do not offer fix-its for tag mismatches
18092 // since they usually mess up the template instead of fixing the problem.
18093 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
18094 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
18095 << getRedeclDiagFromTagKind(Tag: OldTag);
18096 // FIXME: Note previous location?
18097 }
18098 return true;
18099 }
18100
18101 if (isDefinition) {
18102 // On definitions, check all previous tags and issue a fix-it for each
18103 // one that doesn't match the current tag.
18104 if (Previous->getDefinition()) {
18105 // Don't suggest fix-its for redefinitions.
18106 return true;
18107 }
18108
18109 bool previousMismatch = false;
18110 for (const TagDecl *I : Previous->redecls()) {
18111 if (I->getTagKind() != NewTag) {
18112 // Ignore previous declarations for which the warning was disabled.
18113 if (IsIgnored(I))
18114 continue;
18115
18116 if (!previousMismatch) {
18117 previousMismatch = true;
18118 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_previous_tag_mismatch)
18119 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
18120 << getRedeclDiagFromTagKind(Tag: I->getTagKind());
18121 }
18122 Diag(Loc: I->getInnerLocStart(), DiagID: diag::note_struct_class_suggestion)
18123 << getRedeclDiagFromTagKind(Tag: NewTag)
18124 << FixItHint::CreateReplacement(RemoveRange: I->getInnerLocStart(),
18125 Code: TypeWithKeyword::getTagTypeKindName(Kind: NewTag));
18126 }
18127 }
18128 return true;
18129 }
18130
18131 // Identify the prevailing tag kind: this is the kind of the definition (if
18132 // there is a non-ignored definition), or otherwise the kind of the prior
18133 // (non-ignored) declaration.
18134 const TagDecl *PrevDef = Previous->getDefinition();
18135 if (PrevDef && IsIgnored(PrevDef))
18136 PrevDef = nullptr;
18137 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
18138 if (Redecl->getTagKind() != NewTag) {
18139 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
18140 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
18141 << getRedeclDiagFromTagKind(Tag: OldTag);
18142 Diag(Loc: Redecl->getLocation(), DiagID: diag::note_previous_use);
18143
18144 // If there is a previous definition, suggest a fix-it.
18145 if (PrevDef) {
18146 Diag(Loc: NewTagLoc, DiagID: diag::note_struct_class_suggestion)
18147 << getRedeclDiagFromTagKind(Tag: Redecl->getTagKind())
18148 << FixItHint::CreateReplacement(RemoveRange: SourceRange(NewTagLoc),
18149 Code: TypeWithKeyword::getTagTypeKindName(Kind: Redecl->getTagKind()));
18150 }
18151 }
18152
18153 return true;
18154}
18155
18156/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
18157/// from an outer enclosing namespace or file scope inside a friend declaration.
18158/// This should provide the commented out code in the following snippet:
18159/// namespace N {
18160/// struct X;
18161/// namespace M {
18162/// struct Y { friend struct /*N::*/ X; };
18163/// }
18164/// }
18165static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
18166 SourceLocation NameLoc) {
18167 // While the decl is in a namespace, do repeated lookup of that name and see
18168 // if we get the same namespace back. If we do not, continue until
18169 // translation unit scope, at which point we have a fully qualified NNS.
18170 SmallVector<IdentifierInfo *, 4> Namespaces;
18171 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
18172 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
18173 // This tag should be declared in a namespace, which can only be enclosed by
18174 // other namespaces. Bail if there's an anonymous namespace in the chain.
18175 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: DC);
18176 if (!Namespace || Namespace->isAnonymousNamespace())
18177 return FixItHint();
18178 IdentifierInfo *II = Namespace->getIdentifier();
18179 Namespaces.push_back(Elt: II);
18180 NamedDecl *Lookup = SemaRef.LookupSingleName(
18181 S, Name: II, Loc: NameLoc, NameKind: Sema::LookupNestedNameSpecifierName);
18182 if (Lookup == Namespace)
18183 break;
18184 }
18185
18186 // Once we have all the namespaces, reverse them to go outermost first, and
18187 // build an NNS.
18188 SmallString<64> Insertion;
18189 llvm::raw_svector_ostream OS(Insertion);
18190 if (DC->isTranslationUnit())
18191 OS << "::";
18192 std::reverse(first: Namespaces.begin(), last: Namespaces.end());
18193 for (auto *II : Namespaces)
18194 OS << II->getName() << "::";
18195 return FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: Insertion);
18196}
18197
18198/// Determine whether a tag originally declared in context \p OldDC can
18199/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
18200/// found a declaration in \p OldDC as a previous decl, perhaps through a
18201/// using-declaration).
18202static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
18203 DeclContext *NewDC) {
18204 OldDC = OldDC->getRedeclContext();
18205 NewDC = NewDC->getRedeclContext();
18206
18207 if (OldDC->Equals(DC: NewDC))
18208 return true;
18209
18210 // In MSVC mode, we allow a redeclaration if the contexts are related (either
18211 // encloses the other).
18212 if (S.getLangOpts().MSVCCompat &&
18213 (OldDC->Encloses(DC: NewDC) || NewDC->Encloses(DC: OldDC)))
18214 return true;
18215
18216 return false;
18217}
18218
18219DeclResult
18220Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
18221 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18222 const ParsedAttributesView &Attrs, AccessSpecifier AS,
18223 SourceLocation ModulePrivateLoc,
18224 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
18225 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
18226 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
18227 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
18228 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
18229 // If this is not a definition, it must have a name.
18230 IdentifierInfo *OrigName = Name;
18231 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
18232 "Nameless record must be a definition!");
18233 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
18234
18235 OwnedDecl = false;
18236 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
18237 bool ScopedEnum = ScopedEnumKWLoc.isValid();
18238
18239 // FIXME: Check member specializations more carefully.
18240 bool isMemberSpecialization = false;
18241 bool IsInjectedClassName = false;
18242 bool Invalid = false;
18243
18244 // We only need to do this matching if we have template parameters
18245 // or a scope specifier, which also conveniently avoids this work
18246 // for non-C++ cases.
18247 if (TemplateParameterLists.size() > 0 ||
18248 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
18249 TemplateParameterList *TemplateParams =
18250 MatchTemplateParametersToScopeSpecifier(
18251 DeclStartLoc: KWLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TemplateParameterLists,
18252 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
18253
18254 // C++23 [dcl.type.elab] p2:
18255 // If an elaborated-type-specifier is the sole constituent of a
18256 // declaration, the declaration is ill-formed unless it is an explicit
18257 // specialization, an explicit instantiation or it has one of the
18258 // following forms: [...]
18259 // C++23 [dcl.enum] p1:
18260 // If the enum-head-name of an opaque-enum-declaration contains a
18261 // nested-name-specifier, the declaration shall be an explicit
18262 // specialization.
18263 //
18264 // FIXME: Class template partial specializations can be forward declared
18265 // per CWG2213, but the resolution failed to allow qualified forward
18266 // declarations. This is almost certainly unintentional, so we allow them.
18267 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
18268 !isMemberSpecialization)
18269 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_standalone_class_nested_name_specifier)
18270 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();
18271
18272 if (TemplateParams) {
18273 if (Kind == TagTypeKind::Enum) {
18274 Diag(Loc: KWLoc, DiagID: diag::err_enum_template);
18275 return true;
18276 }
18277
18278 if (TemplateParams->size() > 0) {
18279 // This is a declaration or definition of a class template (which may
18280 // be a member of another template).
18281
18282 if (Invalid)
18283 return true;
18284
18285 OwnedDecl = false;
18286 DeclResult Result = CheckClassTemplate(
18287 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attr: Attrs, TemplateParams,
18288 AS, ModulePrivateLoc,
18289 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
18290 OuterTemplateParamLists: TemplateParameterLists.data(), IsMemberSpecialization: isMemberSpecialization, SkipBody);
18291 return Result.get();
18292 } else {
18293 // The "template<>" header is extraneous.
18294 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
18295 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18296 isMemberSpecialization = true;
18297 }
18298 }
18299
18300 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
18301 CheckTemplateDeclScope(S, TemplateParams: TemplateParameterLists.back()))
18302 return true;
18303 }
18304
18305 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
18306 // C++23 [dcl.type.elab]p4:
18307 // If an elaborated-type-specifier appears with the friend specifier as
18308 // an entire member-declaration, the member-declaration shall have one
18309 // of the following forms:
18310 // friend class-key nested-name-specifier(opt) identifier ;
18311 // friend class-key simple-template-id ;
18312 // friend class-key nested-name-specifier template(opt)
18313 // simple-template-id ;
18314 //
18315 // Since enum is not a class-key, so declarations like "friend enum E;"
18316 // are ill-formed. Although CWG2363 reaffirms that such declarations are
18317 // invalid, most implementations accept so we issue a pedantic warning.
18318 Diag(Loc: KWLoc, DiagID: diag::ext_enum_friend) << FixItHint::CreateRemoval(
18319 RemoveRange: ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
18320 assert(ScopedEnum || !ScopedEnumUsesClassTag);
18321 Diag(Loc: KWLoc, DiagID: diag::note_enum_friend)
18322 << (ScopedEnum + ScopedEnumUsesClassTag);
18323 }
18324
18325 // Figure out the underlying type if this a enum declaration. We need to do
18326 // this early, because it's needed to detect if this is an incompatible
18327 // redeclaration.
18328 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
18329 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
18330
18331 if (Kind == TagTypeKind::Enum) {
18332 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum) ||
18333 Invalid) {
18334 // No underlying type explicitly specified, or we failed to parse the
18335 // type, default to int.
18336 EnumUnderlying = Context.IntTy.getTypePtr();
18337 } else if (UnderlyingType.get()) {
18338 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
18339 // integral type; any cv-qualification is ignored.
18340 // C23 6.7.3.3p5: The underlying type of the enumeration is the
18341 // unqualified, non-atomic version of the type specified by the type
18342 // specifiers in the specifier qualifier list.
18343 TypeSourceInfo *TI = nullptr;
18344 GetTypeFromParser(Ty: UnderlyingType.get(), TInfo: &TI);
18345 EnumUnderlying = TI;
18346
18347 if (CheckEnumUnderlyingType(TI))
18348 // Recover by falling back to int.
18349 EnumUnderlying = Context.IntTy.getTypePtr();
18350
18351 if (DiagnoseUnexpandedParameterPack(Loc: TI->getTypeLoc().getBeginLoc(), T: TI,
18352 UPPC: UPPC_FixedUnderlyingType))
18353 EnumUnderlying = Context.IntTy.getTypePtr();
18354
18355 // If the underlying type is atomic, we need to adjust the type before
18356 // continuing. This only happens in the case we stored a TypeSourceInfo
18357 // into EnumUnderlying because the other cases are error recovery up to
18358 // this point. But because it's not possible to gin up a TypeSourceInfo
18359 // for a non-atomic type from an atomic one, we'll store into the Type
18360 // field instead. FIXME: it would be nice to have an easy way to get a
18361 // derived TypeSourceInfo which strips qualifiers including the weird
18362 // ones like _Atomic where it forms a different type.
18363 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying);
18364 TI && TI->getType()->isAtomicType())
18365 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
18366
18367 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
18368 // For MSVC ABI compatibility, unfixed enums must use an underlying type
18369 // of 'int'. However, if this is an unfixed forward declaration, don't set
18370 // the underlying type unless the user enables -fms-compatibility. This
18371 // makes unfixed forward declared enums incomplete and is more conforming.
18372 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
18373 EnumUnderlying = Context.IntTy.getTypePtr();
18374 }
18375 }
18376
18377 DeclContext *SearchDC = CurContext;
18378 DeclContext *DC = CurContext;
18379 bool isStdBadAlloc = false;
18380 bool isStdAlignValT = false;
18381
18382 RedeclarationKind Redecl = forRedeclarationInCurContext();
18383 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
18384 Redecl = RedeclarationKind::NotForRedeclaration;
18385
18386 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
18387 /// implemented asks for structural equivalence checking, the returned decl
18388 /// here is passed back to the parser, allowing the tag body to be parsed.
18389 auto createTagFromNewDecl = [&]() -> TagDecl * {
18390 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
18391 // If there is an identifier, use the location of the identifier as the
18392 // location of the decl, otherwise use the location of the struct/union
18393 // keyword.
18394 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18395 TagDecl *New = nullptr;
18396
18397 if (Kind == TagTypeKind::Enum) {
18398 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, PrevDecl: nullptr,
18399 IsScoped: ScopedEnum, IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18400 // If this is an undefined enum, bail.
18401 if (TUK != TagUseKind::Definition && !Invalid)
18402 return nullptr;
18403 if (EnumUnderlying) {
18404 EnumDecl *ED = cast<EnumDecl>(Val: New);
18405 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
18406 ED->setIntegerTypeSourceInfo(TI);
18407 else
18408 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
18409 QualType EnumTy = ED->getIntegerType();
18410 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
18411 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
18412 : EnumTy);
18413 }
18414 } else { // struct/union
18415 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18416 PrevDecl: nullptr);
18417 }
18418
18419 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18420 // Add alignment attributes if necessary; these attributes are checked
18421 // when the ASTContext lays out the structure.
18422 //
18423 // It is important for implementing the correct semantics that this
18424 // happen here (in ActOnTag). The #pragma pack stack is
18425 // maintained as a result of parser callbacks which can occur at
18426 // many points during the parsing of a struct declaration (because
18427 // the #pragma tokens are effectively skipped over during the
18428 // parsing of the struct).
18429 if (TUK == TagUseKind::Definition &&
18430 (!SkipBody || !SkipBody->ShouldSkip)) {
18431 if (LangOpts.HLSL)
18432 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
18433 AddAlignmentAttributesForRecord(RD);
18434 AddMsStructLayoutForRecord(RD);
18435 }
18436 }
18437 New->setLexicalDeclContext(CurContext);
18438 return New;
18439 };
18440
18441 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
18442 if (Name && SS.isNotEmpty()) {
18443 // We have a nested-name tag ('struct foo::bar').
18444
18445 // Check for invalid 'foo::'.
18446 if (SS.isInvalid()) {
18447 Name = nullptr;
18448 goto CreateNewDecl;
18449 }
18450
18451 // If this is a friend or a reference to a class in a dependent
18452 // context, don't try to make a decl for it.
18453 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18454 DC = computeDeclContext(SS, EnteringContext: false);
18455 if (!DC) {
18456 IsDependent = true;
18457 return true;
18458 }
18459 } else {
18460 DC = computeDeclContext(SS, EnteringContext: true);
18461 if (!DC) {
18462 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_dependent_nested_name_spec)
18463 << SS.getRange();
18464 return true;
18465 }
18466 }
18467
18468 if (RequireCompleteDeclContext(SS, DC))
18469 return true;
18470
18471 SearchDC = DC;
18472 // Look-up name inside 'foo::'.
18473 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18474
18475 if (Previous.isAmbiguous())
18476 return true;
18477
18478 if (Previous.empty()) {
18479 // Name lookup did not find anything. However, if the
18480 // nested-name-specifier refers to the current instantiation,
18481 // and that current instantiation has any dependent base
18482 // classes, we might find something at instantiation time: treat
18483 // this as a dependent elaborated-type-specifier.
18484 // But this only makes any sense for reference-like lookups.
18485 if (Previous.wasNotFoundInCurrentInstantiation() &&
18486 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18487 IsDependent = true;
18488 return true;
18489 }
18490
18491 // A tag 'foo::bar' must already exist.
18492 Diag(Loc: NameLoc, DiagID: diag::err_not_tag_in_scope)
18493 << Kind << Name << DC << SS.getRange();
18494 Name = nullptr;
18495 Invalid = true;
18496 goto CreateNewDecl;
18497 }
18498 } else if (Name) {
18499 // C++14 [class.mem]p14:
18500 // If T is the name of a class, then each of the following shall have a
18501 // name different from T:
18502 // -- every member of class T that is itself a type
18503 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18504 DiagnoseClassNameShadow(DC: SearchDC, NameInfo: DeclarationNameInfo(Name, NameLoc)))
18505 return true;
18506
18507 // If this is a named struct, check to see if there was a previous forward
18508 // declaration or definition.
18509 // FIXME: We're looking into outer scopes here, even when we
18510 // shouldn't be. Doing so can result in ambiguities that we
18511 // shouldn't be diagnosing.
18512 LookupName(R&: Previous, S);
18513
18514 // When declaring or defining a tag, ignore ambiguities introduced
18515 // by types using'ed into this scope.
18516 if (Previous.isAmbiguous() &&
18517 (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) {
18518 LookupResult::Filter F = Previous.makeFilter();
18519 while (F.hasNext()) {
18520 NamedDecl *ND = F.next();
18521 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18522 DC: SearchDC->getRedeclContext()))
18523 F.erase();
18524 }
18525 F.done();
18526 }
18527
18528 // C++11 [namespace.memdef]p3:
18529 // If the name in a friend declaration is neither qualified nor
18530 // a template-id and the declaration is a function or an
18531 // elaborated-type-specifier, the lookup to determine whether
18532 // the entity has been previously declared shall not consider
18533 // any scopes outside the innermost enclosing namespace.
18534 //
18535 // MSVC doesn't implement the above rule for types, so a friend tag
18536 // declaration may be a redeclaration of a type declared in an enclosing
18537 // scope. They do implement this rule for friend functions.
18538 //
18539 // Does it matter that this should be by scope instead of by
18540 // semantic context?
18541 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18542 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18543 LookupResult::Filter F = Previous.makeFilter();
18544 bool FriendSawTagOutsideEnclosingNamespace = false;
18545 while (F.hasNext()) {
18546 NamedDecl *ND = F.next();
18547 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
18548 if (DC->isFileContext() &&
18549 !EnclosingNS->Encloses(DC: ND->getDeclContext())) {
18550 if (getLangOpts().MSVCCompat)
18551 FriendSawTagOutsideEnclosingNamespace = true;
18552 else
18553 F.erase();
18554 }
18555 }
18556 F.done();
18557
18558 // Diagnose this MSVC extension in the easy case where lookup would have
18559 // unambiguously found something outside the enclosing namespace.
18560 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18561 NamedDecl *ND = Previous.getFoundDecl();
18562 Diag(Loc: NameLoc, DiagID: diag::ext_friend_tag_redecl_outside_namespace)
18563 << createFriendTagNNSFixIt(SemaRef&: *this, ND, S, NameLoc);
18564 }
18565 }
18566
18567 // Note: there used to be some attempt at recovery here.
18568 if (Previous.isAmbiguous())
18569 return true;
18570
18571 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18572 // FIXME: This makes sure that we ignore the contexts associated
18573 // with C structs, unions, and enums when looking for a matching
18574 // tag declaration or definition. See the similar lookup tweak
18575 // in Sema::LookupName; is there a better way to deal with this?
18576 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(Val: SearchDC))
18577 SearchDC = SearchDC->getParent();
18578 } else if (getLangOpts().CPlusPlus) {
18579 // Inside ObjCContainer want to keep it as a lexical decl context but go
18580 // past it (most often to TranslationUnit) to find the semantic decl
18581 // context.
18582 while (isa<ObjCContainerDecl>(Val: SearchDC))
18583 SearchDC = SearchDC->getParent();
18584 }
18585 } else if (getLangOpts().CPlusPlus) {
18586 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18587 // TagDecl the same way as we skip it for named TagDecl.
18588 while (isa<ObjCContainerDecl>(Val: SearchDC))
18589 SearchDC = SearchDC->getParent();
18590 }
18591
18592 if (Previous.isSingleResult() &&
18593 Previous.getFoundDecl()->isTemplateParameter()) {
18594 // Maybe we will complain about the shadowed template parameter.
18595 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl: Previous.getFoundDecl());
18596 // Just pretend that we didn't see the previous declaration.
18597 Previous.clear();
18598 }
18599
18600 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18601 DC->getRedeclContext()->Equals(DC: getStdNamespace())) {
18602 if (Name->isStr(Str: "bad_alloc")) {
18603 // This is a declaration of or a reference to "std::bad_alloc".
18604 isStdBadAlloc = true;
18605
18606 // If std::bad_alloc has been implicitly declared (but made invisible to
18607 // name lookup), fill in this implicit declaration as the previous
18608 // declaration, so that the declarations get chained appropriately.
18609 if (Previous.empty() && StdBadAlloc)
18610 Previous.addDecl(D: getStdBadAlloc());
18611 } else if (Name->isStr(Str: "align_val_t")) {
18612 isStdAlignValT = true;
18613 if (Previous.empty() && StdAlignValT)
18614 Previous.addDecl(D: getStdAlignValT());
18615 }
18616 }
18617
18618 // If we didn't find a previous declaration, and this is a reference
18619 // (or friend reference), move to the correct scope. In C++, we
18620 // also need to do a redeclaration lookup there, just in case
18621 // there's a shadow friend decl.
18622 if (Name && Previous.empty() &&
18623 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18624 IsTemplateParamOrArg)) {
18625 if (Invalid) goto CreateNewDecl;
18626 assert(SS.isEmpty());
18627
18628 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18629 // C++ [basic.scope.pdecl]p5:
18630 // -- for an elaborated-type-specifier of the form
18631 //
18632 // class-key identifier
18633 //
18634 // if the elaborated-type-specifier is used in the
18635 // decl-specifier-seq or parameter-declaration-clause of a
18636 // function defined in namespace scope, the identifier is
18637 // declared as a class-name in the namespace that contains
18638 // the declaration; otherwise, except as a friend
18639 // declaration, the identifier is declared in the smallest
18640 // non-class, non-function-prototype scope that contains the
18641 // declaration.
18642 //
18643 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18644 // C structs and unions.
18645 //
18646 // It is an error in C++ to declare (rather than define) an enum
18647 // type, including via an elaborated type specifier. We'll
18648 // diagnose that later; for now, declare the enum in the same
18649 // scope as we would have picked for any other tag type.
18650 //
18651 // GNU C also supports this behavior as part of its incomplete
18652 // enum types extension, while GNU C++ does not.
18653 //
18654 // Find the context where we'll be declaring the tag.
18655 // FIXME: We would like to maintain the current DeclContext as the
18656 // lexical context,
18657 SearchDC = getTagInjectionContext(DC: SearchDC);
18658
18659 // Find the scope where we'll be declaring the tag.
18660 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18661 } else {
18662 assert(TUK == TagUseKind::Friend);
18663 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: SearchDC);
18664
18665 // C++ [namespace.memdef]p3:
18666 // If a friend declaration in a non-local class first declares a
18667 // class or function, the friend class or function is a member of
18668 // the innermost enclosing namespace.
18669 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18670 : SearchDC->getEnclosingNamespaceContext();
18671 }
18672
18673 // In C++, we need to do a redeclaration lookup to properly
18674 // diagnose some problems.
18675 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18676 // hidden declaration so that we don't get ambiguity errors when using a
18677 // type declared by an elaborated-type-specifier. In C that is not correct
18678 // and we should instead merge compatible types found by lookup.
18679 if (getLangOpts().CPlusPlus) {
18680 // FIXME: This can perform qualified lookups into function contexts,
18681 // which are meaningless.
18682 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18683 LookupQualifiedName(R&: Previous, LookupCtx: SearchDC);
18684 } else {
18685 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18686 LookupName(R&: Previous, S);
18687 }
18688 }
18689
18690 // If we have a known previous declaration to use, then use it.
18691 if (Previous.empty() && SkipBody && SkipBody->Previous)
18692 Previous.addDecl(D: SkipBody->Previous);
18693
18694 if (!Previous.empty()) {
18695 NamedDecl *PrevDecl = Previous.getFoundDecl();
18696 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18697
18698 // It's okay to have a tag decl in the same scope as a typedef
18699 // which hides a tag decl in the same scope. Finding this
18700 // with a redeclaration lookup can only actually happen in C++.
18701 //
18702 // This is also okay for elaborated-type-specifiers, which is
18703 // technically forbidden by the current standard but which is
18704 // okay according to the likely resolution of an open issue;
18705 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18706 if (getLangOpts().CPlusPlus) {
18707 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18708 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18709 if (Tag->getDeclName() == Name &&
18710 Tag->getDeclContext()->getRedeclContext()
18711 ->Equals(DC: TD->getDeclContext()->getRedeclContext())) {
18712 PrevDecl = Tag;
18713 Previous.clear();
18714 Previous.addDecl(D: Tag);
18715 Previous.resolveKind();
18716 }
18717 }
18718 }
18719 }
18720
18721 // If this is a redeclaration of a using shadow declaration, it must
18722 // declare a tag in the same context. In MSVC mode, we allow a
18723 // redefinition if either context is within the other.
18724 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: DirectPrevDecl)) {
18725 auto *OldTag = dyn_cast<TagDecl>(Val: PrevDecl);
18726 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18727 TUK != TagUseKind::Friend &&
18728 isDeclInScope(D: Shadow, Ctx: SearchDC, S, AllowInlineNamespace: isMemberSpecialization) &&
18729 !(OldTag && isAcceptableTagRedeclContext(
18730 S&: *this, OldDC: OldTag->getDeclContext(), NewDC: SearchDC))) {
18731 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
18732 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
18733 DiagID: diag::note_using_decl_target);
18734 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
18735 << 0;
18736 // Recover by ignoring the old declaration.
18737 Previous.clear();
18738 goto CreateNewDecl;
18739 }
18740 }
18741
18742 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(Val: PrevDecl)) {
18743 // If this is a use of a previous tag, or if the tag is already declared
18744 // in the same scope (so that the definition/declaration completes or
18745 // rementions the tag), reuse the decl.
18746 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18747 isTagRedeclarationInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18748 AllowInlineNamespace: SS.isNotEmpty() ||
18749 isMemberSpecialization)) {
18750
18751 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: PrevDecl);
18752 RD && RD->isInjectedClassName()) {
18753 // If lookup found the injected class name, the previous declaration
18754 // is the class being injected into.
18755 Previous.clear();
18756 PrevDecl = PrevTagDecl = cast<CXXRecordDecl>(Val: RD->getDeclContext());
18757 Previous.addDecl(D: PrevDecl);
18758 Previous.resolveKind();
18759 IsInjectedClassName = true;
18760 }
18761
18762 // Make sure that this wasn't declared as an enum and now used as a
18763 // struct or something similar.
18764 if (!isAcceptableTagRedeclaration(Previous: PrevTagDecl, NewTag: Kind,
18765 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
18766 Name)) {
18767 bool SafeToContinue =
18768 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18769 Kind != TagTypeKind::Enum);
18770 if (SafeToContinue)
18771 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
18772 << Name
18773 << FixItHint::CreateReplacement(RemoveRange: SourceRange(KWLoc),
18774 Code: PrevTagDecl->getKindName());
18775 else
18776 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag) << Name;
18777 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_use);
18778
18779 if (SafeToContinue)
18780 Kind = PrevTagDecl->getTagKind();
18781 else {
18782 // Recover by making this an anonymous redefinition.
18783 Name = nullptr;
18784 Previous.clear();
18785 Invalid = true;
18786 }
18787 }
18788
18789 if (Kind == TagTypeKind::Enum &&
18790 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18791 const EnumDecl *PrevEnum = cast<EnumDecl>(Val: PrevTagDecl);
18792 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18793 return PrevTagDecl;
18794
18795 QualType EnumUnderlyingTy;
18796 if (TypeSourceInfo *TI =
18797 dyn_cast_if_present<TypeSourceInfo *>(Val&: EnumUnderlying))
18798 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18799 else if (const Type *T =
18800 dyn_cast_if_present<const Type *>(Val&: EnumUnderlying))
18801 EnumUnderlyingTy = QualType(T, 0);
18802
18803 // All conflicts with previous declarations are recovered by
18804 // returning the previous declaration, unless this is a definition,
18805 // in which case we want the caller to bail out.
18806 if (CheckEnumRedeclaration(EnumLoc: NameLoc.isValid() ? NameLoc : KWLoc,
18807 IsScoped: ScopedEnum, EnumUnderlyingTy,
18808 IsFixed, Prev: PrevEnum))
18809 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18810 }
18811
18812 // C++11 [class.mem]p1:
18813 // A member shall not be declared twice in the member-specification,
18814 // except that a nested class or member class template can be declared
18815 // and then later defined.
18816 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18817 S->isDeclScope(D: PrevDecl)) {
18818 Diag(Loc: NameLoc, DiagID: diag::ext_member_redeclared);
18819 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_declaration);
18820 }
18821
18822 // C++ [class.local]p3:
18823 // A class nested within a local class is a local class. A member of
18824 // a local class X shall be declared only in the definition of X or,
18825 // if the member is a nested class, in the nearest enclosing block
18826 // scope of X.
18827 if (TUK == TagUseKind::Definition && SS.isValid()) {
18828 if (const auto *OutermostClass = dyn_cast<CXXRecordDecl>(Val: PrevDecl)) {
18829 while (const auto *ParentClass =
18830 dyn_cast<CXXRecordDecl>(Val: OutermostClass->getParent()))
18831 OutermostClass = ParentClass;
18832
18833 if (OutermostClass->isLocalClass() &&
18834 !S->isDeclScope(D: OutermostClass)) {
18835 Diag(Loc: NameLoc, DiagID: diag::err_local_nested_class_invalid_scope)
18836 << Name << OutermostClass;
18837 Diag(Loc: OutermostClass->getLocation(), DiagID: diag::note_defined_here)
18838 << OutermostClass;
18839 }
18840 }
18841 }
18842
18843 if (!Invalid) {
18844 // If this is a use, just return the declaration we found, unless
18845 // we have attributes.
18846 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18847 if (!Attrs.empty()) {
18848 // FIXME: Diagnose these attributes. For now, we create a new
18849 // declaration to hold them.
18850 } else if (TUK == TagUseKind::Reference &&
18851 (PrevTagDecl->getFriendObjectKind() ==
18852 Decl::FOK_Undeclared ||
18853 PrevDecl->getOwningModule() != getCurrentModule()) &&
18854 SS.isEmpty()) {
18855 // This declaration is a reference to an existing entity, but
18856 // has different visibility from that entity: it either makes
18857 // a friend visible or it makes a type visible in a new module.
18858 // In either case, create a new declaration. We only do this if
18859 // the declaration would have meant the same thing if no prior
18860 // declaration were found, that is, if it was found in the same
18861 // scope where we would have injected a declaration.
18862 if (!getTagInjectionContext(DC: CurContext)->getRedeclContext()
18863 ->Equals(DC: PrevDecl->getDeclContext()->getRedeclContext()))
18864 return PrevTagDecl;
18865 // This is in the injected scope, create a new declaration in
18866 // that scope.
18867 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18868 } else {
18869 return PrevTagDecl;
18870 }
18871 }
18872
18873 // Diagnose attempts to redefine a tag.
18874 if (TUK == TagUseKind::Definition) {
18875 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18876 // If the type is currently being defined, complain
18877 // about a nested redefinition.
18878 if (Def->isBeingDefined()) {
18879 Diag(Loc: NameLoc, DiagID: diag::err_nested_redefinition) << Name;
18880 Diag(Loc: PrevTagDecl->getLocation(),
18881 DiagID: diag::note_previous_definition);
18882 Name = nullptr;
18883 Previous.clear();
18884 Invalid = true;
18885 } else {
18886 // If we're defining a specialization and the previous
18887 // definition is from an implicit instantiation, don't emit an
18888 // error here; we'll catch this in the general case below.
18889 bool IsExplicitSpecializationAfterInstantiation = false;
18890 if (isMemberSpecialization) {
18891 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Def))
18892 IsExplicitSpecializationAfterInstantiation =
18893 RD->getTemplateSpecializationKind() !=
18894 TSK_ExplicitSpecialization;
18895 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: Def))
18896 IsExplicitSpecializationAfterInstantiation =
18897 ED->getTemplateSpecializationKind() !=
18898 TSK_ExplicitSpecialization;
18899 }
18900
18901 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18902 // do not keep more that one definition around (merge them).
18903 // However, ensure the decl passes the structural compatibility
18904 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18905 NamedDecl *Hidden = nullptr;
18906 bool HiddenDefVisible = false;
18907 if (SkipBody && (isRedefinitionAllowedFor(D: Def, NewDefinitionLoc: NameLoc, Suggested: &Hidden,
18908 Visible&: HiddenDefVisible) ||
18909 getLangOpts().C23)) {
18910 // There is a definition of this tag, but it is not visible.
18911 // We explicitly make use of C++'s one definition rule here,
18912 // and assume that this definition is identical to the hidden
18913 // one we already have. Make the existing definition visible
18914 // and use it in place of this one.
18915 if (!getLangOpts().CPlusPlus) {
18916 // Postpone making the old definition visible until after we
18917 // complete parsing the new one and do the structural
18918 // comparison.
18919 SkipBody->CheckSameAsPrevious = true;
18920 SkipBody->New = createTagFromNewDecl();
18921 SkipBody->Previous = Def;
18922
18923 ProcessDeclAttributeList(S, D: SkipBody->New, AttrList: Attrs);
18924 return Def;
18925 }
18926
18927 SkipBody->ShouldSkip = true;
18928 SkipBody->Previous = Def;
18929 if (!HiddenDefVisible && Hidden)
18930 makeMergedDefinitionVisible(ND: Hidden);
18931 // Carry on and handle it like a normal definition. We'll
18932 // skip starting the definition later.
18933
18934 } else if (!IsExplicitSpecializationAfterInstantiation) {
18935 // A redeclaration in function prototype scope in C isn't
18936 // visible elsewhere, so merely issue a warning.
18937 if (!getLangOpts().CPlusPlus &&
18938 S->containedInPrototypeScope())
18939 Diag(Loc: NameLoc, DiagID: diag::warn_redefinition_in_param_list)
18940 << Name;
18941 else
18942 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
18943 notePreviousDefinition(Old: Def,
18944 New: NameLoc.isValid() ? NameLoc : KWLoc);
18945 // If this is a redefinition, recover by making this
18946 // struct be anonymous, which will make any later
18947 // references get the previous definition.
18948 Name = nullptr;
18949 Previous.clear();
18950 Invalid = true;
18951 }
18952 }
18953 }
18954
18955 // Okay, this is definition of a previously declared or referenced
18956 // tag. We're going to create a new Decl for it.
18957 }
18958
18959 // Okay, we're going to make a redeclaration. If this is some kind
18960 // of reference, make sure we build the redeclaration in the same DC
18961 // as the original, and ignore the current access specifier.
18962 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference ||
18963 IsInjectedClassName) {
18964 SearchDC = PrevTagDecl->getDeclContext();
18965 AS = AS_none;
18966 }
18967 }
18968 // If we get here we have (another) forward declaration or we
18969 // have a definition. Just create a new decl.
18970
18971 } else {
18972 // If we get here, this is a definition of a new tag type in a nested
18973 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18974 // new decl/type. We set PrevDecl to NULL so that the entities
18975 // have distinct types.
18976 Previous.clear();
18977 }
18978 // If we get here, we're going to create a new Decl. If PrevDecl
18979 // is non-NULL, it's a definition of the tag declared by
18980 // PrevDecl. If it's NULL, we have a new definition.
18981
18982 // Otherwise, PrevDecl is not a tag, but was found with tag
18983 // lookup. This is only actually possible in C++, where a few
18984 // things like templates still live in the tag namespace.
18985 } else {
18986 // Use a better diagnostic if an elaborated-type-specifier
18987 // found the wrong kind of type on the first
18988 // (non-redeclaration) lookup.
18989 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18990 !Previous.isForRedeclaration()) {
18991 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18992 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_non_tag)
18993 << PrevDecl << NTK << Kind;
18994 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_declared_at);
18995 Invalid = true;
18996
18997 // Otherwise, only diagnose if the declaration is in scope.
18998 } else if (!isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18999 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
19000 // do nothing
19001
19002 // Diagnose implicit declarations introduced by elaborated types.
19003 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
19004 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
19005 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_conflict) << NTK;
19006 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
19007 Invalid = true;
19008
19009 // Otherwise it's a declaration. Call out a particularly common
19010 // case here.
19011 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
19012 unsigned Kind = 0;
19013 if (isa<TypeAliasDecl>(Val: PrevDecl)) Kind = 1;
19014 Diag(Loc: NameLoc, DiagID: diag::err_tag_definition_of_typedef)
19015 << Name << Kind << TND->getUnderlyingType();
19016 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
19017 Invalid = true;
19018
19019 // Otherwise, diagnose.
19020 } else {
19021 // The tag name clashes with something else in the target scope,
19022 // issue an error and recover by making this tag be anonymous.
19023 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
19024 notePreviousDefinition(Old: PrevDecl, New: NameLoc);
19025 Name = nullptr;
19026 Invalid = true;
19027 }
19028
19029 // The existing declaration isn't relevant to us; we're in a
19030 // new scope, so clear out the previous declaration.
19031 Previous.clear();
19032 }
19033 }
19034
19035CreateNewDecl:
19036
19037 TagDecl *PrevDecl = nullptr;
19038 if (Previous.isSingleResult())
19039 PrevDecl = cast<TagDecl>(Val: Previous.getFoundDecl());
19040
19041 // If there is an identifier, use the location of the identifier as the
19042 // location of the decl, otherwise use the location of the struct/union
19043 // keyword.
19044 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
19045
19046 // Otherwise, create a new declaration. If there is a previous
19047 // declaration of the same entity, the two will be linked via
19048 // PrevDecl.
19049 TagDecl *New;
19050
19051 if (Kind == TagTypeKind::Enum) {
19052 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
19053 // enum X { A, B, C } D; D should chain to X.
19054 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
19055 PrevDecl: cast_or_null<EnumDecl>(Val: PrevDecl), IsScoped: ScopedEnum,
19056 IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
19057
19058 EnumDecl *ED = cast<EnumDecl>(Val: New);
19059 ED->setEnumKeyRange(SourceRange(
19060 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
19061
19062 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
19063 StdAlignValT = cast<EnumDecl>(Val: New);
19064
19065 // If this is an undefined enum, warn.
19066 if (TUK != TagUseKind::Definition && !Invalid) {
19067 TagDecl *Def;
19068 if (IsFixed && ED->isFixed()) {
19069 // C++0x: 7.2p2: opaque-enum-declaration.
19070 // Conflicts are diagnosed above. Do nothing.
19071 } else if (PrevDecl &&
19072 (Def = cast<EnumDecl>(Val: PrevDecl)->getDefinition())) {
19073 Diag(Loc, DiagID: diag::ext_forward_ref_enum_def)
19074 << New;
19075 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
19076 } else {
19077 unsigned DiagID = diag::ext_forward_ref_enum;
19078 if (getLangOpts().MSVCCompat)
19079 DiagID = diag::ext_ms_forward_ref_enum;
19080 else if (getLangOpts().CPlusPlus)
19081 DiagID = diag::err_forward_ref_enum;
19082 Diag(Loc, DiagID);
19083 }
19084 }
19085
19086 if (EnumUnderlying) {
19087 EnumDecl *ED = cast<EnumDecl>(Val: New);
19088 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
19089 ED->setIntegerTypeSourceInfo(TI);
19090 else
19091 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
19092 QualType EnumTy = ED->getIntegerType();
19093 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
19094 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
19095 : EnumTy);
19096 assert(ED->isComplete() && "enum with type should be complete");
19097 }
19098 } else {
19099 // struct/union/class
19100
19101 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
19102 // struct X { int A; } D; D should chain to X.
19103 if (getLangOpts().CPlusPlus) {
19104 // FIXME: Look for a way to use RecordDecl for simple structs.
19105 New = CXXRecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
19106 PrevDecl: cast_or_null<CXXRecordDecl>(Val: PrevDecl));
19107
19108 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
19109 StdBadAlloc = cast<CXXRecordDecl>(Val: New);
19110 } else
19111 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
19112 PrevDecl: cast_or_null<RecordDecl>(Val: PrevDecl));
19113 }
19114
19115 // Only C23 and later allow defining new types in 'offsetof()'.
19116 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
19117 !getLangOpts().CPlusPlus && !getLangOpts().C23)
19118 Diag(Loc: New->getLocation(), DiagID: diag::ext_type_defined_in_offsetof)
19119 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
19120
19121 // C++11 [dcl.type]p3:
19122 // A type-specifier-seq shall not define a class or enumeration [...].
19123 if (!Invalid && getLangOpts().CPlusPlus &&
19124 (IsTypeSpecifier || IsTemplateParamOrArg) &&
19125 TUK == TagUseKind::Definition) {
19126 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_type_specifier)
19127 << Context.getCanonicalTagType(TD: New);
19128 Invalid = true;
19129 }
19130
19131 if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition &&
19132 DC->getDeclKind() == Decl::Enum) {
19133 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_enum)
19134 << Context.getCanonicalTagType(TD: New);
19135 Invalid = true;
19136 }
19137
19138 // Maybe add qualifier info.
19139 if (SS.isNotEmpty()) {
19140 if (SS.isSet()) {
19141 // If this is either a declaration or a definition, check the
19142 // nested-name-specifier against the current context.
19143 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
19144 diagnoseQualifiedDeclaration(SS, DC, Name: OrigName, Loc,
19145 /*TemplateId=*/nullptr,
19146 IsMemberSpecialization: isMemberSpecialization))
19147 Invalid = true;
19148
19149 New->setQualifierInfo(SS.getWithLocInContext(Context));
19150 if (TemplateParameterLists.size() > 0) {
19151 New->setTemplateParameterListsInfo(Context, TPLists: TemplateParameterLists);
19152 }
19153 }
19154 else
19155 Invalid = true;
19156 }
19157
19158 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
19159 // Add alignment attributes if necessary; these attributes are checked when
19160 // the ASTContext lays out the structure.
19161 //
19162 // It is important for implementing the correct semantics that this
19163 // happen here (in ActOnTag). The #pragma pack stack is
19164 // maintained as a result of parser callbacks which can occur at
19165 // many points during the parsing of a struct declaration (because
19166 // the #pragma tokens are effectively skipped over during the
19167 // parsing of the struct).
19168 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
19169 if (LangOpts.HLSL)
19170 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
19171 AddAlignmentAttributesForRecord(RD);
19172 AddMsStructLayoutForRecord(RD);
19173 }
19174
19175 // The __interface tag implies __declspec(novtable) according to MSDN:
19176 // https://learn.microsoft.com/en-us/cpp/cpp/interface?view=msvc-170
19177 // so add the implicit attribute now.
19178 if (Kind == TagTypeKind::Interface)
19179 RD->addAttr(A: MSNoVTableAttr::CreateImplicit(Ctx&: Context));
19180 }
19181
19182 if (ModulePrivateLoc.isValid()) {
19183 if (isMemberSpecialization)
19184 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_specialization)
19185 << 2
19186 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
19187 // __module_private__ does not apply to local classes. However, we only
19188 // diagnose this as an error when the declaration specifiers are
19189 // freestanding. Here, we just ignore the __module_private__.
19190 else if (!SearchDC->isFunctionOrMethod())
19191 New->setModulePrivate();
19192 }
19193
19194 // If this is a specialization of a member class (of a class template),
19195 // check the specialization.
19196 if (isMemberSpecialization && CheckMemberSpecialization(Member: New, Previous))
19197 Invalid = true;
19198
19199 // If we're declaring or defining a tag in function prototype scope in C,
19200 // note that this type can only be used within the function and add it to
19201 // the list of decls to inject into the function definition scope. However,
19202 // in C23 and later, while the type is only visible within the function, the
19203 // function can be called with a compatible type defined in the same TU, so
19204 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
19205 if ((Name || Kind == TagTypeKind::Enum) &&
19206 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
19207 if (getLangOpts().CPlusPlus) {
19208 // C++ [dcl.fct]p6:
19209 // Types shall not be defined in return or parameter types.
19210 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
19211 Diag(Loc, DiagID: diag::err_type_defined_in_param_type)
19212 << Name;
19213 Invalid = true;
19214 }
19215 if (TUK == TagUseKind::Declaration)
19216 Invalid = true;
19217 } else if (!PrevDecl) {
19218 // In C23 mode, if the declaration is complete, we do not want to
19219 // diagnose.
19220 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
19221 Diag(Loc, DiagID: diag::warn_decl_in_param_list)
19222 << Context.getCanonicalTagType(TD: New);
19223 }
19224 }
19225
19226 if (Invalid)
19227 New->setInvalidDecl();
19228
19229 // Set the lexical context. If the tag has a C++ scope specifier, the
19230 // lexical context will be different from the semantic context.
19231 New->setLexicalDeclContext(CurContext);
19232
19233 // Mark this as a friend decl if applicable.
19234 // In Microsoft mode, a friend declaration also acts as a forward
19235 // declaration so we always pass true to setObjectOfFriendDecl to make
19236 // the tag name visible.
19237 if (TUK == TagUseKind::Friend)
19238 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
19239
19240 // Set the access specifier.
19241 if (!Invalid && SearchDC->isRecord())
19242 SetMemberAccessSpecifier(MemberDecl: New, PrevMemberDecl: PrevDecl, LexicalAS: AS);
19243
19244 // FIXME: An elaborated-type-specifier referring to an existing tag should
19245 // ideally not introduce a redeclaration. ActOnTag currently creates one, so
19246 // avoid diagnosing it as a redeclaration across module boundaries.
19247 //
19248 // See https://github.com/llvm/llvm-project/pull/194546 for full background.
19249 if (PrevDecl && TUK != TagUseKind::Reference)
19250 CheckRedeclarationInModule(New, Old: PrevDecl);
19251
19252 if (TUK == TagUseKind::Definition) {
19253 if (!SkipBody || !SkipBody->ShouldSkip) {
19254 New->startDefinition();
19255 } else {
19256 New->setCompleteDefinition();
19257 New->demoteThisDefinitionToDeclaration();
19258 }
19259 }
19260
19261 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
19262 AddPragmaAttributes(S, D: New);
19263
19264 // If this has an identifier, add it to the scope stack.
19265 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
19266 // We might be replacing an existing declaration in the lookup tables;
19267 // if so, borrow its access specifier.
19268 if (PrevDecl)
19269 New->setAccess(PrevDecl->getAccess());
19270
19271 DeclContext *DC = New->getDeclContext()->getRedeclContext();
19272 DC->makeDeclVisibleInContext(D: New);
19273 if (Name) // can be null along some error paths
19274 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
19275 PushOnScopeChains(D: New, S: EnclosingScope, /* AddToContext = */ false);
19276 } else if (Name) {
19277 S = getNonFieldDeclScope(S);
19278 PushOnScopeChains(D: New, S, AddToContext: true);
19279 } else {
19280 CurContext->addDecl(D: New);
19281 }
19282
19283 // If this is the C FILE type, notify the AST context.
19284 if (IdentifierInfo *II = New->getIdentifier())
19285 if (!New->isInvalidDecl() &&
19286 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
19287 II->isStr(Str: "FILE"))
19288 Context.setFILEDecl(New);
19289
19290 if (PrevDecl)
19291 mergeDeclAttributes(New, Old: PrevDecl);
19292
19293 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: New)) {
19294 inferGslOwnerPointerAttribute(Record: CXXRD);
19295 inferNullableClassAttribute(CRD: CXXRD);
19296 }
19297
19298 // If there's a #pragma GCC visibility in scope, set the visibility of this
19299 // record.
19300 AddPushedVisibilityAttribute(RD: New);
19301
19302 // If this is not a definition, process API notes for it now.
19303 if (TUK != TagUseKind::Definition)
19304 ProcessAPINotes(D: New);
19305
19306 if (isMemberSpecialization && !New->isInvalidDecl())
19307 CompleteMemberSpecialization(Member: New, Previous);
19308
19309 OwnedDecl = true;
19310 // In C++, don't return an invalid declaration. We can't recover well from
19311 // the cases where we make the type anonymous.
19312 if (Invalid && getLangOpts().CPlusPlus) {
19313 if (New->isBeingDefined())
19314 if (auto RD = dyn_cast<RecordDecl>(Val: New))
19315 RD->completeDefinition();
19316 return true;
19317 } else if (SkipBody && SkipBody->ShouldSkip) {
19318 return SkipBody->Previous;
19319 } else {
19320 return New;
19321 }
19322}
19323
19324void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
19325 AdjustDeclIfTemplate(Decl&: TagD);
19326 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19327
19328 // Enter the tag context.
19329 PushDeclContext(S, DC: Tag);
19330
19331 ActOnDocumentableDecl(D: TagD);
19332
19333 // If there's a #pragma GCC visibility in scope, set the visibility of this
19334 // record.
19335 AddPushedVisibilityAttribute(RD: Tag);
19336}
19337
19338bool Sema::ActOnDuplicateDefinition(Scope *S, Decl *Prev,
19339 SkipBodyInfo &SkipBody) {
19340 if (!hasStructuralCompatLayout(D: Prev, Suggested: SkipBody.New))
19341 return false;
19342
19343 // Make the previous decl visible.
19344 makeMergedDefinitionVisible(ND: SkipBody.Previous);
19345 CleanupMergedEnum(S, New: SkipBody.New);
19346 return true;
19347}
19348
19349void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
19350 SourceLocation FinalLoc,
19351 bool IsFinalSpelledSealed,
19352 bool IsAbstract,
19353 SourceLocation LBraceLoc) {
19354 AdjustDeclIfTemplate(Decl&: TagD);
19355 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: TagD);
19356
19357 FieldCollector->StartClass();
19358
19359 if (!Record->getIdentifier())
19360 return;
19361
19362 if (IsAbstract)
19363 Record->markAbstract();
19364
19365 if (FinalLoc.isValid()) {
19366 Record->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: FinalLoc,
19367 S: IsFinalSpelledSealed
19368 ? FinalAttr::Keyword_sealed
19369 : FinalAttr::Keyword_final));
19370 }
19371
19372 // C++ [class]p2:
19373 // [...] The class-name is also inserted into the scope of the
19374 // class itself; this is known as the injected-class-name. For
19375 // purposes of access checking, the injected-class-name is treated
19376 // as if it were a public member name.
19377 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
19378 C: Context, TK: Record->getTagKind(), DC: CurContext, StartLoc: Record->getBeginLoc(),
19379 IdLoc: Record->getLocation(), Id: Record->getIdentifier());
19380 InjectedClassName->setImplicit();
19381 InjectedClassName->setAccess(AS_public);
19382 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
19383 InjectedClassName->setDescribedClassTemplate(Template);
19384
19385 PushOnScopeChains(D: InjectedClassName, S);
19386 assert(InjectedClassName->isInjectedClassName() &&
19387 "Broken injected-class-name");
19388}
19389
19390void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
19391 SourceRange BraceRange) {
19392 AdjustDeclIfTemplate(Decl&: TagD);
19393 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19394 Tag->setBraceRange(BraceRange);
19395
19396 // Make sure we "complete" the definition even it is invalid.
19397 if (Tag->isBeingDefined()) {
19398 assert(Tag->isInvalidDecl() && "We should already have completed it");
19399 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
19400 RD->completeDefinition();
19401 }
19402
19403 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
19404 FieldCollector->FinishClass();
19405 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
19406 auto *Def = RD->getDefinition();
19407 assert(Def && "The record is expected to have a completed definition");
19408 unsigned NumInitMethods = 0;
19409 for (auto *Method : Def->methods()) {
19410 if (!Method->getIdentifier())
19411 continue;
19412 if (Method->getName() == "__init")
19413 NumInitMethods++;
19414 }
19415 if (NumInitMethods > 1 || !Def->hasInitMethod())
19416 Diag(Loc: RD->getLocation(), DiagID: diag::err_sycl_special_type_num_init_method);
19417 }
19418
19419 // If we're defining a dynamic class in a module interface unit, we always
19420 // need to produce the vtable for it, even if the vtable is not used in the
19421 // current TU.
19422 //
19423 // The case where the current class is not dynamic is handled in
19424 // MarkVTableUsed.
19425 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
19426 MarkVTableUsed(Loc: RD->getLocation(), Class: RD, /*DefinitionRequired=*/true);
19427 }
19428
19429 // Exit this scope of this tag's definition.
19430 PopDeclContext();
19431
19432 if (getCurLexicalContext()->isObjCContainer() &&
19433 Tag->getDeclContext()->isFileContext())
19434 Tag->setTopLevelDeclInObjCContainer();
19435
19436 // Notify the consumer that we've defined a tag.
19437 if (!Tag->isInvalidDecl())
19438 Consumer.HandleTagDeclDefinition(D: Tag);
19439
19440 // Clangs implementation of #pragma align(packed) differs in bitfield layout
19441 // from XLs and instead matches the XL #pragma pack(1) behavior.
19442 if (Context.getTargetInfo().getTriple().isOSAIX() &&
19443 AlignPackStack.hasValue()) {
19444 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
19445 // Only diagnose #pragma align(packed).
19446 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
19447 return;
19448 const RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag);
19449 if (!RD)
19450 return;
19451 // Only warn if there is at least 1 bitfield member.
19452 if (llvm::any_of(Range: RD->fields(),
19453 P: [](const FieldDecl *FD) { return FD->isBitField(); }))
19454 Diag(Loc: BraceRange.getBegin(), DiagID: diag::warn_pragma_align_not_xl_compatible);
19455 }
19456}
19457
19458void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
19459 AdjustDeclIfTemplate(Decl&: TagD);
19460 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19461 Tag->setInvalidDecl();
19462
19463 // Make sure we "complete" the definition even it is invalid.
19464 if (Tag->isBeingDefined()) {
19465 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
19466 RD->completeDefinition();
19467 }
19468
19469 // We're undoing ActOnTagStartDefinition here, not
19470 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
19471 // the FieldCollector.
19472
19473 PopDeclContext();
19474}
19475
19476// Note that FieldName may be null for anonymous bitfields.
19477ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
19478 const IdentifierInfo *FieldName,
19479 QualType FieldTy, bool IsMsStruct,
19480 Expr *BitWidth) {
19481 assert(BitWidth);
19482 if (BitWidth->containsErrors())
19483 return ExprError();
19484
19485 // C99 6.7.2.1p4 - verify the field type.
19486 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
19487 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19488 // Handle incomplete and sizeless types with a specific error.
19489 if (RequireCompleteSizedType(Loc: FieldLoc, T: FieldTy,
19490 DiagID: diag::err_field_incomplete_or_sizeless))
19491 return ExprError();
19492 if (FieldName)
19493 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_bitfield)
19494 << FieldName << FieldTy << BitWidth->getSourceRange();
19495 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_anon_bitfield)
19496 << FieldTy << BitWidth->getSourceRange();
19497 } else if (DiagnoseUnexpandedParameterPack(E: BitWidth, UPPC: UPPC_BitFieldWidth))
19498 return ExprError();
19499
19500 // If the bit-width is type- or value-dependent, don't try to check
19501 // it now.
19502 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19503 return BitWidth;
19504
19505 llvm::APSInt Value;
19506 ExprResult ICE =
19507 VerifyIntegerConstantExpression(E: BitWidth, Result: &Value, CanFold: AllowFoldKind::Allow);
19508 if (ICE.isInvalid())
19509 return ICE;
19510 BitWidth = ICE.get();
19511
19512 // Zero-width bitfield is ok for anonymous field.
19513 if (Value == 0 && FieldName)
19514 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_zero_width)
19515 << FieldName << BitWidth->getSourceRange();
19516
19517 if (Value.isSigned() && Value.isNegative()) {
19518 if (FieldName)
19519 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_negative_width)
19520 << FieldName << toString(I: Value, Radix: 10);
19521 return Diag(Loc: FieldLoc, DiagID: diag::err_anon_bitfield_has_negative_width)
19522 << toString(I: Value, Radix: 10);
19523 }
19524
19525 // The size of the bit-field must not exceed our maximum permitted object
19526 // size.
19527 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19528 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_too_wide)
19529 << !FieldName << FieldName << toString(I: Value, Radix: 10);
19530 }
19531
19532 if (!FieldTy->isDependentType()) {
19533 uint64_t TypeStorageSize = Context.getTypeSize(T: FieldTy);
19534 uint64_t TypeWidth = Context.getIntWidth(T: FieldTy);
19535 bool BitfieldIsOverwide = Value.ugt(RHS: TypeWidth);
19536
19537 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19538 // ABI.
19539 bool CStdConstraintViolation =
19540 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19541 bool MSBitfieldViolation = Value.ugt(RHS: TypeStorageSize) && IsMsStruct;
19542 if (CStdConstraintViolation || MSBitfieldViolation) {
19543 unsigned DiagWidth =
19544 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19545 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_width_exceeds_type_width)
19546 << (bool)FieldName << FieldName << toString(I: Value, Radix: 10)
19547 << !CStdConstraintViolation << DiagWidth;
19548 }
19549
19550 // Warn on types where the user might conceivably expect to get all
19551 // specified bits as value bits: that's all integral types other than
19552 // 'bool'.
19553 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19554 Diag(Loc: FieldLoc, DiagID: diag::warn_bitfield_width_exceeds_type_width)
19555 << FieldName << Value << (unsigned)TypeWidth;
19556 }
19557 }
19558
19559 if (isa<ConstantExpr>(Val: BitWidth))
19560 return BitWidth;
19561 return ConstantExpr::Create(Context: getASTContext(), E: BitWidth, Result: APValue{Value});
19562}
19563
19564Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
19565 Declarator &D, Expr *BitfieldWidth) {
19566 FieldDecl *Res = HandleField(S, TagD: cast_if_present<RecordDecl>(Val: TagD), DeclStart,
19567 D, BitfieldWidth,
19568 /*InitStyle=*/ICIS_NoInit, AS: AS_public);
19569 return Res;
19570}
19571
19572FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
19573 SourceLocation DeclStart,
19574 Declarator &D, Expr *BitWidth,
19575 InClassInitStyle InitStyle,
19576 AccessSpecifier AS) {
19577 if (D.isDecompositionDeclarator()) {
19578 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
19579 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
19580 << Decomp.getSourceRange();
19581 return nullptr;
19582 }
19583
19584 const IdentifierInfo *II = D.getIdentifier();
19585 SourceLocation Loc = DeclStart;
19586 if (II) Loc = D.getIdentifierLoc();
19587
19588 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19589 QualType T = TInfo->getType();
19590 if (getLangOpts().CPlusPlus) {
19591 CheckExtraCXXDefaultArguments(D);
19592
19593 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19594 UPPC: UPPC_DataMemberType)) {
19595 D.setInvalidType();
19596 T = Context.IntTy;
19597 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19598 }
19599 }
19600
19601 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19602
19603 if (D.getDeclSpec().isInlineSpecified())
19604 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
19605 << getLangOpts().CPlusPlus17;
19606 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19607 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
19608 DiagID: diag::err_invalid_thread)
19609 << DeclSpec::getSpecifierName(S: TSCS);
19610
19611 // Check to see if this name was declared as a member previously
19612 NamedDecl *PrevDecl = nullptr;
19613 LookupResult Previous(*this, II, Loc, LookupMemberName,
19614 RedeclarationKind::ForVisibleRedeclaration);
19615 LookupName(R&: Previous, S);
19616 switch (Previous.getResultKind()) {
19617 case LookupResultKind::Found:
19618 case LookupResultKind::FoundUnresolvedValue:
19619 PrevDecl = Previous.getAsSingle<NamedDecl>();
19620 break;
19621
19622 case LookupResultKind::FoundOverloaded:
19623 PrevDecl = Previous.getRepresentativeDecl();
19624 break;
19625
19626 case LookupResultKind::NotFound:
19627 case LookupResultKind::NotFoundInCurrentInstantiation:
19628 case LookupResultKind::Ambiguous:
19629 break;
19630 }
19631 Previous.suppressDiagnostics();
19632
19633 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19634 // Maybe we will complain about the shadowed template parameter.
19635 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
19636 // Just pretend that we didn't see the previous declaration.
19637 PrevDecl = nullptr;
19638 }
19639
19640 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
19641 PrevDecl = nullptr;
19642
19643 bool Mutable
19644 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19645 SourceLocation TSSL = D.getBeginLoc();
19646 FieldDecl *NewFD
19647 = CheckFieldDecl(Name: II, T, TInfo, Record, Loc, Mutable, BitfieldWidth: BitWidth, InitStyle,
19648 TSSL, AS, PrevDecl, D: &D);
19649
19650 if (NewFD->isInvalidDecl())
19651 Record->setInvalidDecl();
19652
19653 if (D.getDeclSpec().isModulePrivateSpecified())
19654 NewFD->setModulePrivate();
19655
19656 if (NewFD->isInvalidDecl() && PrevDecl) {
19657 // Don't introduce NewFD into scope; there's already something
19658 // with the same name in the same scope.
19659 } else if (II) {
19660 PushOnScopeChains(D: NewFD, S);
19661 } else
19662 Record->addDecl(D: NewFD);
19663
19664 return NewFD;
19665}
19666
19667FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
19668 TypeSourceInfo *TInfo,
19669 RecordDecl *Record, SourceLocation Loc,
19670 bool Mutable, Expr *BitWidth,
19671 InClassInitStyle InitStyle,
19672 SourceLocation TSSL,
19673 AccessSpecifier AS, NamedDecl *PrevDecl,
19674 Declarator *D) {
19675 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19676 bool InvalidDecl = false;
19677 if (D) InvalidDecl = D->isInvalidType();
19678
19679 // If we receive a broken type, recover by assuming 'int' and
19680 // marking this declaration as invalid.
19681 if (T.isNull() || T->containsErrors()) {
19682 InvalidDecl = true;
19683 T = Context.IntTy;
19684 }
19685
19686 QualType EltTy = Context.getBaseElementType(QT: T);
19687 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19688 bool isIncomplete =
19689 LangOpts.HLSL // HLSL allows sizeless builtin types
19690 ? RequireCompleteType(Loc, T: EltTy, DiagID: diag::err_incomplete_type)
19691 : RequireCompleteSizedType(Loc, T: EltTy,
19692 DiagID: diag::err_field_incomplete_or_sizeless);
19693 if (isIncomplete) {
19694 // Fields of incomplete type force their record to be invalid.
19695 Record->setInvalidDecl();
19696 InvalidDecl = true;
19697 } else {
19698 NamedDecl *Def;
19699 EltTy->isIncompleteType(Def: &Def);
19700 if (Def && Def->isInvalidDecl()) {
19701 Record->setInvalidDecl();
19702 InvalidDecl = true;
19703 }
19704 }
19705 }
19706
19707 // TR 18037 does not allow fields to be declared with address space
19708 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19709 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19710 Diag(Loc, DiagID: diag::err_field_with_address_space);
19711 Record->setInvalidDecl();
19712 InvalidDecl = true;
19713 }
19714
19715 if (LangOpts.OpenCL) {
19716 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19717 // used as structure or union field: image, sampler, event or block types.
19718 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19719 T->isBlockPointerType()) {
19720 Diag(Loc, DiagID: diag::err_opencl_type_struct_or_union_field) << T;
19721 Record->setInvalidDecl();
19722 InvalidDecl = true;
19723 }
19724 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19725 // is enabled.
19726 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19727 Ext: "__cl_clang_bitfields", LO: LangOpts)) {
19728 Diag(Loc, DiagID: diag::err_opencl_bitfields);
19729 InvalidDecl = true;
19730 }
19731 }
19732
19733 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19734 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19735 T.hasQualifiers()) {
19736 InvalidDecl = true;
19737 Diag(Loc, DiagID: diag::err_anon_bitfield_qualifiers);
19738 }
19739
19740 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19741 // than a variably modified type.
19742 if (!InvalidDecl && T->isVariablyModifiedType()) {
19743 if (!tryToFixVariablyModifiedVarType(
19744 TInfo, T, Loc, FailedFoldDiagID: diag::err_typecheck_field_variable_size))
19745 InvalidDecl = true;
19746 }
19747
19748 // Fields can not have abstract class types
19749 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19750 DiagID: diag::err_abstract_type_in_decl,
19751 Args: AbstractFieldType))
19752 InvalidDecl = true;
19753
19754 if (InvalidDecl)
19755 BitWidth = nullptr;
19756 // If this is declared as a bit-field, check the bit-field.
19757 if (BitWidth) {
19758 BitWidth =
19759 VerifyBitField(FieldLoc: Loc, FieldName: II, FieldTy: T, IsMsStruct: Record->isMsStruct(C: Context), BitWidth).get();
19760 if (!BitWidth) {
19761 InvalidDecl = true;
19762 BitWidth = nullptr;
19763 }
19764 }
19765
19766 // Check that 'mutable' is consistent with the type of the declaration.
19767 if (!InvalidDecl && Mutable) {
19768 unsigned DiagID = 0;
19769 if (T->isReferenceType())
19770 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19771 : diag::err_mutable_reference;
19772 else if (T.isConstQualified())
19773 DiagID = diag::err_mutable_const;
19774
19775 if (DiagID) {
19776 SourceLocation ErrLoc = Loc;
19777 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19778 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19779 Diag(Loc: ErrLoc, DiagID);
19780 if (DiagID != diag::ext_mutable_reference) {
19781 Mutable = false;
19782 InvalidDecl = true;
19783 }
19784 }
19785 }
19786
19787 // C++11 [class.union]p8 (DR1460):
19788 // At most one variant member of a union may have a
19789 // brace-or-equal-initializer.
19790 if (InitStyle != ICIS_NoInit)
19791 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Record), DefaultInitLoc: Loc);
19792
19793 FieldDecl *NewFD = FieldDecl::Create(C: Context, DC: Record, StartLoc: TSSL, IdLoc: Loc, Id: II, T, TInfo,
19794 BW: BitWidth, Mutable, InitStyle);
19795 if (InvalidDecl)
19796 NewFD->setInvalidDecl();
19797
19798 if (!InvalidDecl)
19799 warnOnCTypeHiddenInCPlusPlus(D: NewFD);
19800
19801 if (PrevDecl && !isa<TagDecl>(Val: PrevDecl) &&
19802 !PrevDecl->isPlaceholderVar(LangOpts: getLangOpts())) {
19803 Diag(Loc, DiagID: diag::err_duplicate_member) << II;
19804 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
19805 NewFD->setInvalidDecl();
19806 }
19807
19808 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19809 if (Record->isUnion()) {
19810 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19811 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19812
19813 // C++ [class.union]p1: An object of a class with a non-trivial
19814 // constructor, a non-trivial copy constructor, a non-trivial
19815 // destructor, or a non-trivial copy assignment operator
19816 // cannot be a member of a union, nor can an array of such
19817 // objects.
19818 if (CheckNontrivialField(FD: NewFD))
19819 NewFD->setInvalidDecl();
19820 }
19821
19822 // C++ [class.union]p1: If a union contains a member of reference type,
19823 // the program is ill-formed, except when compiling with MSVC extensions
19824 // enabled.
19825 if (EltTy->isReferenceType()) {
19826 const bool HaveMSExt =
19827 getLangOpts().MicrosoftExt &&
19828 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
19829
19830 Diag(Loc: NewFD->getLocation(),
19831 DiagID: HaveMSExt ? diag::ext_union_member_of_reference_type
19832 : diag::err_union_member_of_reference_type)
19833 << NewFD->getDeclName() << EltTy;
19834 if (!HaveMSExt)
19835 NewFD->setInvalidDecl();
19836 }
19837 }
19838 }
19839
19840 // FIXME: We need to pass in the attributes given an AST
19841 // representation, not a parser representation.
19842 if (D) {
19843 // FIXME: The current scope is almost... but not entirely... correct here.
19844 ProcessDeclAttributes(S: getCurScope(), D: NewFD, PD: *D);
19845
19846 if (NewFD->hasAttrs())
19847 CheckAlignasUnderalignment(D: NewFD);
19848 }
19849
19850 // In auto-retain/release, infer strong retension for fields of
19851 // retainable type.
19852 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewFD))
19853 NewFD->setInvalidDecl();
19854
19855 if (T.isObjCGCWeak())
19856 Diag(Loc, DiagID: diag::warn_attribute_weak_on_field);
19857
19858 // PPC MMA non-pointer types are not allowed as field types.
19859 if (Context.getTargetInfo().getTriple().isPPC64() &&
19860 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewFD->getLocation()))
19861 NewFD->setInvalidDecl();
19862
19863 if (Context.getTargetInfo().hasAMDGPUTypes()) {
19864 if (!AMDGPU().checkAMDGPUTypeSupport(Ty: T, Loc: NewFD->getLocation()))
19865 NewFD->setInvalidDecl();
19866 }
19867
19868 NewFD->setAccess(AS);
19869 return NewFD;
19870}
19871
19872bool Sema::CheckNontrivialField(FieldDecl *FD) {
19873 assert(FD);
19874 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19875
19876 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19877 return false;
19878
19879 QualType EltTy = Context.getBaseElementType(QT: FD->getType());
19880 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19881 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19882 // We check for copy constructors before constructors
19883 // because otherwise we'll never get complaints about
19884 // copy constructors.
19885
19886 CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;
19887 // We're required to check for any non-trivial constructors. Since the
19888 // implicit default constructor is suppressed if there are any
19889 // user-declared constructors, we just need to check that there is a
19890 // trivial default constructor and a trivial copy constructor. (We don't
19891 // worry about move constructors here, since this is a C++98 check.)
19892 if (RDecl->hasNonTrivialCopyConstructor())
19893 member = CXXSpecialMemberKind::CopyConstructor;
19894 else if (!RDecl->hasTrivialDefaultConstructor())
19895 member = CXXSpecialMemberKind::DefaultConstructor;
19896 else if (RDecl->hasNonTrivialCopyAssignment())
19897 member = CXXSpecialMemberKind::CopyAssignment;
19898 else if (RDecl->hasNonTrivialDestructor())
19899 member = CXXSpecialMemberKind::Destructor;
19900
19901 if (member != CXXSpecialMemberKind::Invalid) {
19902 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19903 RDecl->hasObjectMember()) {
19904 // Objective-C++ ARC: it is an error to have a non-trivial field of
19905 // a union. However, system headers in Objective-C programs
19906 // occasionally have Objective-C lifetime objects within unions,
19907 // and rather than cause the program to fail, we make those
19908 // members unavailable.
19909 SourceLocation Loc = FD->getLocation();
19910 if (getSourceManager().isInSystemHeader(Loc)) {
19911 if (!FD->hasAttr<UnavailableAttr>())
19912 FD->addAttr(A: UnavailableAttr::CreateImplicit(
19913 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership, Range: Loc));
19914 return false;
19915 }
19916 }
19917
19918 Diag(Loc: FD->getLocation(),
19919 DiagID: getLangOpts().CPlusPlus11
19920 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19921 : diag::err_illegal_union_or_anon_struct_member)
19922 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19923 DiagnoseNontrivial(Record: RDecl, CSM: member);
19924 return !getLangOpts().CPlusPlus11;
19925 }
19926 }
19927
19928 return false;
19929}
19930
19931void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
19932 SmallVectorImpl<Decl *> &AllIvarDecls) {
19933 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19934 return;
19935
19936 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19937 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Val: ivarDecl);
19938
19939 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19940 return;
19941 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: CurContext);
19942 if (!ID) {
19943 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(Val: CurContext)) {
19944 if (!CD->IsClassExtension())
19945 return;
19946 }
19947 // No need to add this to end of @implementation.
19948 else
19949 return;
19950 }
19951 // All conditions are met. Add a new bitfield to the tail end of ivars.
19952 llvm::APInt Zero(Context.getTypeSize(T: Context.IntTy), 0);
19953 Expr * BW = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: DeclLoc);
19954 Expr *BitWidth =
19955 ConstantExpr::Create(Context, E: BW, Result: APValue(llvm::APSInt(Zero)));
19956
19957 Ivar = ObjCIvarDecl::Create(
19958 C&: Context, DC: cast<ObjCContainerDecl>(Val: CurContext), StartLoc: DeclLoc, IdLoc: DeclLoc, Id: nullptr,
19959 T: Context.CharTy, TInfo: Context.getTrivialTypeSourceInfo(T: Context.CharTy, Loc: DeclLoc),
19960 ac: ObjCIvarDecl::Private, BW: BitWidth, synthesized: true);
19961 AllIvarDecls.push_back(Elt: Ivar);
19962}
19963
19964/// [class.dtor]p4:
19965/// At the end of the definition of a class, overload resolution is
19966/// performed among the prospective destructors declared in that class with
19967/// an empty argument list to select the destructor for the class, also
19968/// known as the selected destructor.
19969///
19970/// We do the overload resolution here, then mark the selected constructor in the AST.
19971/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19972static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
19973 if (!Record->hasUserDeclaredDestructor()) {
19974 return;
19975 }
19976
19977 SourceLocation Loc = Record->getLocation();
19978 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
19979
19980 for (auto *Decl : Record->decls()) {
19981 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: Decl)) {
19982 if (DD->isInvalidDecl())
19983 continue;
19984 S.AddOverloadCandidate(Function: DD, FoundDecl: DeclAccessPair::make(D: DD, AS: DD->getAccess()), Args: {},
19985 CandidateSet&: OCS);
19986 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19987 }
19988 }
19989
19990 if (OCS.empty()) {
19991 return;
19992 }
19993 OverloadCandidateSet::iterator Best;
19994 unsigned Msg = 0;
19995 OverloadCandidateDisplayKind DisplayKind;
19996
19997 switch (OCS.BestViableFunction(S, Loc, Best)) {
19998 case OR_Success:
19999 case OR_Deleted:
20000 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: Best->Function));
20001 break;
20002
20003 case OR_Ambiguous:
20004 Msg = diag::err_ambiguous_destructor;
20005 DisplayKind = OCD_AmbiguousCandidates;
20006 break;
20007
20008 case OR_No_Viable_Function:
20009 Msg = diag::err_no_viable_destructor;
20010 DisplayKind = OCD_AllCandidates;
20011 break;
20012 }
20013
20014 if (Msg) {
20015 // OpenCL have got their own thing going with destructors. It's slightly broken,
20016 // but we allow it.
20017 if (!S.LangOpts.OpenCL) {
20018 PartialDiagnostic Diag = S.PDiag(DiagID: Msg) << Record;
20019 OCS.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, OCD: DisplayKind, Args: {});
20020 Record->setInvalidDecl();
20021 }
20022 // It's a bit hacky: At this point we've raised an error but we want the
20023 // rest of the compiler to continue somehow working. However almost
20024 // everything we'll try to do with the class will depend on there being a
20025 // destructor. So let's pretend the first one is selected and hope for the
20026 // best.
20027 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: OCS.begin()->Function));
20028 }
20029}
20030
20031/// [class.mem.special]p5
20032/// Two special member functions are of the same kind if:
20033/// - they are both default constructors,
20034/// - they are both copy or move constructors with the same first parameter
20035/// type, or
20036/// - they are both copy or move assignment operators with the same first
20037/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
20038static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
20039 CXXMethodDecl *M1,
20040 CXXMethodDecl *M2,
20041 CXXSpecialMemberKind CSM) {
20042 // We don't want to compare templates to non-templates: See
20043 // https://github.com/llvm/llvm-project/issues/59206
20044 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
20045 return bool(M1->getDescribedFunctionTemplate()) ==
20046 bool(M2->getDescribedFunctionTemplate());
20047 // FIXME: better resolve CWG
20048 // https://cplusplus.github.io/CWG/issues/2787.html
20049 if (!Context.hasSameType(T1: M1->getNonObjectParameter(I: 0)->getType(),
20050 T2: M2->getNonObjectParameter(I: 0)->getType()))
20051 return false;
20052 if (!Context.hasSameType(T1: M1->getFunctionObjectParameterReferenceType(),
20053 T2: M2->getFunctionObjectParameterReferenceType()))
20054 return false;
20055
20056 return true;
20057}
20058
20059/// [class.mem.special]p6:
20060/// An eligible special member function is a special member function for which:
20061/// - the function is not deleted,
20062/// - the associated constraints, if any, are satisfied, and
20063/// - no special member function of the same kind whose associated constraints
20064/// [CWG2595], if any, are satisfied is more constrained.
20065static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
20066 ArrayRef<CXXMethodDecl *> Methods,
20067 CXXSpecialMemberKind CSM) {
20068 SmallVector<bool, 4> SatisfactionStatus;
20069
20070 for (CXXMethodDecl *Method : Methods) {
20071 if (!Method->getTrailingRequiresClause())
20072 SatisfactionStatus.push_back(Elt: true);
20073 else {
20074 ConstraintSatisfaction Satisfaction;
20075 if (S.CheckFunctionConstraints(FD: Method, Satisfaction))
20076 SatisfactionStatus.push_back(Elt: false);
20077 else
20078 SatisfactionStatus.push_back(Elt: Satisfaction.IsSatisfied);
20079 }
20080 }
20081
20082 for (size_t i = 0; i < Methods.size(); i++) {
20083 if (!SatisfactionStatus[i])
20084 continue;
20085 CXXMethodDecl *Method = Methods[i];
20086 CXXMethodDecl *OrigMethod = Method;
20087 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
20088 OrigMethod = cast<CXXMethodDecl>(Val: MF);
20089
20090 AssociatedConstraint Orig = OrigMethod->getTrailingRequiresClause();
20091 bool AnotherMethodIsMoreConstrained = false;
20092 for (size_t j = 0; j < Methods.size(); j++) {
20093 if (i == j || !SatisfactionStatus[j])
20094 continue;
20095 CXXMethodDecl *OtherMethod = Methods[j];
20096 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
20097 OtherMethod = cast<CXXMethodDecl>(Val: MF);
20098
20099 if (!AreSpecialMemberFunctionsSameKind(Context&: S.Context, M1: OrigMethod, M2: OtherMethod,
20100 CSM))
20101 continue;
20102
20103 AssociatedConstraint Other = OtherMethod->getTrailingRequiresClause();
20104 if (!Other)
20105 continue;
20106 if (!Orig) {
20107 AnotherMethodIsMoreConstrained = true;
20108 break;
20109 }
20110 if (S.IsAtLeastAsConstrained(D1: OtherMethod, AC1: {Other}, D2: OrigMethod, AC2: {Orig},
20111 Result&: AnotherMethodIsMoreConstrained)) {
20112 // There was an error with the constraints comparison. Exit the loop
20113 // and don't consider this function eligible.
20114 AnotherMethodIsMoreConstrained = true;
20115 }
20116 if (AnotherMethodIsMoreConstrained)
20117 break;
20118 }
20119 // FIXME: Do not consider deleted methods as eligible after implementing
20120 // DR1734 and DR1496.
20121 if (!AnotherMethodIsMoreConstrained) {
20122 Method->setIneligibleOrNotSelected(false);
20123 Record->addedEligibleSpecialMemberFunction(MD: Method,
20124 SMKind: 1 << llvm::to_underlying(E: CSM));
20125 }
20126 }
20127}
20128
20129static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
20130 CXXRecordDecl *Record) {
20131 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
20132 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
20133 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
20134 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
20135 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
20136
20137 for (auto *Decl : Record->decls()) {
20138 auto *MD = dyn_cast<CXXMethodDecl>(Val: Decl);
20139 if (!MD) {
20140 auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Decl);
20141 if (FTD)
20142 MD = dyn_cast<CXXMethodDecl>(Val: FTD->getTemplatedDecl());
20143 }
20144 if (!MD)
20145 continue;
20146 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD)) {
20147 if (CD->isInvalidDecl())
20148 continue;
20149 if (CD->isDefaultConstructor())
20150 DefaultConstructors.push_back(Elt: MD);
20151 else if (CD->isCopyConstructor())
20152 CopyConstructors.push_back(Elt: MD);
20153 else if (CD->isMoveConstructor())
20154 MoveConstructors.push_back(Elt: MD);
20155 } else if (MD->isCopyAssignmentOperator()) {
20156 CopyAssignmentOperators.push_back(Elt: MD);
20157 } else if (MD->isMoveAssignmentOperator()) {
20158 MoveAssignmentOperators.push_back(Elt: MD);
20159 }
20160 }
20161
20162 SetEligibleMethods(S, Record, Methods: DefaultConstructors,
20163 CSM: CXXSpecialMemberKind::DefaultConstructor);
20164 SetEligibleMethods(S, Record, Methods: CopyConstructors,
20165 CSM: CXXSpecialMemberKind::CopyConstructor);
20166 SetEligibleMethods(S, Record, Methods: MoveConstructors,
20167 CSM: CXXSpecialMemberKind::MoveConstructor);
20168 SetEligibleMethods(S, Record, Methods: CopyAssignmentOperators,
20169 CSM: CXXSpecialMemberKind::CopyAssignment);
20170 SetEligibleMethods(S, Record, Methods: MoveAssignmentOperators,
20171 CSM: CXXSpecialMemberKind::MoveAssignment);
20172}
20173
20174bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
20175 // Check to see if a FieldDecl is a pointer to a function.
20176 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
20177 const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
20178 if (!FD) {
20179 // Check whether this is a forward declaration that was inserted by
20180 // Clang. This happens when a non-forward declared / defined type is
20181 // used, e.g.:
20182 //
20183 // struct foo {
20184 // struct bar *(*f)();
20185 // struct bar *(*g)();
20186 // };
20187 //
20188 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
20189 // incomplete definition.
20190 if (const auto *TD = dyn_cast<TagDecl>(Val: D))
20191 return !TD->isCompleteDefinition();
20192 return false;
20193 }
20194 QualType FieldType = FD->getType().getDesugaredType(Context);
20195 if (isa<PointerType>(Val: FieldType)) {
20196 QualType PointeeType = cast<PointerType>(Val&: FieldType)->getPointeeType();
20197 return PointeeType.getDesugaredType(Context)->isFunctionType();
20198 }
20199 // If a member is a struct entirely of function pointers, that counts too.
20200 if (const auto *Record = FieldType->getAsRecordDecl();
20201 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
20202 return true;
20203 return false;
20204 };
20205
20206 return llvm::all_of(Range: Record->decls(), P: IsFunctionPointerOrForwardDecl);
20207}
20208
20209void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
20210 ArrayRef<Decl *> Fields, SourceLocation LBrac,
20211 SourceLocation RBrac,
20212 const ParsedAttributesView &Attrs) {
20213 assert(EnclosingDecl && "missing record or interface decl");
20214
20215 // If this is an Objective-C @implementation or category and we have
20216 // new fields here we should reset the layout of the interface since
20217 // it will now change.
20218 if (!Fields.empty() && isa<ObjCContainerDecl>(Val: EnclosingDecl)) {
20219 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(Val: EnclosingDecl);
20220 switch (DC->getKind()) {
20221 default: break;
20222 case Decl::ObjCCategory:
20223 Context.ResetObjCLayout(D: cast<ObjCCategoryDecl>(Val: DC)->getClassInterface());
20224 break;
20225 case Decl::ObjCImplementation:
20226 Context.
20227 ResetObjCLayout(D: cast<ObjCImplementationDecl>(Val: DC)->getClassInterface());
20228 break;
20229 }
20230 }
20231
20232 RecordDecl *Record = dyn_cast<RecordDecl>(Val: EnclosingDecl);
20233 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Val: EnclosingDecl);
20234
20235 // Start counting up the number of named members; make sure to include
20236 // members of anonymous structs and unions in the total.
20237 unsigned NumNamedMembers = 0;
20238 if (Record) {
20239 for (const auto *I : Record->decls()) {
20240 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
20241 if (IFD->getDeclName())
20242 ++NumNamedMembers;
20243 }
20244 }
20245
20246 // Verify that all the fields are okay.
20247 SmallVector<FieldDecl*, 32> RecFields;
20248 const FieldDecl *PreviousField = nullptr;
20249 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
20250 i != end; PreviousField = cast<FieldDecl>(Val: *i), ++i) {
20251 FieldDecl *FD = cast<FieldDecl>(Val: *i);
20252
20253 // Get the type for the field.
20254 const Type *FDTy = FD->getType().getTypePtr();
20255
20256 if (!FD->isAnonymousStructOrUnion()) {
20257 // Remember all fields written by the user.
20258 RecFields.push_back(Elt: FD);
20259 }
20260
20261 // If the field is already invalid for some reason, don't emit more
20262 // diagnostics about it.
20263 if (FD->isInvalidDecl()) {
20264 EnclosingDecl->setInvalidDecl();
20265 continue;
20266 }
20267
20268 // C99 6.7.2.1p2:
20269 // A structure or union shall not contain a member with
20270 // incomplete or function type (hence, a structure shall not
20271 // contain an instance of itself, but may contain a pointer to
20272 // an instance of itself), except that the last member of a
20273 // structure with more than one named member may have incomplete
20274 // array type; such a structure (and any union containing,
20275 // possibly recursively, a member that is such a structure)
20276 // shall not be a member of a structure or an element of an
20277 // array.
20278 bool IsLastField = (i + 1 == Fields.end());
20279 if (FDTy->isFunctionType()) {
20280 // Field declared as a function.
20281 Diag(Loc: FD->getLocation(), DiagID: diag::err_field_declared_as_function)
20282 << FD->getDeclName();
20283 FD->setInvalidDecl();
20284 EnclosingDecl->setInvalidDecl();
20285 continue;
20286 } else if (FDTy->isIncompleteArrayType() &&
20287 (Record || isa<ObjCContainerDecl>(Val: EnclosingDecl))) {
20288 if (Record) {
20289 // Flexible array member.
20290 // Microsoft and g++ is more permissive regarding flexible array.
20291 // It will accept flexible array in union and also
20292 // as the sole element of a struct/class.
20293 unsigned DiagID = 0;
20294 if (!Record->isUnion() && !IsLastField) {
20295 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_not_at_end)
20296 << FD->getDeclName() << FD->getType() << Record->getTagKind();
20297 Diag(Loc: (*(i + 1))->getLocation(), DiagID: diag::note_next_field_declaration);
20298 FD->setInvalidDecl();
20299 EnclosingDecl->setInvalidDecl();
20300 continue;
20301 } else if (Record->isUnion())
20302 DiagID = getLangOpts().MicrosoftExt
20303 ? diag::ext_flexible_array_union_ms
20304 : diag::ext_flexible_array_union_gnu;
20305 else if (NumNamedMembers < 1)
20306 DiagID = getLangOpts().MicrosoftExt
20307 ? diag::ext_flexible_array_empty_aggregate_ms
20308 : diag::ext_flexible_array_empty_aggregate_gnu;
20309
20310 if (DiagID)
20311 Diag(Loc: FD->getLocation(), DiagID)
20312 << FD->getDeclName() << Record->getTagKind();
20313 // While the layout of types that contain virtual bases is not specified
20314 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
20315 // virtual bases after the derived members. This would make a flexible
20316 // array member declared at the end of an object not adjacent to the end
20317 // of the type.
20318 if (CXXRecord && CXXRecord->getNumVBases() != 0)
20319 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_virtual_base)
20320 << FD->getDeclName() << Record->getTagKind();
20321 if (!getLangOpts().C99)
20322 Diag(Loc: FD->getLocation(), DiagID: diag::ext_c99_flexible_array_member)
20323 << FD->getDeclName() << Record->getTagKind();
20324
20325 // If the element type has a non-trivial destructor, we would not
20326 // implicitly destroy the elements, so disallow it for now.
20327 //
20328 // FIXME: GCC allows this. We should probably either implicitly delete
20329 // the destructor of the containing class, or just allow this.
20330 QualType BaseElem = Context.getBaseElementType(QT: FD->getType());
20331 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
20332 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_has_nontrivial_dtor)
20333 << FD->getDeclName() << FD->getType();
20334 FD->setInvalidDecl();
20335 EnclosingDecl->setInvalidDecl();
20336 continue;
20337 }
20338 // Okay, we have a legal flexible array member at the end of the struct.
20339 Record->setHasFlexibleArrayMember(true);
20340 } else {
20341 // In ObjCContainerDecl ivars with incomplete array type are accepted,
20342 // unless they are followed by another ivar. That check is done
20343 // elsewhere, after synthesized ivars are known.
20344 }
20345 } else if (!FDTy->isDependentType() &&
20346 (LangOpts.HLSL // HLSL allows sizeless builtin types
20347 ? RequireCompleteType(Loc: FD->getLocation(), T: FD->getType(),
20348 DiagID: diag::err_incomplete_type)
20349 : RequireCompleteSizedType(
20350 Loc: FD->getLocation(), T: FD->getType(),
20351 DiagID: diag::err_field_incomplete_or_sizeless))) {
20352 // Incomplete type
20353 FD->setInvalidDecl();
20354 EnclosingDecl->setInvalidDecl();
20355 continue;
20356 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
20357 if (Record && RD->hasFlexibleArrayMember()) {
20358 // A type which contains a flexible array member is considered to be a
20359 // flexible array member.
20360 Record->setHasFlexibleArrayMember(true);
20361 if (!Record->isUnion()) {
20362 // If this is a struct/class and this is not the last element, reject
20363 // it. Note that GCC supports variable sized arrays in the middle of
20364 // structures.
20365 if (!IsLastField)
20366 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variable_sized_type_in_struct)
20367 << FD->getDeclName() << FD->getType();
20368 else {
20369 // We support flexible arrays at the end of structs in
20370 // other structs as an extension.
20371 Diag(Loc: FD->getLocation(), DiagID: diag::ext_flexible_array_in_struct)
20372 << FD->getDeclName();
20373 }
20374 }
20375 }
20376 if (isa<ObjCContainerDecl>(Val: EnclosingDecl) &&
20377 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getType(),
20378 DiagID: diag::err_abstract_type_in_decl,
20379 Args: AbstractIvarType)) {
20380 // Ivars can not have abstract class types
20381 FD->setInvalidDecl();
20382 }
20383 if (Record && RD->hasObjectMember())
20384 Record->setHasObjectMember(true);
20385 if (Record && RD->hasVolatileMember())
20386 Record->setHasVolatileMember(true);
20387 } else if (FDTy->isObjCObjectType()) {
20388 /// A field cannot be an Objective-c object
20389 Diag(Loc: FD->getLocation(), DiagID: diag::err_statically_allocated_object)
20390 << FixItHint::CreateInsertion(InsertionLoc: FD->getLocation(), Code: "*");
20391 QualType T = Context.getObjCObjectPointerType(OIT: FD->getType());
20392 FD->setType(T);
20393 } else if (Record && Record->isUnion() &&
20394 FD->getType().hasNonTrivialObjCLifetime() &&
20395 getSourceManager().isInSystemHeader(Loc: FD->getLocation()) &&
20396 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
20397 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
20398 !Context.hasDirectOwnershipQualifier(Ty: FD->getType()))) {
20399 // For backward compatibility, fields of C unions declared in system
20400 // headers that have non-trivial ObjC ownership qualifications are marked
20401 // as unavailable unless the qualifier is explicit and __strong. This can
20402 // break ABI compatibility between programs compiled with ARC and MRR, but
20403 // is a better option than rejecting programs using those unions under
20404 // ARC.
20405 FD->addAttr(A: UnavailableAttr::CreateImplicit(
20406 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership,
20407 Range: FD->getLocation()));
20408 } else if (getLangOpts().ObjC &&
20409 getLangOpts().getGC() != LangOptions::NonGC && Record &&
20410 !Record->hasObjectMember()) {
20411 if (FD->getType()->isObjCObjectPointerType() ||
20412 FD->getType().isObjCGCStrong())
20413 Record->setHasObjectMember(true);
20414 else if (Context.getAsArrayType(T: FD->getType())) {
20415 QualType BaseType = Context.getBaseElementType(QT: FD->getType());
20416 if (const auto *RD = BaseType->getAsRecordDecl();
20417 RD && RD->hasObjectMember())
20418 Record->setHasObjectMember(true);
20419 else if (BaseType->isObjCObjectPointerType() ||
20420 BaseType.isObjCGCStrong())
20421 Record->setHasObjectMember(true);
20422 }
20423 }
20424
20425 if (Record && !getLangOpts().CPlusPlus &&
20426 !shouldIgnoreForRecordTriviality(FD)) {
20427 QualType FT = FD->getType();
20428 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
20429 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
20430 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
20431 Record->isUnion())
20432 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
20433 }
20434 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
20435 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
20436 Record->setNonTrivialToPrimitiveCopy(true);
20437 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
20438 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
20439 }
20440 if (FD->hasAttr<ExplicitInitAttr>())
20441 Record->setHasUninitializedExplicitInitFields(true);
20442 if (FT.isDestructedType()) {
20443 Record->setNonTrivialToPrimitiveDestroy(true);
20444 Record->setParamDestroyedInCallee(true);
20445 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
20446 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
20447 }
20448
20449 if (const auto *RD = FT->getAsRecordDecl()) {
20450 if (RD->getArgPassingRestrictions() ==
20451 RecordArgPassingKind::CanNeverPassInRegs)
20452 Record->setArgPassingRestrictions(
20453 RecordArgPassingKind::CanNeverPassInRegs);
20454 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
20455 Record->setArgPassingRestrictions(
20456 RecordArgPassingKind::CanNeverPassInRegs);
20457 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
20458 Q && Q.isAddressDiscriminated()) {
20459 Record->setArgPassingRestrictions(
20460 RecordArgPassingKind::CanNeverPassInRegs);
20461 Record->setNonTrivialToPrimitiveCopy(true);
20462 }
20463 }
20464
20465 if (Record && FD->getType().isVolatileQualified())
20466 Record->setHasVolatileMember(true);
20467 bool ReportMSBitfieldStoragePacking =
20468 Record && PreviousField &&
20469 !Diags.isIgnored(DiagID: diag::warn_ms_bitfield_mismatched_storage_packing,
20470 Loc: Record->getLocation());
20471 auto IsNonDependentBitField = [](const FieldDecl *FD) {
20472 return FD->isBitField() && !FD->getType()->isDependentType();
20473 };
20474
20475 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
20476 IsNonDependentBitField(PreviousField)) {
20477 CharUnits FDStorageSize = Context.getTypeSizeInChars(T: FD->getType());
20478 CharUnits PreviousFieldStorageSize =
20479 Context.getTypeSizeInChars(T: PreviousField->getType());
20480 if (FDStorageSize != PreviousFieldStorageSize) {
20481 Diag(Loc: FD->getLocation(),
20482 DiagID: diag::warn_ms_bitfield_mismatched_storage_packing)
20483 << FD << FD->getType() << FDStorageSize.getQuantity()
20484 << PreviousFieldStorageSize.getQuantity();
20485 Diag(Loc: PreviousField->getLocation(),
20486 DiagID: diag::note_ms_bitfield_mismatched_storage_size_previous)
20487 << PreviousField << PreviousField->getType();
20488 }
20489 }
20490 // Keep track of the number of named members.
20491 if (FD->getIdentifier())
20492 ++NumNamedMembers;
20493 }
20494
20495 // Okay, we successfully defined 'Record'.
20496 if (Record) {
20497 bool Completed = false;
20498 if (S) {
20499 Scope *Parent = S->getParent();
20500 if (Parent && Parent->isTypeAliasScope() &&
20501 Parent->isTemplateParamScope())
20502 Record->setInvalidDecl();
20503 }
20504
20505 if (CXXRecord) {
20506 if (!CXXRecord->isInvalidDecl()) {
20507 // Set access bits correctly on the directly-declared conversions.
20508 for (CXXRecordDecl::conversion_iterator
20509 I = CXXRecord->conversion_begin(),
20510 E = CXXRecord->conversion_end(); I != E; ++I)
20511 I.setAccess((*I)->getAccess());
20512 }
20513
20514 // Add any implicitly-declared members to this class.
20515 AddImplicitlyDeclaredMembersToClass(ClassDecl: CXXRecord);
20516
20517 if (!CXXRecord->isDependentType()) {
20518 if (!CXXRecord->isInvalidDecl()) {
20519 // If we have virtual base classes, we may end up finding multiple
20520 // final overriders for a given virtual function. Check for this
20521 // problem now.
20522 if (CXXRecord->getNumVBases()) {
20523 CXXFinalOverriderMap FinalOverriders;
20524 CXXRecord->getFinalOverriders(FinaOverriders&: FinalOverriders);
20525
20526 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20527 MEnd = FinalOverriders.end();
20528 M != MEnd; ++M) {
20529 for (OverridingMethods::iterator SO = M->second.begin(),
20530 SOEnd = M->second.end();
20531 SO != SOEnd; ++SO) {
20532 assert(SO->second.size() > 0 &&
20533 "Virtual function without overriding functions?");
20534 if (SO->second.size() == 1)
20535 continue;
20536
20537 // C++ [class.virtual]p2:
20538 // In a derived class, if a virtual member function of a base
20539 // class subobject has more than one final overrider the
20540 // program is ill-formed.
20541 Diag(Loc: Record->getLocation(), DiagID: diag::err_multiple_final_overriders)
20542 << (const NamedDecl *)M->first << Record;
20543 Diag(Loc: M->first->getLocation(),
20544 DiagID: diag::note_overridden_virtual_function);
20545 for (OverridingMethods::overriding_iterator
20546 OM = SO->second.begin(),
20547 OMEnd = SO->second.end();
20548 OM != OMEnd; ++OM)
20549 Diag(Loc: OM->Method->getLocation(), DiagID: diag::note_final_overrider)
20550 << (const NamedDecl *)M->first << OM->Method->getParent();
20551
20552 Record->setInvalidDecl();
20553 }
20554 }
20555 CXXRecord->completeDefinition(FinalOverriders: &FinalOverriders);
20556 Completed = true;
20557 }
20558 }
20559 ComputeSelectedDestructor(S&: *this, Record: CXXRecord);
20560 ComputeSpecialMemberFunctionsEligiblity(S&: *this, Record: CXXRecord);
20561 }
20562 }
20563
20564 if (!Completed)
20565 Record->completeDefinition();
20566
20567 // Handle attributes before checking the layout.
20568 ProcessDeclAttributeList(S, D: Record, AttrList: Attrs);
20569
20570 // Maybe randomize the record's decls. We automatically randomize a record
20571 // of function pointers, unless it has the "no_randomize_layout" attribute.
20572 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20573 !Record->isRandomized() && !Record->isUnion() &&
20574 (Record->hasAttr<RandomizeLayoutAttr>() ||
20575 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20576 EntirelyFunctionPointers(Record)))) {
20577 SmallVector<Decl *, 32> NewDeclOrdering;
20578 if (randstruct::randomizeStructureLayout(Context, RD: Record,
20579 FinalOrdering&: NewDeclOrdering))
20580 Record->reorderDecls(Decls: NewDeclOrdering);
20581 }
20582
20583 // We may have deferred checking for a deleted destructor. Check now.
20584 if (CXXRecord) {
20585 auto *Dtor = CXXRecord->getDestructor();
20586 if (Dtor && Dtor->isImplicit() &&
20587 ShouldDeleteSpecialMember(MD: Dtor, CSM: CXXSpecialMemberKind::Destructor)) {
20588 CXXRecord->setImplicitDestructorIsDeleted();
20589 SetDeclDeleted(dcl: Dtor, DelLoc: CXXRecord->getLocation());
20590 }
20591 }
20592
20593 if (Record->hasAttrs()) {
20594 CheckAlignasUnderalignment(D: Record);
20595
20596 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20597 checkMSInheritanceAttrOnDefinition(RD: cast<CXXRecordDecl>(Val: Record),
20598 Range: IA->getRange(), BestCase: IA->getBestCase(),
20599 SemanticSpelling: IA->getInheritanceModel());
20600 }
20601
20602 // Check if the structure/union declaration is a type that can have zero
20603 // size in C. For C this is a language extension, for C++ it may cause
20604 // compatibility problems.
20605 bool CheckForZeroSize;
20606 if (!getLangOpts().CPlusPlus) {
20607 CheckForZeroSize = true;
20608 } else {
20609 // For C++ filter out types that cannot be referenced in C code.
20610 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record);
20611 CheckForZeroSize =
20612 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20613 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20614 CXXRecord->isCLike();
20615 }
20616 if (CheckForZeroSize) {
20617 bool ZeroSize = true;
20618 bool IsEmpty = true;
20619 unsigned NonBitFields = 0;
20620 for (RecordDecl::field_iterator I = Record->field_begin(),
20621 E = Record->field_end();
20622 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20623 IsEmpty = false;
20624 if (I->isUnnamedBitField()) {
20625 if (!I->isZeroLengthBitField())
20626 ZeroSize = false;
20627 } else {
20628 ++NonBitFields;
20629 QualType FieldType = I->getType();
20630 if (FieldType->isIncompleteType() ||
20631 !Context.getTypeSizeInChars(T: FieldType).isZero())
20632 ZeroSize = false;
20633 }
20634 }
20635
20636 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20637 // allowed in C++, but warn if its declaration is inside
20638 // extern "C" block.
20639 if (ZeroSize) {
20640 Diag(Loc: RecLoc, DiagID: getLangOpts().CPlusPlus ?
20641 diag::warn_zero_size_struct_union_in_extern_c :
20642 diag::warn_zero_size_struct_union_compat)
20643 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20644 }
20645
20646 // Structs without named members are extension in C (C99 6.7.2.1p7),
20647 // but are accepted by GCC. In C2y, this became implementation-defined
20648 // (C2y 6.7.3.2p10).
20649 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20650 Diag(Loc: RecLoc, DiagID: IsEmpty ? diag::ext_empty_struct_union
20651 : diag::ext_no_named_members_in_struct_union)
20652 << Record->isUnion();
20653 }
20654 }
20655 } else {
20656 ObjCIvarDecl **ClsFields =
20657 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20658 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: EnclosingDecl)) {
20659 ID->setEndOfDefinitionLoc(RBrac);
20660 // Add ivar's to class's DeclContext.
20661 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20662 ClsFields[i]->setLexicalDeclContext(ID);
20663 ID->addDecl(D: ClsFields[i]);
20664 }
20665 // Must enforce the rule that ivars in the base classes may not be
20666 // duplicates.
20667 if (ID->getSuperClass())
20668 ObjC().DiagnoseDuplicateIvars(ID, SID: ID->getSuperClass());
20669 } else if (ObjCImplementationDecl *IMPDecl =
20670 dyn_cast<ObjCImplementationDecl>(Val: EnclosingDecl)) {
20671 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20672 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20673 // Ivar declared in @implementation never belongs to the implementation.
20674 // Only it is in implementation's lexical context.
20675 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20676 ObjC().CheckImplementationIvars(ImpDecl: IMPDecl, Fields: ClsFields, nIvars: RecFields.size(),
20677 Loc: RBrac);
20678 IMPDecl->setIvarLBraceLoc(LBrac);
20679 IMPDecl->setIvarRBraceLoc(RBrac);
20680 } else if (ObjCCategoryDecl *CDecl =
20681 dyn_cast<ObjCCategoryDecl>(Val: EnclosingDecl)) {
20682 // case of ivars in class extension; all other cases have been
20683 // reported as errors elsewhere.
20684 // FIXME. Class extension does not have a LocEnd field.
20685 // CDecl->setLocEnd(RBrac);
20686 // Add ivar's to class extension's DeclContext.
20687 // Diagnose redeclaration of private ivars.
20688 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20689 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20690 if (IDecl) {
20691 if (const ObjCIvarDecl *ClsIvar =
20692 IDecl->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20693 Diag(Loc: ClsFields[i]->getLocation(),
20694 DiagID: diag::err_duplicate_ivar_declaration);
20695 Diag(Loc: ClsIvar->getLocation(), DiagID: diag::note_previous_definition);
20696 continue;
20697 }
20698 for (const auto *Ext : IDecl->known_extensions()) {
20699 if (const ObjCIvarDecl *ClsExtIvar
20700 = Ext->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20701 Diag(Loc: ClsFields[i]->getLocation(),
20702 DiagID: diag::err_duplicate_ivar_declaration);
20703 Diag(Loc: ClsExtIvar->getLocation(), DiagID: diag::note_previous_definition);
20704 continue;
20705 }
20706 }
20707 }
20708 ClsFields[i]->setLexicalDeclContext(CDecl);
20709 CDecl->addDecl(D: ClsFields[i]);
20710 }
20711 CDecl->setIvarLBraceLoc(LBrac);
20712 CDecl->setIvarRBraceLoc(RBrac);
20713 }
20714 }
20715
20716 if (Record)
20717 AMDGPU().checkNamedBarrierWrapper(R: Record);
20718
20719 if (Record && !isa<ClassTemplateSpecializationDecl>(Val: Record))
20720 ProcessAPINotes(D: Record);
20721}
20722
20723// Given an integral type, return the next larger integral type
20724// (or a NULL type of no such type exists).
20725static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
20726 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20727 // enum checking below.
20728 assert((T->isIntegralType(Context) ||
20729 T->isEnumeralType()) && "Integral type required!");
20730 const unsigned NumTypes = 4;
20731 QualType SignedIntegralTypes[NumTypes] = {
20732 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20733 };
20734 QualType UnsignedIntegralTypes[NumTypes] = {
20735 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20736 Context.UnsignedLongLongTy
20737 };
20738
20739 // Compare value widths, not storage sizes: a _BitInt(33) is stored in 64
20740 // bits but a 64-bit standard type can still represent its incremented
20741 // value. C23 6.7.3.3p12 does not allow the widened type to be a
20742 // bit-precise type either.
20743 unsigned BitWidth = Context.getIntWidth(T);
20744 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20745 : UnsignedIntegralTypes;
20746 for (unsigned I = 0; I != NumTypes; ++I)
20747 if (Context.getTypeSize(T: Types[I]) > BitWidth)
20748 return Types[I];
20749
20750 return QualType();
20751}
20752
20753EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
20754 EnumConstantDecl *LastEnumConst,
20755 SourceLocation IdLoc,
20756 IdentifierInfo *Id,
20757 Expr *Val) {
20758 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20759 llvm::APSInt EnumVal(IntWidth);
20760 QualType EltTy;
20761
20762 if (Val && DiagnoseUnexpandedParameterPack(E: Val, UPPC: UPPC_EnumeratorValue))
20763 Val = nullptr;
20764
20765 if (Val)
20766 Val = DefaultLvalueConversion(E: Val).get();
20767
20768 if (Val) {
20769 if (Enum->isDependentType() || Val->isTypeDependent() ||
20770 Val->containsErrors())
20771 EltTy = Context.DependentTy;
20772 else {
20773 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20774 // underlying type, but do allow it in all other contexts.
20775 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20776 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20777 // constant-expression in the enumerator-definition shall be a converted
20778 // constant expression of the underlying type.
20779 EltTy = Enum->getIntegerType();
20780 ExprResult Converted = CheckConvertedConstantExpression(
20781 From: Val, T: EltTy, Value&: EnumVal, CCE: CCEKind::Enumerator);
20782 if (Converted.isInvalid())
20783 Val = nullptr;
20784 else
20785 Val = Converted.get();
20786 } else if (!Val->isValueDependent() &&
20787 !(Val = VerifyIntegerConstantExpression(E: Val, Result: &EnumVal,
20788 CanFold: AllowFoldKind::Allow)
20789 .get())) {
20790 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20791 } else {
20792 if (Enum->isComplete()) {
20793 EltTy = Enum->getIntegerType();
20794
20795 // In Obj-C and Microsoft mode, require the enumeration value to be
20796 // representable in the underlying type of the enumeration. In C++11,
20797 // we perform a non-narrowing conversion as part of converted constant
20798 // expression checking.
20799 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20800 if (Context.getTargetInfo()
20801 .getTriple()
20802 .isWindowsMSVCEnvironment()) {
20803 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_too_large) << EltTy;
20804 } else {
20805 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_too_large) << EltTy;
20806 }
20807 }
20808
20809 // Cast to the underlying type.
20810 Val = ImpCastExprToType(E: Val, Type: EltTy,
20811 CK: EltTy->isBooleanType() ? CK_IntegralToBoolean
20812 : CK_IntegralCast)
20813 .get();
20814 } else if (getLangOpts().CPlusPlus) {
20815 // C++11 [dcl.enum]p5:
20816 // If the underlying type is not fixed, the type of each enumerator
20817 // is the type of its initializing value:
20818 // - If an initializer is specified for an enumerator, the
20819 // initializing value has the same type as the expression.
20820 EltTy = Val->getType();
20821 } else {
20822 // C99 6.7.2.2p2:
20823 // The expression that defines the value of an enumeration constant
20824 // shall be an integer constant expression that has a value
20825 // representable as an int.
20826
20827 // Complain if the value is not representable in an int.
20828 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: Context.IntTy)) {
20829 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20830 ? diag::warn_c17_compat_enum_value_not_int
20831 : diag::ext_c23_enum_value_not_int)
20832 << 0 << toString(I: EnumVal, Radix: 10) << Val->getSourceRange()
20833 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20834 } else if (!Context.hasSameType(T1: Val->getType(), T2: Context.IntTy)) {
20835 // Force the type of the expression to 'int'.
20836 Val = ImpCastExprToType(E: Val, Type: Context.IntTy, CK: CK_IntegralCast).get();
20837 }
20838 EltTy = Val->getType();
20839 }
20840 }
20841 }
20842 }
20843
20844 if (!Val) {
20845 if (Enum->isDependentType())
20846 EltTy = Context.DependentTy;
20847 else if (!LastEnumConst) {
20848 // C++0x [dcl.enum]p5:
20849 // If the underlying type is not fixed, the type of each enumerator
20850 // is the type of its initializing value:
20851 // - If no initializer is specified for the first enumerator, the
20852 // initializing value has an unspecified integral type.
20853 //
20854 // GCC uses 'int' for its unspecified integral type, as does
20855 // C99 6.7.2.2p3.
20856 if (Enum->isFixed()) {
20857 EltTy = Enum->getIntegerType();
20858 }
20859 else {
20860 EltTy = Context.IntTy;
20861 }
20862 } else {
20863 // Assign the last value + 1.
20864 EnumVal = LastEnumConst->getInitVal();
20865 ++EnumVal;
20866 EltTy = LastEnumConst->getType();
20867
20868 // Check for overflow on increment.
20869 if (EnumVal < LastEnumConst->getInitVal()) {
20870 // C++0x [dcl.enum]p5:
20871 // If the underlying type is not fixed, the type of each enumerator
20872 // is the type of its initializing value:
20873 //
20874 // - Otherwise the type of the initializing value is the same as
20875 // the type of the initializing value of the preceding enumerator
20876 // unless the incremented value is not representable in that type,
20877 // in which case the type is an unspecified integral type
20878 // sufficient to contain the incremented value. If no such type
20879 // exists, the program is ill-formed.
20880 QualType T = getNextLargerIntegralType(Context, T: EltTy);
20881 if (T.isNull() || Enum->isFixed()) {
20882 // There is no integral type larger enough to represent this
20883 // value. Complain, then allow the value to wrap around.
20884 EnumVal = LastEnumConst->getInitVal();
20885 EnumVal = EnumVal.zext(width: EnumVal.getBitWidth() * 2);
20886 ++EnumVal;
20887 if (Enum->isFixed())
20888 // When the underlying type is fixed, this is ill-formed.
20889 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_wrapped)
20890 << toString(I: EnumVal, Radix: 10)
20891 << EltTy;
20892 else
20893 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_increment_too_large)
20894 << toString(I: EnumVal, Radix: 10);
20895 } else {
20896 EltTy = T;
20897 }
20898
20899 // Retrieve the last enumerator's value, extent that type to the
20900 // type that is supposed to be large enough to represent the incremented
20901 // value, then increment.
20902 EnumVal = LastEnumConst->getInitVal();
20903 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20904 EnumVal = EnumVal.zextOrTrunc(width: Context.getIntWidth(T: EltTy));
20905 ++EnumVal;
20906
20907 // If we're not in C++, diagnose the overflow of enumerator values,
20908 // which in C99 means that the enumerator value is not representable in
20909 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20910 // are representable in some larger integral type and we allow it in
20911 // older language modes as an extension.
20912 // Exclude fixed enumerators since they are diagnosed with an error for
20913 // this case.
20914 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20915 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20916 ? diag::warn_c17_compat_enum_value_not_int
20917 : diag::ext_c23_enum_value_not_int)
20918 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20919 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20920 !Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20921 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20922 Diag(Loc: IdLoc, DiagID: getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20923 : diag::ext_c23_enum_value_not_int)
20924 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20925 }
20926 }
20927 }
20928
20929 if (!EltTy->isDependentType()) {
20930 // Make the enumerator value match the signedness and size of the
20931 // enumerator's type.
20932 EnumVal = EnumVal.extOrTrunc(width: Context.getIntWidth(T: EltTy));
20933 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20934 }
20935
20936 return EnumConstantDecl::Create(C&: Context, DC: Enum, L: IdLoc, Id, T: EltTy,
20937 E: Val, V: EnumVal);
20938}
20939
20940SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
20941 SourceLocation IILoc) {
20942 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20943 !getLangOpts().CPlusPlus)
20944 return SkipBodyInfo();
20945
20946 // We have an anonymous enum definition. Look up the first enumerator to
20947 // determine if we should merge the definition with an existing one and
20948 // skip the body.
20949 NamedDecl *PrevDecl = LookupSingleName(S, Name: II, Loc: IILoc, NameKind: LookupOrdinaryName,
20950 Redecl: forRedeclarationInCurContext());
20951 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(Val: PrevDecl);
20952 if (!PrevECD)
20953 return SkipBodyInfo();
20954
20955 EnumDecl *PrevED = cast<EnumDecl>(Val: PrevECD->getDeclContext());
20956 NamedDecl *Hidden;
20957 if (!PrevED->getDeclName() && !hasVisibleDefinition(D: PrevED, Suggested: &Hidden)) {
20958 SkipBodyInfo Skip;
20959 Skip.Previous = Hidden;
20960 return Skip;
20961 }
20962
20963 return SkipBodyInfo();
20964}
20965
20966Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20967 SourceLocation IdLoc, IdentifierInfo *Id,
20968 const ParsedAttributesView &Attrs,
20969 SourceLocation EqualLoc, Expr *Val,
20970 SkipBodyInfo *SkipBody) {
20971 EnumDecl *TheEnumDecl = cast<EnumDecl>(Val: theEnumDecl);
20972 EnumConstantDecl *LastEnumConst =
20973 cast_or_null<EnumConstantDecl>(Val: lastEnumConst);
20974
20975 // The scope passed in may not be a decl scope. Zip up the scope tree until
20976 // we find one that is.
20977 S = getNonFieldDeclScope(S);
20978
20979 // Verify that there isn't already something declared with this name in this
20980 // scope.
20981 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20982 RedeclarationKind::ForVisibleRedeclaration);
20983 LookupName(R, S);
20984 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20985
20986 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20987 // Maybe we will complain about the shadowed template parameter.
20988 DiagnoseTemplateParameterShadow(Loc: IdLoc, PrevDecl);
20989 // Just pretend that we didn't see the previous declaration.
20990 PrevDecl = nullptr;
20991 }
20992
20993 // C++ [class.mem]p15:
20994 // If T is the name of a class, then each of the following shall have a name
20995 // different from T:
20996 // - every enumerator of every member of class T that is an unscoped
20997 // enumerated type
20998 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20999 DiagnoseClassNameShadow(DC: TheEnumDecl->getDeclContext(),
21000 NameInfo: DeclarationNameInfo(Id, IdLoc)))
21001 return nullptr;
21002
21003 EnumConstantDecl *New =
21004 CheckEnumConstant(Enum: TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
21005 if (!New)
21006 return nullptr;
21007
21008 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
21009 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(Val: PrevDecl)) {
21010 // Check for other kinds of shadowing not already handled.
21011 CheckShadow(D: New, ShadowedDecl: PrevDecl, R);
21012 }
21013
21014 // When in C++, we may get a TagDecl with the same name; in this case the
21015 // enum constant will 'hide' the tag.
21016 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
21017 "Received TagDecl when not in C++!");
21018 if (!isa<TagDecl>(Val: PrevDecl) && isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
21019 if (isa<EnumConstantDecl>(Val: PrevDecl))
21020 Diag(Loc: IdLoc, DiagID: diag::err_redefinition_of_enumerator) << Id;
21021 else
21022 Diag(Loc: IdLoc, DiagID: diag::err_redefinition) << Id;
21023 notePreviousDefinition(Old: PrevDecl, New: IdLoc);
21024 return nullptr;
21025 }
21026 }
21027
21028 // Process attributes.
21029 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
21030 AddPragmaAttributes(S, D: New);
21031 ProcessAPINotes(D: New);
21032
21033 // Register this decl in the current scope stack.
21034 New->setAccess(TheEnumDecl->getAccess());
21035 PushOnScopeChains(D: New, S);
21036
21037 ActOnDocumentableDecl(D: New);
21038
21039 return New;
21040}
21041
21042// Returns true when the enum initial expression does not trigger the
21043// duplicate enum warning. A few common cases are exempted as follows:
21044// Element2 = Element1
21045// Element2 = Element1 + 1
21046// Element2 = Element1 - 1
21047// Where Element2 and Element1 are from the same enum.
21048static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
21049 Expr *InitExpr = ECD->getInitExpr();
21050 if (!InitExpr)
21051 return true;
21052 InitExpr = InitExpr->IgnoreImpCasts();
21053
21054 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: InitExpr)) {
21055 if (!BO->isAdditiveOp())
21056 return true;
21057 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: BO->getRHS());
21058 if (!IL)
21059 return true;
21060 if (IL->getValue() != 1)
21061 return true;
21062
21063 InitExpr = BO->getLHS();
21064 }
21065
21066 // This checks if the elements are from the same enum.
21067 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InitExpr);
21068 if (!DRE)
21069 return true;
21070
21071 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(Val: DRE->getDecl());
21072 if (!EnumConstant)
21073 return true;
21074
21075 if (cast<EnumDecl>(Val: TagDecl::castFromDeclContext(DC: ECD->getDeclContext())) !=
21076 Enum)
21077 return true;
21078
21079 return false;
21080}
21081
21082// Emits a warning when an element is implicitly set a value that
21083// a previous element has already been set to.
21084static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
21085 EnumDecl *Enum, QualType EnumType) {
21086 // Avoid anonymous enums
21087 if (!Enum->getIdentifier())
21088 return;
21089
21090 // Only check for small enums.
21091 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
21092 return;
21093
21094 if (S.Diags.isIgnored(DiagID: diag::warn_duplicate_enum_values, Loc: Enum->getLocation()))
21095 return;
21096
21097 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
21098 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
21099
21100 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
21101
21102 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
21103 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
21104
21105 // Use int64_t as a key to avoid needing special handling for map keys.
21106 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
21107 llvm::APSInt Val = D->getInitVal();
21108 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
21109 };
21110
21111 DuplicatesVector DupVector;
21112 ValueToVectorMap EnumMap;
21113
21114 // Populate the EnumMap with all values represented by enum constants without
21115 // an initializer.
21116 for (auto *Element : Elements) {
21117 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: Element);
21118
21119 // Null EnumConstantDecl means a previous diagnostic has been emitted for
21120 // this constant. Skip this enum since it may be ill-formed.
21121 if (!ECD) {
21122 return;
21123 }
21124
21125 // Constants with initializers are handled in the next loop.
21126 if (ECD->getInitExpr())
21127 continue;
21128
21129 // Duplicate values are handled in the next loop.
21130 EnumMap.insert(x: {EnumConstantToKey(ECD), ECD});
21131 }
21132
21133 if (EnumMap.size() == 0)
21134 return;
21135
21136 // Create vectors for any values that has duplicates.
21137 for (auto *Element : Elements) {
21138 // The last loop returned if any constant was null.
21139 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Val: Element);
21140 if (!ValidDuplicateEnum(ECD, Enum))
21141 continue;
21142
21143 auto Iter = EnumMap.find(x: EnumConstantToKey(ECD));
21144 if (Iter == EnumMap.end())
21145 continue;
21146
21147 DeclOrVector& Entry = Iter->second;
21148 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Val&: Entry)) {
21149 // Ensure constants are different.
21150 if (D == ECD)
21151 continue;
21152
21153 // Create new vector and push values onto it.
21154 auto Vec = std::make_unique<ECDVector>();
21155 Vec->push_back(Elt: D);
21156 Vec->push_back(Elt: ECD);
21157
21158 // Update entry to point to the duplicates vector.
21159 Entry = Vec.get();
21160
21161 // Store the vector somewhere we can consult later for quick emission of
21162 // diagnostics.
21163 DupVector.emplace_back(Args: std::move(Vec));
21164 continue;
21165 }
21166
21167 ECDVector *Vec = cast<ECDVector *>(Val&: Entry);
21168 // Make sure constants are not added more than once.
21169 if (*Vec->begin() == ECD)
21170 continue;
21171
21172 Vec->push_back(Elt: ECD);
21173 }
21174
21175 // Emit diagnostics.
21176 for (const auto &Vec : DupVector) {
21177 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
21178
21179 // Emit warning for one enum constant.
21180 auto *FirstECD = Vec->front();
21181 S.Diag(Loc: FirstECD->getLocation(), DiagID: diag::warn_duplicate_enum_values)
21182 << FirstECD << toString(I: FirstECD->getInitVal(), Radix: 10)
21183 << FirstECD->getSourceRange();
21184
21185 // Emit one note for each of the remaining enum constants with
21186 // the same value.
21187 for (auto *ECD : llvm::drop_begin(RangeOrContainer&: *Vec))
21188 S.Diag(Loc: ECD->getLocation(), DiagID: diag::note_duplicate_element)
21189 << ECD << toString(I: ECD->getInitVal(), Radix: 10)
21190 << ECD->getSourceRange();
21191 }
21192}
21193
21194bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
21195 bool AllowMask) const {
21196 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
21197 assert(ED->isCompleteDefinition() && "expected enum definition");
21198
21199 auto R = FlagBitsCache.try_emplace(Key: ED);
21200 llvm::APInt &FlagBits = R.first->second;
21201
21202 if (R.second) {
21203 for (auto *E : ED->enumerators()) {
21204 const auto &EVal = E->getInitVal();
21205 // Only single-bit enumerators introduce new flag values.
21206 if (EVal.isPowerOf2())
21207 FlagBits = FlagBits.zext(width: EVal.getBitWidth()) | EVal;
21208 }
21209 }
21210
21211 // A value is in a flag enum if either its bits are a subset of the enum's
21212 // flag bits (the first condition) or we are allowing masks and the same is
21213 // true of its complement (the second condition). When masks are allowed, we
21214 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
21215 //
21216 // While it's true that any value could be used as a mask, the assumption is
21217 // that a mask will have all of the insignificant bits set. Anything else is
21218 // likely a logic error.
21219 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(width: Val.getBitWidth());
21220 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
21221}
21222
21223// Emits a warning when a suspicious comparison operator is used along side
21224// binary operators in enum initializers.
21225static void CheckForComparisonInEnumInitializer(SemaBase &Sema,
21226 const EnumDecl *Enum) {
21227 bool HasBitwiseOp = false;
21228 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
21229
21230 // Iterate over all the enum values, gather suspisious comparison ops and
21231 // whether any enum initialisers contain a binary operator.
21232 for (const auto *ECD : Enum->enumerators()) {
21233 const Expr *InitExpr = ECD->getInitExpr();
21234 if (!InitExpr)
21235 continue;
21236
21237 const Expr *E = InitExpr->IgnoreParenImpCasts();
21238
21239 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: E)) {
21240 BinaryOperatorKind Op = BinOp->getOpcode();
21241
21242 // Check for bitwise ops (<<, >>, &, |)
21243 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
21244 HasBitwiseOp = true;
21245 } else if (Op == BO_LT || Op == BO_GT) {
21246 // Check for the typo pattern (Comparison < or >)
21247 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
21248 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(Val: LHS)) {
21249 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
21250 if (IntLiteral->getValue() == 1)
21251 SuspiciousCompares.push_back(Elt: BinOp);
21252 }
21253 }
21254 }
21255 }
21256
21257 // If we found a bitwise op and some sus compares, iterate over the compares
21258 // and warn.
21259 if (HasBitwiseOp) {
21260 for (const auto *BinOp : SuspiciousCompares) {
21261 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
21262 ? BinaryOperator::getOpcodeStr(Op: BO_Shl)
21263 : BinaryOperator::getOpcodeStr(Op: BO_Shr);
21264 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
21265
21266 Sema.Diag(Loc: OperatorLoc, DiagID: diag::warn_comparison_in_enum_initializer)
21267 << BinOp->getOpcodeStr() << SuggestedOp;
21268
21269 Sema.Diag(Loc: OperatorLoc, DiagID: diag::note_enum_compare_typo_suggest)
21270 << SuggestedOp
21271 << FixItHint::CreateReplacement(RemoveRange: OperatorLoc, Code: SuggestedOp);
21272 }
21273 }
21274}
21275
21276void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
21277 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
21278 const ParsedAttributesView &Attrs) {
21279 EnumDecl *Enum = cast<EnumDecl>(Val: EnumDeclX);
21280 CanQualType EnumType = Context.getCanonicalTagType(TD: Enum);
21281
21282 ProcessDeclAttributeList(S, D: Enum, AttrList: Attrs);
21283 ProcessAPINotes(D: Enum);
21284
21285 if (Enum->isDependentType()) {
21286 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
21287 EnumConstantDecl *ECD =
21288 cast_or_null<EnumConstantDecl>(Val: Elements[i]);
21289 if (!ECD) continue;
21290
21291 ECD->setType(EnumType);
21292 }
21293
21294 Enum->completeDefinition(NewType: Context.DependentTy, PromotionType: Context.DependentTy, NumPositiveBits: 0, NumNegativeBits: 0);
21295 return;
21296 }
21297
21298 // Verify that all the values are okay, compute the size of the values, and
21299 // reverse the list.
21300 unsigned NumNegativeBits = 0;
21301 unsigned NumPositiveBits = 0;
21302 bool MembersRepresentableByInt =
21303 Context.computeEnumBits(EnumConstants: Elements, NumNegativeBits, NumPositiveBits);
21304
21305 // Figure out the type that should be used for this enum.
21306 QualType BestType;
21307 unsigned BestWidth;
21308
21309 // C++0x N3000 [conv.prom]p3:
21310 // An rvalue of an unscoped enumeration type whose underlying
21311 // type is not fixed can be converted to an rvalue of the first
21312 // of the following types that can represent all the values of
21313 // the enumeration: int, unsigned int, long int, unsigned long
21314 // int, long long int, or unsigned long long int.
21315 // C99 6.4.4.3p2:
21316 // An identifier declared as an enumeration constant has type int.
21317 // The C99 rule is modified by C23.
21318 QualType BestPromotionType;
21319
21320 bool Packed = Enum->hasAttr<PackedAttr>();
21321 // -fshort-enums is the equivalent to specifying the packed attribute on all
21322 // enum definitions.
21323 if (LangOpts.ShortEnums)
21324 Packed = true;
21325
21326 // If the enum already has a type because it is fixed or dictated by the
21327 // target, promote that type instead of analyzing the enumerators.
21328 if (Enum->isComplete()) {
21329 BestType = Enum->getIntegerType();
21330 if (Context.isPromotableIntegerType(T: BestType))
21331 BestPromotionType = Context.getPromotedIntegerType(PromotableType: BestType);
21332 else
21333 BestPromotionType = BestType;
21334
21335 BestWidth = Context.getIntWidth(T: BestType);
21336 } else {
21337 bool EnumTooLarge = Context.computeBestEnumTypes(
21338 IsPacked: Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
21339 BestWidth = Context.getIntWidth(T: BestType);
21340 if (EnumTooLarge)
21341 Diag(Loc: Enum->getLocation(), DiagID: diag::ext_enum_too_large);
21342 }
21343
21344 // Loop over all of the enumerator constants, changing their types to match
21345 // the type of the enum if needed.
21346 for (auto *D : Elements) {
21347 auto *ECD = cast_or_null<EnumConstantDecl>(Val: D);
21348 if (!ECD) continue; // Already issued a diagnostic.
21349
21350 // C99 says the enumerators have int type, but we allow, as an
21351 // extension, the enumerators to be larger than int size. If each
21352 // enumerator value fits in an int, type it as an int, otherwise type it the
21353 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
21354 // that X has type 'int', not 'unsigned'.
21355
21356 // Determine whether the value fits into an int.
21357 llvm::APSInt InitVal = ECD->getInitVal();
21358
21359 // If it fits into an integer type, force it. Otherwise force it to match
21360 // the enum decl type.
21361 QualType NewTy;
21362 unsigned NewWidth;
21363 bool NewSign;
21364 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
21365 MembersRepresentableByInt) {
21366 // C23 6.7.3.3.3p15:
21367 // The enumeration member type for an enumerated type without fixed
21368 // underlying type upon completion is:
21369 // - int if all the values of the enumeration are representable as an
21370 // int; or,
21371 // - the enumerated type
21372 NewTy = Context.IntTy;
21373 NewWidth = Context.getTargetInfo().getIntWidth();
21374 NewSign = true;
21375 } else if (ECD->getType() == BestType) {
21376 // Already the right type!
21377 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
21378 // C++ [dcl.enum]p4: Following the closing brace of an
21379 // enum-specifier, each enumerator has the type of its
21380 // enumeration.
21381 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21382 // with fixed underlying type is the enumerated type.
21383 ECD->setType(EnumType);
21384 continue;
21385 } else {
21386 NewTy = BestType;
21387 NewWidth = BestWidth;
21388 NewSign = BestType->isSignedIntegerOrEnumerationType();
21389 }
21390
21391 // Adjust the APSInt value.
21392 InitVal = InitVal.extOrTrunc(width: NewWidth);
21393 InitVal.setIsSigned(NewSign);
21394 ECD->setInitVal(C: Context, V: InitVal);
21395
21396 // Adjust the Expr initializer and type.
21397 if (ECD->getInitExpr() &&
21398 !Context.hasSameType(T1: NewTy, T2: ECD->getInitExpr()->getType()))
21399 ECD->setInitExpr(ImplicitCastExpr::Create(
21400 Context, T: NewTy, Kind: CK_IntegralCast, Operand: ECD->getInitExpr(),
21401 /*base paths*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()));
21402 if (getLangOpts().CPlusPlus ||
21403 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
21404 // C++ [dcl.enum]p4: Following the closing brace of an
21405 // enum-specifier, each enumerator has the type of its
21406 // enumeration.
21407 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21408 // with fixed underlying type is the enumerated type.
21409 ECD->setType(EnumType);
21410 else
21411 ECD->setType(NewTy);
21412 }
21413
21414 Enum->completeDefinition(NewType: BestType, PromotionType: BestPromotionType,
21415 NumPositiveBits, NumNegativeBits);
21416
21417 CheckForDuplicateEnumValues(S&: *this, Elements, Enum, EnumType);
21418 CheckForComparisonInEnumInitializer(Sema&: *this, Enum);
21419
21420 if (Enum->isClosedFlag()) {
21421 for (Decl *D : Elements) {
21422 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: D);
21423 if (!ECD) continue; // Already issued a diagnostic.
21424
21425 llvm::APSInt InitVal = ECD->getInitVal();
21426 if (InitVal != 0 && !InitVal.isPowerOf2() &&
21427 !IsValueInFlagEnum(ED: Enum, Val: InitVal, AllowMask: true))
21428 Diag(Loc: ECD->getLocation(), DiagID: diag::warn_flag_enum_constant_out_of_range)
21429 << ECD << Enum;
21430 }
21431 }
21432
21433 // Now that the enum type is defined, ensure it's not been underaligned.
21434 if (Enum->hasAttrs())
21435 CheckAlignasUnderalignment(D: Enum);
21436}
21437
21438Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, SourceLocation StartLoc,
21439 SourceLocation EndLoc) {
21440
21441 FileScopeAsmDecl *New =
21442 FileScopeAsmDecl::Create(C&: Context, DC: CurContext, Str: expr, AsmLoc: StartLoc, RParenLoc: EndLoc);
21443 CurContext->addDecl(D: New);
21444 return New;
21445}
21446
21447TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {
21448 auto *New = TopLevelStmtDecl::Create(C&: Context, /*Statement=*/nullptr);
21449 CurContext->addDecl(D: New);
21450 PushDeclContext(S, DC: New);
21451 PushFunctionScope();
21452 PushCompoundScope(IsStmtExpr: false);
21453 return New;
21454}
21455
21456void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {
21457 if (Statement)
21458 D->setStmt(Statement);
21459 PopCompoundScope();
21460 PopFunctionScopeInfo();
21461 PopDeclContext();
21462}
21463
21464void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
21465 IdentifierInfo* AliasName,
21466 SourceLocation PragmaLoc,
21467 SourceLocation NameLoc,
21468 SourceLocation AliasNameLoc) {
21469 NamedDecl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc,
21470 NameKind: LookupOrdinaryName);
21471 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
21472 AttributeCommonInfo::Form::Pragma());
21473 AsmLabelAttr *Attr =
21474 AsmLabelAttr::CreateImplicit(Ctx&: Context, Label: AliasName->getName(), CommonInfo: Info);
21475
21476 // If a declaration that:
21477 // 1) declares a function or a variable
21478 // 2) has external linkage
21479 // already exists, add a label attribute to it.
21480 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21481 if (isDeclExternC(D: PrevDecl))
21482 PrevDecl->addAttr(A: Attr);
21483 else
21484 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
21485 << /*Variable*/(isa<FunctionDecl>(Val: PrevDecl) ? 0 : 1) << PrevDecl;
21486 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
21487 } else
21488 (void)ExtnameUndeclaredIdentifiers.insert(KV: std::make_pair(x&: Name, y&: Attr));
21489}
21490
21491void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
21492 SourceLocation PragmaLoc,
21493 SourceLocation NameLoc) {
21494 NamedDecl *PrevDecl =
21495 LookupSingleName(S: TUScope, Name, Loc: NameLoc, NameKind: LookupOrdinaryName);
21496
21497 if (PrevDecl) {
21498 auto *Attr = WeakAttr::CreateImplicit(Ctx&: Context, Range: PragmaLoc);
21499 if (checkWeakAttrCompatibility(S&: *this, ND: *PrevDecl, Attr: *Attr))
21500 PrevDecl->addAttr(A: Attr);
21501 } else {
21502 (void)WeakUndeclaredIdentifiers[Name].insert(X: WeakInfo(nullptr, NameLoc));
21503 }
21504}
21505
21506void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
21507 IdentifierInfo* AliasName,
21508 SourceLocation PragmaLoc,
21509 SourceLocation NameLoc,
21510 SourceLocation AliasNameLoc) {
21511 Decl *PrevDecl = LookupSingleName(S: TUScope, Name: AliasName, Loc: AliasNameLoc,
21512 NameKind: LookupOrdinaryName);
21513 WeakInfo W = WeakInfo(Name, NameLoc);
21514
21515 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21516 if (!PrevDecl->hasAttr<AliasAttr>())
21517 if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: PrevDecl))
21518 DeclApplyPragmaWeak(S: TUScope, ND, W);
21519 } else {
21520 (void)WeakUndeclaredIdentifiers[AliasName].insert(X: W);
21521 }
21522}
21523
21524Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
21525 bool Final) {
21526 assert(FD && "Expected non-null FunctionDecl");
21527
21528 // Templates are emitted when they're instantiated.
21529 if (FD->isDependentContext())
21530 return FunctionEmissionStatus::TemplateDiscarded;
21531
21532 if (LangOpts.SYCLIsDevice && (FD->hasAttr<SYCLKernelAttr>() ||
21533 FD->hasAttr<SYCLKernelEntryPointAttr>() ||
21534 FD->hasAttr<SYCLExternalAttr>()))
21535 return FunctionEmissionStatus::Emitted;
21536
21537 // Check whether this function is an externally visible definition.
21538 auto IsEmittedForExternalSymbol = [this, FD]() {
21539 // We have to check the GVA linkage of the function's *definition* -- if we
21540 // only have a declaration, we don't know whether or not the function will
21541 // be emitted, because (say) the definition could include "inline".
21542 const FunctionDecl *Def = FD->getDefinition();
21543
21544 // We can't compute linkage when we skip function bodies.
21545 return Def && !Def->hasSkippedBody() &&
21546 !isDiscardableGVALinkage(
21547 L: getASTContext().GetGVALinkageForFunction(FD: Def));
21548 };
21549
21550 if (LangOpts.OpenMPIsTargetDevice) {
21551 // In OpenMP device mode we will not emit host only functions, or functions
21552 // we don't need due to their linkage.
21553 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21554 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21555 // DevTy may be changed later by
21556 // #pragma omp declare target to(*) device_type(*).
21557 // Therefore DevTy having no value does not imply host. The emission status
21558 // will be checked again at the end of compilation unit with Final = true.
21559 if (DevTy)
21560 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21561 return FunctionEmissionStatus::OMPDiscarded;
21562 // If we have an explicit value for the device type, or we are in a target
21563 // declare context, we need to emit all extern and used symbols.
21564 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21565 if (IsEmittedForExternalSymbol())
21566 return FunctionEmissionStatus::Emitted;
21567 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21568 // we'll omit it.
21569 if (Final)
21570 return FunctionEmissionStatus::OMPDiscarded;
21571 } else if (LangOpts.OpenMP > 45) {
21572 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21573 // function. In 5.0, no_host was introduced which might cause a function to
21574 // be omitted.
21575 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21576 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21577 if (DevTy)
21578 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21579 return FunctionEmissionStatus::OMPDiscarded;
21580 }
21581
21582 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21583 return FunctionEmissionStatus::Emitted;
21584
21585 if (LangOpts.CUDA) {
21586 // When compiling for device, host functions are never emitted. Similarly,
21587 // when compiling for host, device and global functions are never emitted.
21588 // (Technically, we do emit a host-side stub for global functions, but this
21589 // doesn't count for our purposes here.)
21590 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: FD);
21591 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21592 return FunctionEmissionStatus::CUDADiscarded;
21593 if (!LangOpts.CUDAIsDevice &&
21594 (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))
21595 return FunctionEmissionStatus::CUDADiscarded;
21596
21597 if (IsEmittedForExternalSymbol())
21598 return FunctionEmissionStatus::Emitted;
21599 }
21600
21601 // Otherwise, the function is known-emitted if it's in our set of
21602 // known-emitted functions.
21603 return FunctionEmissionStatus::Unknown;
21604}
21605
21606bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
21607 // Host-side references to a __global__ function refer to the stub, so the
21608 // function itself is never emitted and therefore should not be marked.
21609 // If we have host fn calls kernel fn calls host+device, the HD function
21610 // does not get instantiated on the host. We model this by omitting at the
21611 // call to the kernel from the callgraph. This ensures that, when compiling
21612 // for host, only HD functions actually called from the host get marked as
21613 // known-emitted.
21614 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21615 CUDA().IdentifyTarget(D: Callee) == CUDAFunctionTarget::Global;
21616}
21617
21618bool Sema::isRedefinitionAllowedFor(NamedDecl *D,
21619 SourceLocation NewDefinitionLoc,
21620 NamedDecl **Suggested, bool &Visible) {
21621 Visible = hasVisibleDefinition(D, Suggested);
21622 // Accoding to [basic.def.odr]p16, it is not allowed to have duplicated definition
21623 // for declaratins which is attached to named modules.
21624 // We only did this if the current module is named module as we have better
21625 // diagnostics for declarations in global module and named modules.
21626 if (getCurrentModule() && getCurrentModule()->isNamedModule() &&
21627 D->isInNamedModule())
21628 return false;
21629 // The redefinition of D in the **current** TU is allowed if D is invisible or
21630 // D is defined in the global module of other module units or D is defined in
21631 // the same header in a different module.
21632 return D->isInAnotherModuleUnit() || !Visible ||
21633 isFromSameSingleIncludeHeader(PrevD: D, NewLoc: NewDefinitionLoc);
21634}
21635