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::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1508 // We assume that the caller has already called
1509 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1510 FunctionDecl *FD = D->getAsFunction();
1511 if (!FD)
1512 return;
1513
1514 // Same implementation as PushDeclContext, but enters the context
1515 // from the lexical parent, rather than the top-level class.
1516 assert(CurContext == FD->getLexicalParent() &&
1517 "The next DeclContext should be lexically contained in the current one.");
1518 CurContext = FD;
1519 S->setEntity(CurContext);
1520
1521 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1522 ParmVarDecl *Param = FD->getParamDecl(i: P);
1523 // If the parameter has an identifier, then add it to the scope
1524 if (Param->getIdentifier()) {
1525 S->AddDecl(D: Param);
1526 IdResolver.AddDecl(D: Param);
1527 }
1528 }
1529}
1530
1531void Sema::ActOnExitFunctionContext() {
1532 // Same implementation as PopDeclContext, but returns to the lexical parent,
1533 // rather than the top-level class.
1534 assert(CurContext && "DeclContext imbalance!");
1535 CurContext = CurContext->getLexicalParent();
1536 assert(CurContext && "Popped translation unit!");
1537}
1538
1539/// Determine whether overloading is allowed for a new function
1540/// declaration considering prior declarations of the same name.
1541///
1542/// This routine determines whether overloading is possible, not
1543/// whether a new declaration actually overloads a previous one.
1544/// It will return true in C++ (where overloads are always permitted)
1545/// or, as a C extension, when either the new declaration or a
1546/// previous one is declared with the 'overloadable' attribute.
1547static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1548 ASTContext &Context,
1549 const FunctionDecl *New) {
1550 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1551 return true;
1552
1553 // Multiversion function declarations are not overloads in the
1554 // usual sense of that term, but lookup will report that an
1555 // overload set was found if more than one multiversion function
1556 // declaration is present for the same name. It is therefore
1557 // inadequate to assume that some prior declaration(s) had
1558 // the overloadable attribute; checking is required. Since one
1559 // declaration is permitted to omit the attribute, it is necessary
1560 // to check at least two; hence the 'any_of' check below. Note that
1561 // the overloadable attribute is implicitly added to declarations
1562 // that were required to have it but did not.
1563 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1564 return llvm::any_of(Range: Previous, P: [](const NamedDecl *ND) {
1565 return ND->hasAttr<OverloadableAttr>();
1566 });
1567 } else if (Previous.getResultKind() == LookupResultKind::Found)
1568 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1569
1570 return false;
1571}
1572
1573void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1574 // Move up the scope chain until we find the nearest enclosing
1575 // non-transparent context. The declaration will be introduced into this
1576 // scope.
1577 while (S->getEntity() && S->getEntity()->isTransparentContext())
1578 S = S->getParent();
1579
1580 // Add scoped declarations into their context, so that they can be
1581 // found later. Declarations without a context won't be inserted
1582 // into any context.
1583 if (AddToContext)
1584 CurContext->addDecl(D);
1585
1586 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1587 // are function-local declarations.
1588 if (getLangOpts().CPlusPlus && D->isOutOfLine()) {
1589 if (!S->getFnParent())
1590 return;
1591
1592 // Even inside a function, an out-of-line definition of a type that is
1593 // nested inside a local class must not be pushed into the enclosing
1594 // function scope. For example:
1595 //
1596 // class A { public: class B; };
1597 // class A::B {}; // out-of-line definition inside the function
1598 // B b; // must fail - only A::B is valid
1599 // Wrapper{B{}} // must also fail
1600 //
1601 // Per C++ scoping rules only the qualified form A::B is accessible.
1602 // Without this guard, PushOnScopeChains would add B to the function's
1603 // local scope, making it findable via unqualified lookup, which is
1604 // incorrect. The condition targets TagDecls (class/struct/union/enum)
1605 // whose DeclContext is a CXXRecordDecl, i.e., types that are members
1606 // of a local class being defined out-of-line.
1607 if (isa<TagDecl>(Val: D) && isa<CXXRecordDecl>(Val: D->getDeclContext()))
1608 return;
1609 }
1610
1611 // Template instantiations should also not be pushed into scope.
1612 if (isa<FunctionDecl>(Val: D) &&
1613 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization())
1614 return;
1615
1616 if (isa<UsingEnumDecl>(Val: D) && D->getDeclName().isEmpty()) {
1617 S->AddDecl(D);
1618 return;
1619 }
1620 // If this replaces anything in the current scope,
1621 IdentifierResolver::iterator I = IdResolver.begin(Name: D->getDeclName()),
1622 IEnd = IdResolver.end();
1623 for (; I != IEnd; ++I) {
1624 if (S->isDeclScope(D: *I) && D->declarationReplaces(OldD: *I)) {
1625 S->RemoveDecl(D: *I);
1626 IdResolver.RemoveDecl(D: *I);
1627
1628 // Should only need to replace one decl.
1629 break;
1630 }
1631 }
1632
1633 S->AddDecl(D);
1634
1635 if (isa<LabelDecl>(Val: D) && !cast<LabelDecl>(Val: D)->isGnuLocal()) {
1636 // Implicitly-generated labels may end up getting generated in an order that
1637 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1638 // the label at the appropriate place in the identifier chain.
1639 for (I = IdResolver.begin(Name: D->getDeclName()); I != IEnd; ++I) {
1640 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1641 if (IDC == CurContext) {
1642 if (!S->isDeclScope(D: *I))
1643 continue;
1644 } else if (IDC->Encloses(DC: CurContext))
1645 break;
1646 }
1647
1648 IdResolver.InsertDeclAfter(Pos: I, D);
1649 } else {
1650 IdResolver.AddDecl(D);
1651 }
1652 warnOnReservedIdentifier(D);
1653}
1654
1655bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1656 bool AllowInlineNamespace) const {
1657 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1658}
1659
1660bool Sema::isTagRedeclarationInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1661 bool AllowInlineNamespace) const {
1662 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1663 return true;
1664
1665 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: D))
1666 return isDeclInScope(D: Shadow->getTargetDecl(), Ctx, S, AllowInlineNamespace);
1667
1668 return false;
1669}
1670
1671Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1672 DeclContext *TargetDC = DC->getPrimaryContext();
1673 do {
1674 if (DeclContext *ScopeDC = S->getEntity())
1675 if (ScopeDC->getPrimaryContext() == TargetDC)
1676 return S;
1677 } while ((S = S->getParent()));
1678
1679 return nullptr;
1680}
1681
1682static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1683 DeclContext*,
1684 ASTContext&);
1685
1686void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1687 bool ConsiderLinkage,
1688 bool AllowInlineNamespace) {
1689 LookupResult::Filter F = R.makeFilter();
1690 while (F.hasNext()) {
1691 NamedDecl *D = F.next();
1692
1693 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1694 continue;
1695
1696 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1697 continue;
1698
1699 F.erase();
1700 }
1701
1702 F.done();
1703}
1704
1705static bool isImplicitInstantiation(NamedDecl *D) {
1706 if (auto *VD = dyn_cast<VarDecl>(Val: D))
1707 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1708 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
1709 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1710 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1711 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1712
1713 return false;
1714}
1715
1716bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1717 // [module.interface]p7:
1718 // A declaration is attached to a module as follows:
1719 // - If the declaration is a non-dependent friend declaration that nominates a
1720 // function with a declarator-id that is a qualified-id or template-id or that
1721 // nominates a class other than with an elaborated-type-specifier with neither
1722 // a nested-name-specifier nor a simple-template-id, it is attached to the
1723 // module to which the friend is attached ([basic.link]).
1724 if (New->getFriendObjectKind() &&
1725 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1726 New->setLocalOwningModule(Old->getOwningModule());
1727 makeMergedDefinitionVisible(ND: New);
1728 return false;
1729 }
1730
1731 // Although we have questions for the module ownership of implicit
1732 // instantiations, it should be sure that we shouldn't diagnose the
1733 // redeclaration of incorrect module ownership for different implicit
1734 // instantiations in different modules. We will diagnose the redeclaration of
1735 // incorrect module ownership for the template itself.
1736 if (isImplicitInstantiation(D: New) || isImplicitInstantiation(D: Old))
1737 return false;
1738
1739 Module *NewM = New->getOwningModule();
1740 Module *OldM = Old->getOwningModule();
1741
1742 if (NewM && NewM->isPrivateModule())
1743 NewM = NewM->Parent;
1744 if (OldM && OldM->isPrivateModule())
1745 OldM = OldM->Parent;
1746
1747 if (NewM == OldM)
1748 return false;
1749
1750 if (NewM && OldM) {
1751 // A module implementation unit has visibility of the decls in its
1752 // implicitly imported interface.
1753 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1754 return false;
1755
1756 // Partitions are part of the module, but a partition could import another
1757 // module, so verify that the PMIs agree.
1758 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1759 getASTContext().isInSameModule(M1: NewM, M2: OldM))
1760 return false;
1761 }
1762
1763 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1764 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1765 if (NewIsModuleInterface || OldIsModuleInterface) {
1766 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1767 // if a declaration of D [...] appears in the purview of a module, all
1768 // other such declarations shall appear in the purview of the same module
1769 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_owning_module)
1770 << New
1771 << NewIsModuleInterface
1772 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1773 << OldIsModuleInterface
1774 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1775 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1776 New->setInvalidDecl();
1777 return true;
1778 }
1779
1780 return false;
1781}
1782
1783bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1784 // [module.interface]p1:
1785 // An export-declaration shall inhabit a namespace scope.
1786 //
1787 // So it is meaningless to talk about redeclaration which is not at namespace
1788 // scope.
1789 if (!New->getLexicalDeclContext()
1790 ->getNonTransparentContext()
1791 ->isFileContext() ||
1792 !Old->getLexicalDeclContext()
1793 ->getNonTransparentContext()
1794 ->isFileContext())
1795 return false;
1796
1797 bool IsNewExported = New->isInExportDeclContext();
1798 bool IsOldExported = Old->isInExportDeclContext();
1799
1800 // It should be irrevelant if both of them are not exported.
1801 if (!IsNewExported && !IsOldExported)
1802 return false;
1803
1804 if (IsOldExported)
1805 return false;
1806
1807 // If the Old declaration are not attached to named modules
1808 // and the New declaration are attached to global module.
1809 // It should be fine to allow the export since it doesn't change
1810 // the linkage of declarations. See
1811 // https://github.com/llvm/llvm-project/issues/98583 for details.
1812 if (!Old->isInNamedModule() && New->getOwningModule() &&
1813 New->getOwningModule()->isImplicitGlobalModule())
1814 return false;
1815
1816 assert(IsNewExported);
1817
1818 auto Lk = Old->getFormalLinkage();
1819 int S = 0;
1820 if (Lk == Linkage::Internal)
1821 S = 1;
1822 else if (Lk == Linkage::Module)
1823 S = 2;
1824 Diag(Loc: New->getLocation(), DiagID: diag::err_redeclaration_non_exported) << New << S;
1825 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1826 return true;
1827}
1828
1829bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1830 if (CheckRedeclarationModuleOwnership(New, Old))
1831 return true;
1832
1833 if (CheckRedeclarationExported(New, Old))
1834 return true;
1835
1836 return false;
1837}
1838
1839bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1840 const NamedDecl *Old) const {
1841 assert(getASTContext().isSameEntity(New, Old) &&
1842 "New and Old are not the same definition, we should diagnostic it "
1843 "immediately instead of checking it.");
1844 assert(const_cast<Sema *>(this)->isReachable(New) &&
1845 const_cast<Sema *>(this)->isReachable(Old) &&
1846 "We shouldn't see unreachable definitions here.");
1847
1848 Module *NewM = New->getOwningModule();
1849 Module *OldM = Old->getOwningModule();
1850
1851 // We only checks for named modules here. The header like modules is skipped.
1852 // FIXME: This is not right if we import the header like modules in the module
1853 // purview.
1854 //
1855 // For example, assuming "header.h" provides definition for `D`.
1856 // ```C++
1857 // //--- M.cppm
1858 // export module M;
1859 // import "header.h"; // or #include "header.h" but import it by clang modules
1860 // actually.
1861 //
1862 // //--- Use.cpp
1863 // import M;
1864 // import "header.h"; // or uses clang modules.
1865 // ```
1866 //
1867 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1868 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1869 // reject it. But the current implementation couldn't detect the case since we
1870 // don't record the information about the importee modules.
1871 //
1872 // But this might not be painful in practice. Since the design of C++20 Named
1873 // Modules suggests us to use headers in global module fragment instead of
1874 // module purview.
1875 if (NewM && NewM->isHeaderLikeModule())
1876 NewM = nullptr;
1877 if (OldM && OldM->isHeaderLikeModule())
1878 OldM = nullptr;
1879
1880 if (!NewM && !OldM)
1881 return true;
1882
1883 // [basic.def.odr]p14.3
1884 // Each such definition shall not be attached to a named module
1885 // ([module.unit]).
1886 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1887 return true;
1888
1889 // Then New and Old lives in the same TU if their share one same module unit.
1890 if (NewM)
1891 NewM = NewM->getTopLevelModule();
1892 if (OldM)
1893 OldM = OldM->getTopLevelModule();
1894 return OldM == NewM;
1895}
1896
1897static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1898 if (D->getDeclContext()->isFileContext())
1899 return false;
1900
1901 return isa<UsingShadowDecl>(Val: D) ||
1902 isa<UnresolvedUsingTypenameDecl>(Val: D) ||
1903 isa<UnresolvedUsingValueDecl>(Val: D);
1904}
1905
1906/// Removes using shadow declarations not at class scope from the lookup
1907/// results.
1908static void RemoveUsingDecls(LookupResult &R) {
1909 LookupResult::Filter F = R.makeFilter();
1910 while (F.hasNext())
1911 if (isUsingDeclNotAtClassScope(D: F.next()))
1912 F.erase();
1913
1914 F.done();
1915}
1916
1917/// Check for this common pattern:
1918/// @code
1919/// class S {
1920/// S(const S&); // DO NOT IMPLEMENT
1921/// void operator=(const S&); // DO NOT IMPLEMENT
1922/// };
1923/// @endcode
1924static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1925 // FIXME: Should check for private access too but access is set after we get
1926 // the decl here.
1927 if (D->doesThisDeclarationHaveABody())
1928 return false;
1929
1930 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: D))
1931 return CD->isCopyConstructor();
1932 return D->isCopyAssignmentOperator();
1933}
1934
1935bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1936 const DeclContext *DC = D->getDeclContext();
1937 while (!DC->isTranslationUnit()) {
1938 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Val: DC)){
1939 if (!RD->hasNameForLinkage())
1940 return true;
1941 }
1942 DC = DC->getParent();
1943 }
1944
1945 return !D->isExternallyVisible();
1946}
1947
1948bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1949 assert(D);
1950
1951 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1952 return false;
1953
1954 // Ignore all entities declared within templates, and out-of-line definitions
1955 // of members of class templates.
1956 if (D->getDeclContext()->isDependentContext() ||
1957 D->getLexicalDeclContext()->isDependentContext())
1958 return false;
1959
1960 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1961 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1962 return false;
1963 // A non-out-of-line declaration of a member specialization was implicitly
1964 // instantiated; it's the out-of-line declaration that we're interested in.
1965 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1966 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1967 return false;
1968
1969 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
1970 if (MD->isVirtual() || IsDisallowedCopyOrAssign(D: MD))
1971 return false;
1972 } else {
1973 // 'static inline' functions are defined in headers; don't warn.
1974 if (FD->isInlined() && !isMainFileLoc(Loc: FD->getLocation()))
1975 return false;
1976 }
1977
1978 if (FD->doesThisDeclarationHaveABody() &&
1979 Context.DeclMustBeEmitted(D: FD))
1980 return false;
1981 } else if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1982 // Constants and utility variables are defined in headers with internal
1983 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1984 // like "inline".)
1985 if (!isMainFileLoc(Loc: VD->getLocation()))
1986 return false;
1987
1988 if (Context.DeclMustBeEmitted(D: VD))
1989 return false;
1990
1991 if (VD->isStaticDataMember() &&
1992 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1993 return false;
1994 if (VD->isStaticDataMember() &&
1995 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1996 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1997 return false;
1998
1999 if (VD->isInline() && !isMainFileLoc(Loc: VD->getLocation()))
2000 return false;
2001 } else {
2002 return false;
2003 }
2004
2005 // Only warn for unused decls internal to the translation unit.
2006 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
2007 // for inline functions defined in the main source file, for instance.
2008 return mightHaveNonExternalLinkage(D);
2009}
2010
2011void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
2012 if (!D)
2013 return;
2014
2015 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
2016 const FunctionDecl *First = FD->getFirstDecl();
2017 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
2018 return; // First should already be in the vector.
2019 }
2020
2021 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2022 const VarDecl *First = VD->getFirstDecl();
2023 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
2024 return; // First should already be in the vector.
2025 }
2026
2027 if (ShouldWarnIfUnusedFileScopedDecl(D))
2028 UnusedFileScopedDecls.push_back(LocalValue: D);
2029}
2030
2031static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
2032 const NamedDecl *D) {
2033 if (D->isInvalidDecl())
2034 return false;
2035
2036 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: D)) {
2037 // For a decomposition declaration, warn if none of the bindings are
2038 // referenced, instead of if the variable itself is referenced (which
2039 // it is, by the bindings' expressions).
2040 bool IsAllIgnored = true;
2041 for (const auto *BD : DD->bindings()) {
2042 if (BD->isReferenced())
2043 return false;
2044 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2045 BD->hasAttr<UnusedAttr>());
2046 }
2047 if (IsAllIgnored)
2048 return false;
2049 } else if (!D->getDeclName()) {
2050 return false;
2051 } else if (D->isReferenced() || D->isUsed()) {
2052 return false;
2053 }
2054
2055 if (D->isPlaceholderVar(LangOpts))
2056 return false;
2057
2058 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2059 D->hasAttr<CleanupAttr>())
2060 return false;
2061
2062 if (isa<LabelDecl>(Val: D))
2063 return true;
2064
2065 // Except for labels, we only care about unused decls that are local to
2066 // functions.
2067 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2068 if (const auto *R = dyn_cast<CXXRecordDecl>(Val: D->getDeclContext()))
2069 // For dependent types, the diagnostic is deferred.
2070 WithinFunction =
2071 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2072 if (!WithinFunction)
2073 return false;
2074
2075 if (isa<TypedefNameDecl>(Val: D))
2076 return true;
2077
2078 // White-list anything that isn't a local variable.
2079 if (!isa<VarDecl>(Val: D) || isa<ParmVarDecl>(Val: D) || isa<ImplicitParamDecl>(Val: D))
2080 return false;
2081
2082 // Types of valid local variables should be complete, so this should succeed.
2083 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2084
2085 const Expr *Init = VD->getInit();
2086 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Val: Init))
2087 Init = Cleanups->getSubExpr();
2088
2089 const auto *Ty = VD->getType().getTypePtr();
2090
2091 // Only look at the outermost level of typedef.
2092 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2093 // Allow anything marked with __attribute__((unused)).
2094 if (TT->getDecl()->hasAttr<UnusedAttr>())
2095 return false;
2096 }
2097
2098 // Warn for reference variables whose initializtion performs lifetime
2099 // extension.
2100 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Val: Init);
2101 MTE && MTE->getExtendingDecl()) {
2102 Ty = VD->getType().getNonReferenceType().getTypePtr();
2103 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2104 }
2105
2106 // If we failed to complete the type for some reason, or if the type is
2107 // dependent, don't diagnose the variable.
2108 if (Ty->isIncompleteType() || Ty->isDependentType())
2109 return false;
2110
2111 // Look at the element type to ensure that the warning behaviour is
2112 // consistent for both scalars and arrays.
2113 Ty = Ty->getBaseElementTypeUnsafe();
2114
2115 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2116 if (Tag->hasAttr<UnusedAttr>())
2117 return false;
2118
2119 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
2120 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2121 return false;
2122
2123 if (Init) {
2124 const auto *Construct =
2125 dyn_cast<CXXConstructExpr>(Val: Init->IgnoreImpCasts());
2126 if (Construct && !Construct->isElidable()) {
2127 const CXXConstructorDecl *CD = Construct->getConstructor();
2128 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2129 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2130 return false;
2131 }
2132
2133 // Suppress the warning if we don't know how this is constructed, and
2134 // it could possibly be non-trivial constructor.
2135 if (Init->isTypeDependent()) {
2136 for (const CXXConstructorDecl *Ctor : RD->ctors())
2137 if (!Ctor->isTrivial())
2138 return false;
2139 }
2140
2141 // Suppress the warning if the constructor is unresolved because
2142 // its arguments are dependent.
2143 if (isa<CXXUnresolvedConstructExpr>(Val: Init))
2144 return false;
2145 }
2146 }
2147 }
2148
2149 // TODO: __attribute__((unused)) templates?
2150 }
2151
2152 return true;
2153}
2154
2155static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2156 FixItHint &Hint) {
2157 if (isa<LabelDecl>(Val: D)) {
2158 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2159 loc: D->getEndLoc(), TKind: tok::colon, SM: Ctx.getSourceManager(), LangOpts: Ctx.getLangOpts(),
2160 /*SkipTrailingWhitespaceAndNewline=*/SkipTrailingWhitespaceAndNewLine: false);
2161 if (AfterColon.isInvalid())
2162 return;
2163 Hint = FixItHint::CreateRemoval(
2164 RemoveRange: CharSourceRange::getCharRange(B: D->getBeginLoc(), E: AfterColon));
2165 }
2166}
2167
2168void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2169 DiagnoseUnusedNestedTypedefs(
2170 D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2171}
2172
2173void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2174 DiagReceiverTy DiagReceiver) {
2175 if (D->isDependentType())
2176 return;
2177
2178 for (auto *TmpD : D->decls()) {
2179 if (const auto *T = dyn_cast<TypedefNameDecl>(Val: TmpD))
2180 DiagnoseUnusedDecl(ND: T, DiagReceiver);
2181 else if(const auto *R = dyn_cast<RecordDecl>(Val: TmpD))
2182 DiagnoseUnusedNestedTypedefs(D: R, DiagReceiver);
2183 }
2184}
2185
2186void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2187 DiagnoseUnusedDecl(
2188 ND: D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2189}
2190
2191void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2192 if (!ShouldDiagnoseUnusedDecl(LangOpts: getLangOpts(), D))
2193 return;
2194
2195 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
2196 // typedefs can be referenced later on, so the diagnostics are emitted
2197 // at end-of-translation-unit.
2198 UnusedLocalTypedefNameCandidates.insert(Ptr: TD);
2199 return;
2200 }
2201
2202 FixItHint Hint;
2203 GenerateFixForUnusedDecl(D, Ctx&: Context, Hint);
2204
2205 unsigned DiagID;
2206 if (isa<VarDecl>(Val: D) && cast<VarDecl>(Val: D)->isExceptionVariable())
2207 DiagID = diag::warn_unused_exception_param;
2208 else if (isa<LabelDecl>(Val: D))
2209 DiagID = diag::warn_unused_label;
2210 else
2211 DiagID = diag::warn_unused_variable;
2212
2213 SourceLocation DiagLoc = D->getLocation();
2214 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2215}
2216
2217void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2218 DiagReceiverTy DiagReceiver) {
2219 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2220 // it's not really unused.
2221 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2222 return;
2223
2224 // In C++, `_` variables behave as if they were maybe_unused
2225 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(LangOpts: getLangOpts()))
2226 return;
2227
2228 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2229
2230 if (Ty->isReferenceType() || Ty->isDependentType())
2231 return;
2232
2233 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2234 if (Tag->hasAttr<UnusedAttr>())
2235 return;
2236 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2237 // mimic gcc's behavior.
2238 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag);
2239 RD && !RD->hasAttr<WarnUnusedAttr>())
2240 return;
2241 }
2242
2243 // Don't warn on volatile file-scope variables. They are visible beyond their
2244 // declaring function and writes to them could be observable side effects.
2245 if (VD->getType().isVolatileQualified() && VD->isFileVarDecl())
2246 return;
2247
2248 // Don't warn about __block Objective-C pointer variables, as they might
2249 // be assigned in the block but not used elsewhere for the purpose of lifetime
2250 // extension.
2251 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2252 return;
2253
2254 // Don't warn about Objective-C pointer variables with precise lifetime
2255 // semantics; they can be used to ensure ARC releases the object at a known
2256 // time, which may mean assignment but no other references.
2257 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2258 return;
2259
2260 auto iter = RefsMinusAssignments.find(Val: VD->getCanonicalDecl());
2261 if (iter == RefsMinusAssignments.end())
2262 return;
2263
2264 assert(iter->getSecond() >= 0 &&
2265 "Found a negative number of references to a VarDecl");
2266 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2267 // Assume the given VarDecl is "used" if its ref count stored in
2268 // `RefMinusAssignments` is positive, with one exception.
2269 //
2270 // For a C++ variable whose decl (with initializer) entirely consist the
2271 // condition expression of a if/while/for construct,
2272 // Clang creates a DeclRefExpr for the condition expression rather than a
2273 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2274 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2275 // used in the body of the if/while/for construct.
2276 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2277 if (!UnusedCXXCondDecl)
2278 return;
2279 }
2280
2281 unsigned DiagID;
2282 if (isa<ParmVarDecl>(Val: VD))
2283 DiagID = diag::warn_unused_but_set_parameter;
2284 else if (VD->isFileVarDecl())
2285 DiagID = diag::warn_unused_but_set_global;
2286 else
2287 DiagID = diag::warn_unused_but_set_variable;
2288 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2289}
2290
2291static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2292 Sema::DiagReceiverTy DiagReceiver) {
2293 // Verify that we have no forward references left. If so, there was a goto
2294 // or address of a label taken, but no definition of it. Label fwd
2295 // definitions are indicated with a null substmt which is also not a resolved
2296 // MS inline assembly label name.
2297 bool Diagnose = false;
2298 if (L->isMSAsmLabel())
2299 Diagnose = !L->isResolvedMSAsmLabel();
2300 else
2301 Diagnose = L->getStmt() == nullptr;
2302 if (Diagnose)
2303 DiagReceiver(L->getLocation(), S.PDiag(DiagID: diag::err_undeclared_label_use)
2304 << L);
2305}
2306
2307void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2308 S->applyNRVO();
2309
2310 if (S->decl_empty()) return;
2311 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2312 "Scope shouldn't contain decls!");
2313
2314 /// We visit the decls in non-deterministic order, but we want diagnostics
2315 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2316 /// and sort the diagnostics before emitting them, after we visited all decls.
2317 struct LocAndDiag {
2318 SourceLocation Loc;
2319 std::optional<SourceLocation> PreviousDeclLoc;
2320 PartialDiagnostic PD;
2321 };
2322 SmallVector<LocAndDiag, 16> DeclDiags;
2323 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2324 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: std::nullopt, .PD: std::move(PD)});
2325 };
2326 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2327 SourceLocation PreviousDeclLoc,
2328 PartialDiagnostic PD) {
2329 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: PreviousDeclLoc, .PD: std::move(PD)});
2330 };
2331
2332 for (auto *TmpD : S->decls()) {
2333 assert(TmpD && "This decl didn't get pushed??");
2334
2335 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2336 NamedDecl *D = cast<NamedDecl>(Val: TmpD);
2337
2338 // Diagnose unused variables in this scope.
2339 if (!S->hasUnrecoverableErrorOccurred()) {
2340 DiagnoseUnusedDecl(D, DiagReceiver: addDiag);
2341 if (const auto *RD = dyn_cast<RecordDecl>(Val: D))
2342 DiagnoseUnusedNestedTypedefs(D: RD, DiagReceiver: addDiag);
2343 // Wait until end of TU to diagnose internal linkage file vars.
2344 if (auto *VD = dyn_cast<VarDecl>(Val: D);
2345 VD && !VD->isInternalLinkageFileVar()) {
2346 DiagnoseUnusedButSetDecl(VD, DiagReceiver: addDiag);
2347 RefsMinusAssignments.erase(Val: VD->getCanonicalDecl());
2348 }
2349 }
2350
2351 if (!D->getDeclName()) continue;
2352
2353 // If this was a forward reference to a label, verify it was defined.
2354 if (LabelDecl *LD = dyn_cast<LabelDecl>(Val: D))
2355 CheckPoppedLabel(L: LD, S&: *this, DiagReceiver: addDiag);
2356
2357 // Partial translation units that are created in incremental processing must
2358 // not clean up the IdResolver because PTUs should take into account the
2359 // declarations that came from previous PTUs.
2360 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2361 getLangOpts().CPlusPlus)
2362 IdResolver.RemoveDecl(D);
2363
2364 // Warn on it if we are shadowing a declaration.
2365 auto ShadowI = ShadowingDecls.find(Val: D);
2366 if (ShadowI != ShadowingDecls.end()) {
2367 if (const auto *FD = dyn_cast<FieldDecl>(Val: ShadowI->second)) {
2368 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2369 PDiag(DiagID: diag::warn_ctor_parm_shadows_field)
2370 << D << FD << FD->getParent());
2371 }
2372 ShadowingDecls.erase(I: ShadowI);
2373 }
2374 }
2375
2376 llvm::sort(C&: DeclDiags,
2377 Comp: [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2378 // The particular order for diagnostics is not important, as long
2379 // as the order is deterministic. Using the raw location is going
2380 // to generally be in source order unless there are macro
2381 // expansions involved.
2382 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2383 });
2384 for (const LocAndDiag &D : DeclDiags) {
2385 Diag(Loc: D.Loc, PD: D.PD);
2386 if (D.PreviousDeclLoc)
2387 Diag(Loc: *D.PreviousDeclLoc, DiagID: diag::note_previous_declaration);
2388 }
2389}
2390
2391Scope *Sema::getNonFieldDeclScope(Scope *S) {
2392 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2393 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2394 (S->isClassScope() && !getLangOpts().CPlusPlus))
2395 S = S->getParent();
2396 return S;
2397}
2398
2399static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2400 ASTContext::GetBuiltinTypeError Error) {
2401 switch (Error) {
2402 case ASTContext::GE_None:
2403 return "";
2404 case ASTContext::GE_Missing_type:
2405 return BuiltinInfo.getHeaderName(ID);
2406 case ASTContext::GE_Missing_stdio:
2407 return "stdio.h";
2408 case ASTContext::GE_Missing_setjmp:
2409 return "setjmp.h";
2410 case ASTContext::GE_Missing_ucontext:
2411 return "ucontext.h";
2412 }
2413 llvm_unreachable("unhandled error kind");
2414}
2415
2416FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2417 unsigned ID, SourceLocation Loc) {
2418 DeclContext *Parent = Context.getTranslationUnitDecl();
2419
2420 if (getLangOpts().CPlusPlus) {
2421 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2422 C&: Context, DC: Parent, ExternLoc: Loc, LangLoc: Loc, Lang: LinkageSpecLanguageIDs::C, HasBraces: false);
2423 CLinkageDecl->setImplicit();
2424 Parent->addDecl(D: CLinkageDecl);
2425 Parent = CLinkageDecl;
2426 }
2427
2428 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified;
2429 if (Context.BuiltinInfo.isImmediate(ID)) {
2430 assert(getLangOpts().CPlusPlus20 &&
2431 "consteval builtins should only be available in C++20 mode");
2432 ConstexprKind = ConstexprSpecKind::Consteval;
2433 }
2434
2435 FunctionDecl *New = FunctionDecl::Create(
2436 C&: Context, DC: Parent, StartLoc: Loc, NLoc: Loc, N: II, T: Type, /*TInfo=*/nullptr, SC: SC_Extern,
2437 UsesFPIntrin: getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2438 hasWrittenPrototype: Type->isFunctionProtoType(), ConstexprKind);
2439 New->setImplicit();
2440 New->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID));
2441
2442 // Create Decl objects for each parameter, adding them to the
2443 // FunctionDecl.
2444 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: Type)) {
2445 SmallVector<ParmVarDecl *, 16> Params;
2446 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2447 ParmVarDecl *parm = ParmVarDecl::Create(
2448 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
2449 T: FT->getParamType(i), /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
2450 parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
2451 Params.push_back(Elt: parm);
2452 }
2453 New->setParams(Params);
2454 }
2455
2456 AddKnownFunctionAttributes(FD: New);
2457 return New;
2458}
2459
2460NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2461 Scope *S, bool ForRedeclaration,
2462 SourceLocation Loc) {
2463 LookupNecessaryTypesForBuiltin(S, ID);
2464
2465 ASTContext::GetBuiltinTypeError Error;
2466 QualType R = Context.GetBuiltinType(ID, Error);
2467 if (Error) {
2468 if (!ForRedeclaration)
2469 return nullptr;
2470
2471 // If we have a builtin without an associated type we should not emit a
2472 // warning when we were not able to find a type for it.
2473 if (Error == ASTContext::GE_Missing_type ||
2474 Context.BuiltinInfo.allowTypeMismatch(ID))
2475 return nullptr;
2476
2477 // If we could not find a type for setjmp it is because the jmp_buf type was
2478 // not defined prior to the setjmp declaration.
2479 if (Error == ASTContext::GE_Missing_setjmp) {
2480 Diag(Loc, DiagID: diag::warn_implicit_decl_no_jmp_buf)
2481 << Context.BuiltinInfo.getName(ID);
2482 return nullptr;
2483 }
2484
2485 // Generally, we emit a warning that the declaration requires the
2486 // appropriate header.
2487 Diag(Loc, DiagID: diag::warn_implicit_decl_requires_sysheader)
2488 << getHeaderName(BuiltinInfo&: Context.BuiltinInfo, ID, Error)
2489 << Context.BuiltinInfo.getName(ID);
2490 return nullptr;
2491 }
2492
2493 if (!ForRedeclaration &&
2494 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2495 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2496 Diag(Loc, DiagID: LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2497 : diag::ext_implicit_lib_function_decl)
2498 << Context.BuiltinInfo.getName(ID) << R;
2499 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2500 Diag(Loc, DiagID: diag::note_include_header_or_declare)
2501 << Header << Context.BuiltinInfo.getName(ID);
2502 }
2503
2504 if (R.isNull())
2505 return nullptr;
2506
2507 FunctionDecl *New = CreateBuiltin(II, Type: R, ID, Loc);
2508 RegisterLocallyScopedExternCDecl(ND: New, S);
2509
2510 // TUScope is the translation-unit scope to insert this function into.
2511 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2512 // relate Scopes to DeclContexts, and probably eliminate CurContext
2513 // entirely, but we're not there yet.
2514 DeclContext *SavedContext = CurContext;
2515 CurContext = New->getDeclContext();
2516 PushOnScopeChains(D: New, S: TUScope);
2517 CurContext = SavedContext;
2518 return New;
2519}
2520
2521/// Typedef declarations don't have linkage, but they still denote the same
2522/// entity if their types are the same.
2523/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2524/// isSameEntity.
2525static void
2526filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl,
2527 LookupResult &Previous) {
2528 // This is only interesting when modules are enabled.
2529 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2530 return;
2531
2532 // Empty sets are uninteresting.
2533 if (Previous.empty())
2534 return;
2535
2536 LookupResult::Filter Filter = Previous.makeFilter();
2537 while (Filter.hasNext()) {
2538 NamedDecl *Old = Filter.next();
2539
2540 // Non-hidden declarations are never ignored.
2541 if (S.isVisible(D: Old))
2542 continue;
2543
2544 // Declarations of the same entity are not ignored, even if they have
2545 // different linkages.
2546 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2547 if (S.Context.hasSameType(T1: OldTD->getUnderlyingType(),
2548 T2: Decl->getUnderlyingType()))
2549 continue;
2550
2551 // If both declarations give a tag declaration a typedef name for linkage
2552 // purposes, then they declare the same entity.
2553 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2554 Decl->getAnonDeclWithTypedefName())
2555 continue;
2556 }
2557
2558 Filter.erase();
2559 }
2560
2561 Filter.done();
2562}
2563
2564bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) {
2565 QualType OldType;
2566 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Val: Old))
2567 OldType = OldTypedef->getUnderlyingType();
2568 else
2569 OldType = Context.getTypeDeclType(Decl: Old);
2570 QualType NewType = New->getUnderlyingType();
2571
2572 if (NewType->isVariablyModifiedType()) {
2573 // Must not redefine a typedef with a variably-modified type.
2574 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2575 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_variably_modified_typedef)
2576 << Kind << NewType;
2577 if (Old->getLocation().isValid())
2578 notePreviousDefinition(Old, New: New->getLocation());
2579 New->setInvalidDecl();
2580 return true;
2581 }
2582
2583 if (OldType != NewType &&
2584 !OldType->isDependentType() &&
2585 !NewType->isDependentType() &&
2586 !Context.hasSameType(T1: OldType, T2: NewType)) {
2587 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2588 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_typedef)
2589 << Kind << NewType << OldType;
2590 if (Old->getLocation().isValid())
2591 notePreviousDefinition(Old, New: New->getLocation());
2592 New->setInvalidDecl();
2593 return true;
2594 }
2595 return false;
2596}
2597
2598void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2599 LookupResult &OldDecls) {
2600 // If the new decl is known invalid already, don't bother doing any
2601 // merging checks.
2602 if (New->isInvalidDecl()) return;
2603
2604 // Allow multiple definitions for ObjC built-in typedefs.
2605 // FIXME: Verify the underlying types are equivalent!
2606 if (getLangOpts().ObjC) {
2607 const IdentifierInfo *TypeID = New->getIdentifier();
2608 switch (TypeID->getLength()) {
2609 default: break;
2610 case 2:
2611 {
2612 if (!TypeID->isStr(Str: "id"))
2613 break;
2614 QualType T = New->getUnderlyingType();
2615 if (!T->isPointerType())
2616 break;
2617 if (!T->isVoidPointerType()) {
2618 QualType PT = T->castAs<PointerType>()->getPointeeType();
2619 if (!PT->isStructureType())
2620 break;
2621 }
2622 Context.setObjCIdRedefinitionType(T);
2623 // Install the built-in type for 'id', ignoring the current definition.
2624 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2625 modedTy: Context.getObjCIdType());
2626 return;
2627 }
2628 case 5:
2629 if (!TypeID->isStr(Str: "Class"))
2630 break;
2631 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2632 // Install the built-in type for 'Class', ignoring the current definition.
2633 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2634 modedTy: Context.getObjCClassType());
2635 return;
2636 case 3:
2637 if (!TypeID->isStr(Str: "SEL"))
2638 break;
2639 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2640 // Install the built-in type for 'SEL', ignoring the current definition.
2641 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2642 modedTy: Context.getObjCSelType());
2643 return;
2644 }
2645 // Fall through - the typedef name was not a builtin type.
2646 }
2647
2648 // Verify the old decl was also a type.
2649 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2650 if (!Old) {
2651 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
2652 << New->getDeclName();
2653
2654 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2655 if (OldD->getLocation().isValid())
2656 notePreviousDefinition(Old: OldD, New: New->getLocation());
2657
2658 return New->setInvalidDecl();
2659 }
2660
2661 // If the old declaration is invalid, just give up here.
2662 if (Old->isInvalidDecl())
2663 return New->setInvalidDecl();
2664
2665 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2666 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2667 auto *NewTag = New->getAnonDeclWithTypedefName();
2668 NamedDecl *Hidden = nullptr;
2669 if (OldTag && NewTag &&
2670 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2671 !hasVisibleDefinition(D: OldTag, Suggested: &Hidden)) {
2672 // There is a definition of this tag, but it is not visible. Use it
2673 // instead of our tag.
2674 if (OldTD->isModed())
2675 New->setModedTypeSourceInfo(unmodedTSI: OldTD->getTypeSourceInfo(),
2676 modedTy: OldTD->getUnderlyingType());
2677 else
2678 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2679
2680 // An anonymous enum is recognized as a redeclaration only when its
2681 // typedef name gets merged, at which point the new enum and its
2682 // enumerators already have a distinct canonical type. Link the enum
2683 // declarations, but also retype the new enumerators because
2684 // setPreviousDecl() does not update QualTypes built before the merge;
2685 // otherwise the merged typedef and its enumerators disagree on the type
2686 // (GH213299).
2687 //
2688 // FIXME: The global module restriction only limits the impact of this
2689 // change; relax it if the issue shows up in other contexts.
2690 if (Module *M = OldTag->getOwningModule(); M && M->isGlobalModule()) {
2691 if (auto *NewEnum = dyn_cast<EnumDecl>(Val: NewTag)) {
2692 if (auto *OldEnum = dyn_cast<EnumDecl>(Val: OldTag)) {
2693 NewEnum->setPreviousDecl(OldEnum);
2694 QualType EnumType = Context.getCanonicalTagType(TD: OldEnum);
2695 for (auto *ECD : NewEnum->enumerators())
2696 ECD->setType(EnumType);
2697 }
2698 }
2699 }
2700
2701 // Make the old tag definition visible.
2702 makeMergedDefinitionVisible(ND: Hidden);
2703
2704 CleanupMergedEnum(S, New: NewTag);
2705 }
2706 }
2707
2708 // If the typedef types are not identical, reject them in all languages and
2709 // with any extensions enabled.
2710 if (isIncompatibleTypedef(Old, New))
2711 return;
2712
2713 // The types match. Link up the redeclaration chain and merge attributes if
2714 // the old declaration was a typedef.
2715 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Val: Old)) {
2716 New->setPreviousDecl(Typedef);
2717 mergeDeclAttributes(New, Old);
2718 }
2719
2720 if (getLangOpts().MicrosoftExt)
2721 return;
2722
2723 if (getLangOpts().CPlusPlus) {
2724 // C++ [dcl.typedef]p2:
2725 // In a given non-class scope, a typedef specifier can be used to
2726 // redefine the name of any type declared in that scope to refer
2727 // to the type to which it already refers.
2728 if (!isa<CXXRecordDecl>(Val: CurContext))
2729 return;
2730
2731 // C++0x [dcl.typedef]p4:
2732 // In a given class scope, a typedef specifier can be used to redefine
2733 // any class-name declared in that scope that is not also a typedef-name
2734 // to refer to the type to which it already refers.
2735 //
2736 // This wording came in via DR424, which was a correction to the
2737 // wording in DR56, which accidentally banned code like:
2738 //
2739 // struct S {
2740 // typedef struct A { } A;
2741 // };
2742 //
2743 // in the C++03 standard. We implement the C++0x semantics, which
2744 // allow the above but disallow
2745 //
2746 // struct S {
2747 // typedef int I;
2748 // typedef int I;
2749 // };
2750 //
2751 // since that was the intent of DR56.
2752 if (!isa<TypedefNameDecl>(Val: Old))
2753 return;
2754
2755 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition)
2756 << New->getDeclName();
2757 notePreviousDefinition(Old, New: New->getLocation());
2758 return New->setInvalidDecl();
2759 }
2760
2761 // Modules always permit redefinition of typedefs, as does C11.
2762 if (getLangOpts().Modules || getLangOpts().C11)
2763 return;
2764
2765 // If we have a redefinition of a typedef in C, emit a warning. This warning
2766 // is normally mapped to an error, but can be controlled with
2767 // -Wtypedef-redefinition. If either the original or the redefinition is
2768 // in a system header, don't emit this for compatibility with GCC.
2769 if (getDiagnostics().getSuppressSystemWarnings() &&
2770 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2771 (Old->isImplicit() ||
2772 Context.getSourceManager().isInSystemHeader(Loc: Old->getLocation()) ||
2773 Context.getSourceManager().isInSystemHeader(Loc: New->getLocation())))
2774 return;
2775
2776 Diag(Loc: New->getLocation(), DiagID: diag::ext_redefinition_of_typedef)
2777 << New->getDeclName();
2778 notePreviousDefinition(Old, New: New->getLocation());
2779}
2780
2781void Sema::CleanupMergedEnum(Scope *S, Decl *New) {
2782 // If this was an unscoped enumeration, yank all of its enumerators
2783 // out of the scope.
2784 if (auto *ED = dyn_cast<EnumDecl>(Val: New); ED && !ED->isScoped()) {
2785 Scope *EnumScope = getNonFieldDeclScope(S);
2786 for (auto *ECD : ED->enumerators()) {
2787 assert(EnumScope->isDeclScope(ECD));
2788 EnumScope->RemoveDecl(D: ECD);
2789 IdResolver.RemoveDecl(D: ECD);
2790 }
2791 }
2792}
2793
2794/// DeclhasAttr - returns true if decl Declaration already has the target
2795/// attribute.
2796static bool DeclHasAttr(const Decl *D, const Attr *A) {
2797 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(Val: A);
2798 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(Val: A);
2799 for (const auto *i : D->attrs())
2800 if (i->getKind() == A->getKind()) {
2801 if (Ann) {
2802 if (Ann->getAnnotation() == cast<AnnotateAttr>(Val: i)->getAnnotation())
2803 return true;
2804 continue;
2805 }
2806 // FIXME: Don't hardcode this check
2807 if (OA && isa<OwnershipAttr>(Val: i))
2808 return OA->getOwnKind() == cast<OwnershipAttr>(Val: i)->getOwnKind();
2809 return true;
2810 }
2811
2812 return false;
2813}
2814
2815static bool isAttributeTargetADefinition(Decl *D) {
2816 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D))
2817 return VD->isThisDeclarationADefinition();
2818 if (TagDecl *TD = dyn_cast<TagDecl>(Val: D))
2819 return TD->isCompleteDefinition() || TD->isBeingDefined();
2820 return true;
2821}
2822
2823/// Merge alignment attributes from \p Old to \p New, taking into account the
2824/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2825///
2826/// \return \c true if any attributes were added to \p New.
2827static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2828 // Look for alignas attributes on Old, and pick out whichever attribute
2829 // specifies the strictest alignment requirement.
2830 AlignedAttr *OldAlignasAttr = nullptr;
2831 AlignedAttr *OldStrictestAlignAttr = nullptr;
2832 unsigned OldAlign = 0;
2833 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2834 // FIXME: We have no way of representing inherited dependent alignments
2835 // in a case like:
2836 // template<int A, int B> struct alignas(A) X;
2837 // template<int A, int B> struct alignas(B) X {};
2838 // For now, we just ignore any alignas attributes which are not on the
2839 // definition in such a case.
2840 if (I->isAlignmentDependent())
2841 return false;
2842
2843 if (I->isAlignas())
2844 OldAlignasAttr = I;
2845
2846 unsigned Align = I->getAlignment(Ctx&: S.Context);
2847 if (Align > OldAlign) {
2848 OldAlign = Align;
2849 OldStrictestAlignAttr = I;
2850 }
2851 }
2852
2853 // Look for alignas attributes on New.
2854 AlignedAttr *NewAlignasAttr = nullptr;
2855 unsigned NewAlign = 0;
2856 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2857 if (I->isAlignmentDependent())
2858 return false;
2859
2860 if (I->isAlignas())
2861 NewAlignasAttr = I;
2862
2863 unsigned Align = I->getAlignment(Ctx&: S.Context);
2864 if (Align > NewAlign)
2865 NewAlign = Align;
2866 }
2867
2868 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2869 // Both declarations have 'alignas' attributes. We require them to match.
2870 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2871 // fall short. (If two declarations both have alignas, they must both match
2872 // every definition, and so must match each other if there is a definition.)
2873
2874 // If either declaration only contains 'alignas(0)' specifiers, then it
2875 // specifies the natural alignment for the type.
2876 if (OldAlign == 0 || NewAlign == 0) {
2877 QualType Ty;
2878 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: New))
2879 Ty = VD->getType();
2880 else
2881 Ty = S.Context.getCanonicalTagType(TD: cast<TagDecl>(Val: New));
2882
2883 if (OldAlign == 0)
2884 OldAlign = S.Context.getTypeAlign(T: Ty);
2885 if (NewAlign == 0)
2886 NewAlign = S.Context.getTypeAlign(T: Ty);
2887 }
2888
2889 if (OldAlign != NewAlign) {
2890 S.Diag(Loc: NewAlignasAttr->getLocation(), DiagID: diag::err_alignas_mismatch)
2891 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: OldAlign).getQuantity()
2892 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: NewAlign).getQuantity();
2893 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_previous_declaration);
2894 }
2895 }
2896
2897 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(D: New)) {
2898 // C++11 [dcl.align]p6:
2899 // if any declaration of an entity has an alignment-specifier,
2900 // every defining declaration of that entity shall specify an
2901 // equivalent alignment.
2902 // C11 6.7.5/7:
2903 // If the definition of an object does not have an alignment
2904 // specifier, any other declaration of that object shall also
2905 // have no alignment specifier.
2906 S.Diag(Loc: New->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
2907 << OldAlignasAttr;
2908 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_alignas_on_declaration)
2909 << OldAlignasAttr;
2910 }
2911
2912 bool AnyAdded = false;
2913
2914 // Ensure we have an attribute representing the strictest alignment.
2915 if (OldAlign > NewAlign) {
2916 AlignedAttr *Clone = OldStrictestAlignAttr->clone(C&: S.Context);
2917 Clone->setInherited(true);
2918 New->addAttr(A: Clone);
2919 AnyAdded = true;
2920 }
2921
2922 // Ensure we have an alignas attribute if the old declaration had one.
2923 if (OldAlignasAttr && !NewAlignasAttr &&
2924 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2925 AlignedAttr *Clone = OldAlignasAttr->clone(C&: S.Context);
2926 Clone->setInherited(true);
2927 New->addAttr(A: Clone);
2928 AnyAdded = true;
2929 }
2930
2931 return AnyAdded;
2932}
2933
2934#define WANT_DECL_MERGE_LOGIC
2935#include "clang/Sema/AttrParsedAttrImpl.inc"
2936#undef WANT_DECL_MERGE_LOGIC
2937
2938static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2939 const InheritableAttr *Attr,
2940 AvailabilityMergeKind AMK) {
2941 // Diagnose any mutual exclusions between the attribute that we want to add
2942 // and attributes that already exist on the declaration.
2943 if (!DiagnoseMutualExclusions(S, D, A: Attr))
2944 return false;
2945
2946 // This function copies an attribute Attr from a previous declaration to the
2947 // new declaration D if the new declaration doesn't itself have that attribute
2948 // yet or if that attribute allows duplicates.
2949 // If you're adding a new attribute that requires logic different from
2950 // "use explicit attribute on decl if present, else use attribute from
2951 // previous decl", for example if the attribute needs to be consistent
2952 // between redeclarations, you need to call a custom merge function here.
2953 InheritableAttr *NewAttr = nullptr;
2954 if (const auto *AA = dyn_cast<AvailabilityAttr>(Val: Attr)) {
2955 const IdentifierInfo *InferredPlatformII = nullptr;
2956 if (AvailabilityAttr *Inf = AA->getInferredAttrAs())
2957 InferredPlatformII = Inf->getPlatform();
2958 NewAttr = S.mergeAndInferAvailabilityAttr(
2959 D, CI: *AA, Platform: AA->getPlatform(), Implicit: AA->isImplicit(), Introduced: AA->getIntroduced(),
2960 Deprecated: AA->getDeprecated(), Obsoleted: AA->getObsoleted(), IsUnavailable: AA->getUnavailable(),
2961 Message: AA->getMessage(), IsStrict: AA->getStrict(), Replacement: AA->getReplacement(), AMK,
2962 Priority: AA->getPriority(), IIEnvironment: AA->getEnvironment(), InferredPlatformII);
2963 } else if (const auto *VA = dyn_cast<VisibilityAttr>(Val: Attr))
2964 NewAttr = S.mergeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2965 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Val: Attr))
2966 NewAttr = S.mergeTypeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2967 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Val: Attr))
2968 NewAttr = S.mergeDLLImportAttr(D, CI: *ImportA);
2969 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Val: Attr))
2970 NewAttr = S.mergeDLLExportAttr(D, CI: *ExportA);
2971 else if (const auto *EA = dyn_cast<ErrorAttr>(Val: Attr))
2972 NewAttr = S.mergeErrorAttr(D, CI: *EA, NewUserDiagnostic: EA->getUserDiagnostic());
2973 else if (const auto *FA = dyn_cast<FormatAttr>(Val: Attr))
2974 NewAttr = S.mergeFormatAttr(D, CI: *FA, Format: FA->getType(), FormatIdx: FA->getFormatIdx(),
2975 FirstArg: FA->getFirstArg());
2976 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Val: Attr))
2977 NewAttr = S.mergeFormatMatchesAttr(
2978 D, CI: *FMA, Format: FMA->getType(), FormatIdx: FMA->getFormatIdx(), FormatStr: FMA->getFormatString());
2979 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Val: Attr))
2980 NewAttr = S.mergeModularFormatAttr(
2981 D, CI: *MFA, ModularImplFn: MFA->getModularImplFn(), ImplName: MFA->getImplName(),
2982 Aspects: MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2983 else if (const auto *SA = dyn_cast<SectionAttr>(Val: Attr))
2984 NewAttr = S.mergeSectionAttr(D, CI: *SA, Name: SA->getName());
2985 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Val: Attr))
2986 NewAttr = S.mergeCodeSegAttr(D, CI: *CSA, Name: CSA->getName());
2987 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Val: Attr))
2988 NewAttr = S.mergeMSInheritanceAttr(D, CI: *IA, BestCase: IA->getBestCase(),
2989 Model: IA->getInheritanceModel());
2990 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Val: Attr))
2991 NewAttr = S.mergeAlwaysInlineAttr(D, CI: *AA,
2992 Ident: &S.Context.Idents.get(Name: AA->getSpelling()));
2993 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(Val: D) &&
2994 (isa<CUDAHostAttr>(Val: Attr) || isa<CUDADeviceAttr>(Val: Attr) ||
2995 isa<CUDAGlobalAttr>(Val: Attr))) {
2996 // CUDA target attributes are part of function signature for
2997 // overloading purposes and must not be merged.
2998 return false;
2999 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Val: Attr))
3000 NewAttr = S.mergeMinSizeAttr(D, CI: *MA);
3001 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Val: Attr))
3002 NewAttr = S.Swift().mergeNameAttr(D, SNA: *SNA, Name: SNA->getName());
3003 else if (const auto *SAA = dyn_cast<SwiftAttrAttr>(Val: Attr))
3004 NewAttr = S.Swift().mergeAttrAttr(D, SAA: *SAA);
3005 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Val: Attr))
3006 NewAttr = S.mergeOptimizeNoneAttr(D, CI: *OA);
3007 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Val: Attr))
3008 NewAttr = S.mergeInternalLinkageAttr(D, AL: *InternalLinkageA);
3009 else if (isa<AlignedAttr>(Val: Attr))
3010 // AlignedAttrs are handled separately, because we need to handle all
3011 // such attributes on a declaration at the same time.
3012 NewAttr = nullptr;
3013 else if ((isa<DeprecatedAttr>(Val: Attr) || isa<UnavailableAttr>(Val: Attr)) &&
3014 (AMK == AvailabilityMergeKind::Override ||
3015 AMK == AvailabilityMergeKind::ProtocolImplementation ||
3016 AMK == AvailabilityMergeKind::OptionalProtocolImplementation))
3017 NewAttr = nullptr;
3018 else if (const auto *UA = dyn_cast<UuidAttr>(Val: Attr))
3019 NewAttr = S.mergeUuidAttr(D, CI: *UA, UuidAsWritten: UA->getGuid(), GuidDecl: UA->getGuidDecl());
3020 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Val: Attr))
3021 NewAttr = S.Wasm().mergeImportModuleAttr(D, AL: *IMA);
3022 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Val: Attr))
3023 NewAttr = S.Wasm().mergeImportNameAttr(D, AL: *INA);
3024 else if (const auto *ENA = dyn_cast<WebAssemblyExportNameAttr>(Val: Attr))
3025 NewAttr = S.Wasm().mergeExportNameAttr(D, AL: *ENA);
3026 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Val: Attr))
3027 NewAttr = S.mergeEnforceTCBAttr(D, AL: *TCBA);
3028 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Val: Attr))
3029 NewAttr = S.mergeEnforceTCBLeafAttr(D, AL: *TCBLA);
3030 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Val: Attr))
3031 NewAttr = S.mergeBTFDeclTagAttr(D, AL: *BTFA);
3032 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Val: Attr))
3033 NewAttr = S.HLSL().mergeNumThreadsAttr(D, AL: *NT, X: NT->getX(), Y: NT->getY(),
3034 Z: NT->getZ());
3035 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Val: Attr))
3036 NewAttr = S.HLSL().mergeWaveSizeAttr(D, AL: *WS, Min: WS->getMin(), Max: WS->getMax(),
3037 Preferred: WS->getPreferred(),
3038 SpelledArgsCount: WS->getSpelledArgsCount());
3039 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Val: Attr))
3040 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, AL: *CI, Id: CI->getId());
3041 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Val: Attr))
3042 NewAttr = S.HLSL().mergeShaderAttr(D, AL: *SA, ShaderType: SA->getType());
3043 else if (isa<SuppressAttr>(Val: Attr))
3044 // Do nothing. Each redeclaration should be suppressed separately.
3045 NewAttr = nullptr;
3046 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Val: Attr))
3047 NewAttr = S.OpenACC().mergeRoutineDeclAttr(Old: *RD);
3048 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, A: Attr))
3049 NewAttr = cast<InheritableAttr>(Val: Attr->clone(C&: S.Context));
3050 else if (const auto *PA = dyn_cast<PersonalityAttr>(Val: Attr))
3051 NewAttr = S.mergePersonalityAttr(D, Routine: PA->getRoutine(), CI: *PA);
3052
3053 if (NewAttr) {
3054 NewAttr->setInherited(true);
3055 D->addAttr(A: NewAttr);
3056 if (isa<MSInheritanceAttr>(Val: NewAttr))
3057 S.Consumer.AssignInheritanceModel(RD: cast<CXXRecordDecl>(Val: D));
3058 return true;
3059 }
3060
3061 return false;
3062}
3063
3064static const NamedDecl *getDefinition(const Decl *D) {
3065 if (const TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
3066 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
3067 return Def;
3068 return nullptr;
3069 }
3070 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
3071 const VarDecl *Def = VD->getDefinition();
3072 if (Def)
3073 return Def;
3074 return VD->getActingDefinition();
3075 }
3076 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
3077 const FunctionDecl *Def = nullptr;
3078 if (FD->isDefined(Definition&: Def, CheckForPendingFriendDefinition: true))
3079 return Def;
3080 }
3081 return nullptr;
3082}
3083
3084static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3085 for (const auto *Attribute : D->attrs())
3086 if (Attribute->getKind() == Kind)
3087 return true;
3088 return false;
3089}
3090
3091/// checkNewAttributesAfterDef - If we already have a definition, check that
3092/// there are no new attributes in this declaration.
3093static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3094 if (!New->hasAttrs())
3095 return;
3096
3097 const NamedDecl *Def = getDefinition(D: Old);
3098 if (!Def || Def == New)
3099 return;
3100
3101 AttrVec &NewAttributes = New->getAttrs();
3102 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3103 Attr *NewAttribute = NewAttributes[I];
3104
3105 if (isa<AliasAttr>(Val: NewAttribute) || isa<IFuncAttr>(Val: NewAttribute)) {
3106 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: New)) {
3107 SkipBodyInfo SkipBody;
3108 S.CheckForFunctionRedefinition(FD, EffectiveDefinition: cast<FunctionDecl>(Val: Def), SkipBody: &SkipBody);
3109
3110 // If we're skipping this definition, drop the "alias" attribute.
3111 if (SkipBody.ShouldSkip) {
3112 NewAttributes.erase(CI: NewAttributes.begin() + I);
3113 --E;
3114 continue;
3115 }
3116 } else {
3117 VarDecl *VD = cast<VarDecl>(Val: New);
3118 unsigned Diag = cast<VarDecl>(Val: Def)->isThisDeclarationADefinition() ==
3119 VarDecl::TentativeDefinition
3120 ? diag::err_alias_after_tentative
3121 : diag::err_redefinition;
3122 S.Diag(Loc: VD->getLocation(), DiagID: Diag) << VD->getDeclName();
3123 if (Diag == diag::err_redefinition)
3124 S.notePreviousDefinition(Old: Def, New: VD->getLocation());
3125 else
3126 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3127 VD->setInvalidDecl();
3128 }
3129 ++I;
3130 continue;
3131 }
3132
3133 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: Def)) {
3134 // Tentative definitions are only interesting for the alias check above.
3135 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3136 ++I;
3137 continue;
3138 }
3139 }
3140
3141 if (hasAttribute(D: Def, Kind: NewAttribute->getKind())) {
3142 ++I;
3143 continue; // regular attr merging will take care of validating this.
3144 }
3145
3146 if (NewAttribute->getLocation().isInvalid()) {
3147 // An attribute with no source location was not written by the user. API
3148 // notes, in particular, are matched against whichever declaration the
3149 // compiler reaches, which can be a redeclaration that follows the
3150 // definition, possibly in a different module. There is nothing for the
3151 // user to correct, and erasing the attribute would silently change what
3152 // the annotated API means.
3153 ++I;
3154 continue;
3155 }
3156
3157 if (isa<C11NoReturnAttr>(Val: NewAttribute)) {
3158 // C's _Noreturn is allowed to be added to a function after it is defined.
3159 ++I;
3160 continue;
3161 } else if (isa<UuidAttr>(Val: NewAttribute)) {
3162 // msvc will allow a subsequent definition to add an uuid to a class
3163 ++I;
3164 continue;
3165 } else if (isa<DeprecatedAttr, WarnUnusedResultAttr, UnusedAttr>(
3166 Val: NewAttribute) &&
3167 NewAttribute->isStandardAttributeSyntax()) {
3168 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3169 // deprecated attribute can later be re-declared with the attribute and
3170 // vice-versa.
3171 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3172 // maybe_unused attribute can later be redeclared with the attribute and
3173 // vice versa.
3174 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3175 // nodiscard attribute can later be redeclared with the attribute and
3176 // vice-versa.
3177 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3178 ++I;
3179 continue;
3180 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(Val: NewAttribute)) {
3181 if (AA->isAlignas()) {
3182 // C++11 [dcl.align]p6:
3183 // if any declaration of an entity has an alignment-specifier,
3184 // every defining declaration of that entity shall specify an
3185 // equivalent alignment.
3186 // C11 6.7.5/7:
3187 // If the definition of an object does not have an alignment
3188 // specifier, any other declaration of that object shall also
3189 // have no alignment specifier.
3190 S.Diag(Loc: Def->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
3191 << AA;
3192 S.Diag(Loc: NewAttribute->getLocation(), DiagID: diag::note_alignas_on_declaration)
3193 << AA;
3194 NewAttributes.erase(CI: NewAttributes.begin() + I);
3195 --E;
3196 continue;
3197 }
3198 } else if (isa<LoaderUninitializedAttr>(Val: NewAttribute)) {
3199 // If there is a C definition followed by a redeclaration with this
3200 // attribute then there are two different definitions. In C++, prefer the
3201 // standard diagnostics.
3202 if (!S.getLangOpts().CPlusPlus) {
3203 S.Diag(Loc: NewAttribute->getLocation(),
3204 DiagID: diag::err_loader_uninitialized_redeclaration);
3205 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3206 NewAttributes.erase(CI: NewAttributes.begin() + I);
3207 --E;
3208 continue;
3209 }
3210 } else if (isa<SelectAnyAttr>(Val: NewAttribute) &&
3211 cast<VarDecl>(Val: New)->isInline() &&
3212 !cast<VarDecl>(Val: New)->isInlineSpecified()) {
3213 // Don't warn about applying selectany to implicitly inline variables.
3214 // Older compilers and language modes would require the use of selectany
3215 // to make such variables inline, and it would have no effect if we
3216 // honored it.
3217 ++I;
3218 continue;
3219 } else if (isa<OMPDeclareVariantAttr>(Val: NewAttribute)) {
3220 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3221 // declarations after definitions.
3222 ++I;
3223 continue;
3224 } else if (isa<SYCLKernelEntryPointAttr>(Val: NewAttribute)) {
3225 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3226 // error since the definition will have already been created without
3227 // the semantic effects of the attribute having been applied.
3228 S.Diag(Loc: NewAttribute->getLocation(),
3229 DiagID: diag::err_sycl_entry_point_after_definition)
3230 << NewAttribute;
3231 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3232 cast<SYCLKernelEntryPointAttr>(Val: NewAttribute)->setInvalidAttr();
3233 ++I;
3234 continue;
3235 } else if (isa<SYCLExternalAttr>(Val: NewAttribute)) {
3236 // SYCLExternalAttr may be added after a definition.
3237 ++I;
3238 continue;
3239 }
3240
3241 S.Diag(Loc: NewAttribute->getLocation(),
3242 DiagID: diag::warn_attribute_precede_definition);
3243 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3244 NewAttributes.erase(CI: NewAttributes.begin() + I);
3245 --E;
3246 }
3247}
3248
3249static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3250 const ConstInitAttr *CIAttr,
3251 bool AttrBeforeInit) {
3252 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3253
3254 // Figure out a good way to write this specifier on the old declaration.
3255 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3256 // enough of the attribute list spelling information to extract that without
3257 // heroics.
3258 std::string SuitableSpelling;
3259 if (S.getLangOpts().CPlusPlus20)
3260 SuitableSpelling = std::string(
3261 S.PP.getLastMacroWithSpelling(Loc: InsertLoc, Tokens: {tok::kw_constinit}));
3262 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3263 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3264 Loc: InsertLoc, Tokens: {tok::l_square, tok::l_square,
3265 S.PP.getIdentifierInfo(Name: "clang"), tok::coloncolon,
3266 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3267 tok::r_square, tok::r_square}));
3268 if (SuitableSpelling.empty())
3269 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3270 Loc: InsertLoc, Tokens: {tok::kw___attribute, tok::l_paren, tok::r_paren,
3271 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3272 tok::r_paren, tok::r_paren}));
3273 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3274 SuitableSpelling = "constinit";
3275 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3276 SuitableSpelling = "[[clang::require_constant_initialization]]";
3277 if (SuitableSpelling.empty())
3278 SuitableSpelling = "__attribute__((require_constant_initialization))";
3279 SuitableSpelling += " ";
3280
3281 if (AttrBeforeInit) {
3282 // extern constinit int a;
3283 // int a = 0; // error (missing 'constinit'), accepted as extension
3284 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3285 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::ext_constinit_missing)
3286 << InitDecl << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3287 S.Diag(Loc: CIAttr->getLocation(), DiagID: diag::note_constinit_specified_here);
3288 } else {
3289 // int a = 0;
3290 // constinit extern int a; // error (missing 'constinit')
3291 S.Diag(Loc: CIAttr->getLocation(),
3292 DiagID: CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3293 : diag::warn_require_const_init_added_too_late)
3294 << FixItHint::CreateRemoval(RemoveRange: SourceRange(CIAttr->getLocation()));
3295 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::note_constinit_missing_here)
3296 << CIAttr->isConstinit()
3297 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3298 }
3299}
3300
3301void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3302 AvailabilityMergeKind AMK) {
3303 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3304 UsedAttr *NewAttr = OldAttr->clone(C&: Context);
3305 NewAttr->setInherited(true);
3306 New->addAttr(A: NewAttr);
3307 }
3308 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3309 RetainAttr *NewAttr = OldAttr->clone(C&: Context);
3310 NewAttr->setInherited(true);
3311 New->addAttr(A: NewAttr);
3312 }
3313
3314 if (!Old->hasAttrs() && !New->hasAttrs())
3315 return;
3316
3317 // [dcl.constinit]p1:
3318 // If the [constinit] specifier is applied to any declaration of a
3319 // variable, it shall be applied to the initializing declaration.
3320 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3321 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3322 if (bool(OldConstInit) != bool(NewConstInit)) {
3323 const auto *OldVD = cast<VarDecl>(Val: Old);
3324 auto *NewVD = cast<VarDecl>(Val: New);
3325
3326 // Find the initializing declaration. Note that we might not have linked
3327 // the new declaration into the redeclaration chain yet.
3328 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3329 if (!InitDecl &&
3330 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3331 InitDecl = NewVD;
3332
3333 if (InitDecl == NewVD) {
3334 // This is the initializing declaration. If it would inherit 'constinit',
3335 // that's ill-formed. (Note that we do not apply this to the attribute
3336 // form).
3337 if (OldConstInit && OldConstInit->isConstinit())
3338 diagnoseMissingConstinit(S&: *this, InitDecl: NewVD, CIAttr: OldConstInit,
3339 /*AttrBeforeInit=*/true);
3340 } else if (NewConstInit) {
3341 // This is the first time we've been told that this declaration should
3342 // have a constant initializer. If we already saw the initializing
3343 // declaration, this is too late.
3344 if (InitDecl && InitDecl != NewVD) {
3345 diagnoseMissingConstinit(S&: *this, InitDecl, CIAttr: NewConstInit,
3346 /*AttrBeforeInit=*/false);
3347 NewVD->dropAttr<ConstInitAttr>();
3348 }
3349 }
3350 }
3351
3352 // Attributes declared post-definition are currently ignored.
3353 checkNewAttributesAfterDef(S&: *this, New, Old);
3354
3355 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3356 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3357 if (!OldA->isEquivalent(Other: NewA)) {
3358 // This redeclaration changes __asm__ label.
3359 Diag(Loc: New->getLocation(), DiagID: diag::err_different_asm_label);
3360 Diag(Loc: OldA->getLocation(), DiagID: diag::note_previous_declaration);
3361 }
3362 } else if (Old->isUsed()) {
3363 // This redeclaration adds an __asm__ label to a declaration that has
3364 // already been ODR-used.
3365 Diag(Loc: New->getLocation(), DiagID: diag::err_late_asm_label_name)
3366 << isa<FunctionDecl>(Val: Old) << New->getAttr<AsmLabelAttr>()->getRange();
3367 }
3368 }
3369
3370 // Re-declaration cannot add abi_tag's.
3371 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3372 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3373 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3374 if (!llvm::is_contained(Range: OldAbiTagAttr->tags(), Element: NewTag)) {
3375 Diag(Loc: NewAbiTagAttr->getLocation(),
3376 DiagID: diag::err_new_abi_tag_on_redeclaration)
3377 << NewTag;
3378 Diag(Loc: OldAbiTagAttr->getLocation(), DiagID: diag::note_previous_declaration);
3379 }
3380 }
3381 } else {
3382 Diag(Loc: NewAbiTagAttr->getLocation(), DiagID: diag::err_abi_tag_on_redeclaration);
3383 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3384 }
3385 }
3386
3387 // This redeclaration adds a section attribute.
3388 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3389 if (auto *VD = dyn_cast<VarDecl>(Val: New)) {
3390 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3391 Diag(Loc: New->getLocation(), DiagID: diag::warn_attribute_section_on_redeclaration);
3392 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3393 }
3394 }
3395 }
3396
3397 // Redeclaration adds code-seg attribute.
3398 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3399 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3400 !NewCSA->isImplicit() && isa<CXXMethodDecl>(Val: New)) {
3401 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_section)
3402 << 0 /*codeseg*/;
3403 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3404 }
3405
3406 if (!Old->hasAttrs())
3407 return;
3408
3409 bool foundAny = New->hasAttrs();
3410
3411 // Ensure that any moving of objects within the allocated map is done before
3412 // we process them.
3413 if (!foundAny) New->setAttrs(AttrVec());
3414
3415 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3416 // Ignore deprecated/unavailable/availability attributes if requested.
3417 AvailabilityMergeKind LocalAMK = AvailabilityMergeKind::None;
3418 if (isa<DeprecatedAttr>(Val: I) ||
3419 isa<UnavailableAttr>(Val: I) ||
3420 isa<AvailabilityAttr>(Val: I)) {
3421 switch (AMK) {
3422 case AvailabilityMergeKind::None:
3423 continue;
3424
3425 case AvailabilityMergeKind::Redeclaration:
3426 case AvailabilityMergeKind::Override:
3427 case AvailabilityMergeKind::ProtocolImplementation:
3428 case AvailabilityMergeKind::OptionalProtocolImplementation:
3429 LocalAMK = AMK;
3430 break;
3431 }
3432 }
3433
3434 // Already handled.
3435 if (isa<UsedAttr>(Val: I) || isa<RetainAttr>(Val: I))
3436 continue;
3437
3438 // Don't propagate inferred noreturn or conflicting inline attributes to
3439 // explicit specializations.
3440 if (isa<InferredNoReturnAttr>(Val: I) || isa<AlwaysInlineAttr>(Val: I) ||
3441 isa<NoInlineAttr>(Val: I)) {
3442 if (auto *FD = dyn_cast<FunctionDecl>(Val: New);
3443 FD &&
3444 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3445 continue;
3446 }
3447
3448 if (mergeDeclAttribute(S&: *this, D: New, Attr: I, AMK: LocalAMK))
3449 foundAny = true;
3450 }
3451
3452 if (mergeAlignedAttrs(S&: *this, New, Old))
3453 foundAny = true;
3454
3455 if (!foundAny) New->dropAttrs();
3456}
3457
3458void Sema::CheckAttributesOnDeducedType(Decl *D) {
3459 for (const Attr *A : D->attrs())
3460 checkAttrIsTypeDependent(D, A);
3461}
3462
3463// Returns the number of added attributes.
3464template <class T>
3465static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3466 Sema &S) {
3467 unsigned found = 0;
3468 for (const auto *I : From->specific_attrs<T>()) {
3469 if (!DeclHasAttr(To, I)) {
3470 T *newAttr = cast<T>(I->clone(S.Context));
3471 newAttr->setInherited(true);
3472 To->addAttr(A: newAttr);
3473 ++found;
3474 }
3475 }
3476 return found;
3477}
3478
3479template <class F>
3480static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3481 F &&propagator) {
3482 if (!From->hasAttrs()) {
3483 return;
3484 }
3485
3486 bool foundAny = To->hasAttrs();
3487
3488 // Ensure that any moving of objects within the allocated map is
3489 // done before we process them.
3490 if (!foundAny)
3491 To->setAttrs(AttrVec());
3492
3493 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3494
3495 if (!foundAny)
3496 To->dropAttrs();
3497}
3498
3499/// mergeParamDeclAttributes - Copy attributes from the old parameter
3500/// to the new one.
3501static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3502 const ParmVarDecl *oldDecl, Sema &S) {
3503 propagateAttributes(
3504 To: newDecl, From: oldDecl, propagator: [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3505 unsigned found = 0;
3506 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3507 // Propagate the lifetimebound attribute from parameters to the
3508 // most recent declaration. Note that this doesn't include the implicit
3509 // 'this' parameter, as the attribute is applied to the function type in
3510 // that case.
3511 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3512 return found;
3513 });
3514}
3515
3516static bool EquivalentArrayTypes(QualType Old, QualType New,
3517 const ASTContext &Ctx) {
3518
3519 auto NoSizeInfo = [&Ctx](QualType Ty) {
3520 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3521 return true;
3522 if (const auto *VAT = Ctx.getAsVariableArrayType(T: Ty))
3523 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3524 return false;
3525 };
3526
3527 // `type[]` is equivalent to `type *` and `type[*]`.
3528 if (NoSizeInfo(Old) && NoSizeInfo(New))
3529 return true;
3530
3531 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3532 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3533 const auto *OldVAT = Ctx.getAsVariableArrayType(T: Old);
3534 const auto *NewVAT = Ctx.getAsVariableArrayType(T: New);
3535 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3536 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3537 return false;
3538 return true;
3539 }
3540
3541 // Only compare size, ignore Size modifiers and CVR.
3542 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3543 return Ctx.getAsConstantArrayType(T: Old)->getSize() ==
3544 Ctx.getAsConstantArrayType(T: New)->getSize();
3545 }
3546
3547 // Don't try to compare dependent sized array
3548 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3549 return true;
3550 }
3551
3552 return Old == New;
3553}
3554
3555static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3556 const ParmVarDecl *OldParam,
3557 Sema &S) {
3558 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3559 if (auto Newnullability = NewParam->getType()->getNullability()) {
3560 if (*Oldnullability != *Newnullability) {
3561 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_mismatched_nullability_attr)
3562 << DiagNullabilityKind(
3563 *Newnullability,
3564 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3565 != 0))
3566 << DiagNullabilityKind(
3567 *Oldnullability,
3568 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3569 != 0));
3570 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration);
3571 }
3572 } else {
3573 QualType NewT = NewParam->getType();
3574 NewT = S.Context.getAttributedType(nullability: *Oldnullability, modifiedType: NewT, equivalentType: NewT);
3575 NewParam->setType(NewT);
3576 }
3577 }
3578 const auto *OldParamDT = dyn_cast<DecayedType>(Val: OldParam->getType());
3579 const auto *NewParamDT = dyn_cast<DecayedType>(Val: NewParam->getType());
3580 if (OldParamDT && NewParamDT &&
3581 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3582 QualType OldParamOT = OldParamDT->getOriginalType();
3583 QualType NewParamOT = NewParamDT->getOriginalType();
3584 if (!EquivalentArrayTypes(Old: OldParamOT, New: NewParamOT, Ctx: S.getASTContext())) {
3585 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_inconsistent_array_form)
3586 << NewParam << NewParamOT;
3587 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration_as)
3588 << OldParamOT;
3589 }
3590 }
3591}
3592
3593namespace {
3594
3595/// Used in MergeFunctionDecl to keep track of function parameters in
3596/// C.
3597struct GNUCompatibleParamWarning {
3598 ParmVarDecl *OldParm;
3599 ParmVarDecl *NewParm;
3600 QualType PromotedType;
3601};
3602
3603} // end anonymous namespace
3604
3605// Determine whether the previous declaration was a definition, implicit
3606// declaration, or a declaration.
3607template <typename T>
3608static std::pair<diag::kind, SourceLocation>
3609getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3610 diag::kind PrevDiag;
3611 SourceLocation OldLocation = Old->getLocation();
3612 if (Old->isThisDeclarationADefinition())
3613 PrevDiag = diag::note_previous_definition;
3614 else if (Old->isImplicit()) {
3615 PrevDiag = diag::note_previous_implicit_declaration;
3616 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3617 if (FD->getBuiltinID())
3618 PrevDiag = diag::note_previous_builtin_declaration;
3619 }
3620 if (OldLocation.isInvalid())
3621 OldLocation = New->getLocation();
3622 } else
3623 PrevDiag = diag::note_previous_declaration;
3624 return std::make_pair(x&: PrevDiag, y&: OldLocation);
3625}
3626
3627/// canRedefineFunction - checks if a function can be redefined. Currently,
3628/// only extern inline functions can be redefined, and even then only in
3629/// GNU89 mode.
3630static bool canRedefineFunction(const FunctionDecl *FD,
3631 const LangOptions& LangOpts) {
3632 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3633 !LangOpts.CPlusPlus &&
3634 FD->isInlineSpecified() &&
3635 FD->getStorageClass() == SC_Extern);
3636}
3637
3638const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3639 const AttributedType *AT = T->getAs<AttributedType>();
3640 while (AT && !AT->isCallingConv())
3641 AT = AT->getModifiedType()->getAs<AttributedType>();
3642 return AT;
3643}
3644
3645template <typename T>
3646static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3647 const DeclContext *DC = Old->getDeclContext();
3648 if (DC->isRecord())
3649 return false;
3650
3651 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3652 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3653 return true;
3654 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3655 return true;
3656 return false;
3657}
3658
3659template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3660static bool isExternC(VarTemplateDecl *) { return false; }
3661static bool isExternC(FunctionTemplateDecl *) { return false; }
3662
3663/// Check whether a redeclaration of an entity introduced by a
3664/// using-declaration is valid, given that we know it's not an overload
3665/// (nor a hidden tag declaration).
3666template<typename ExpectedDecl>
3667static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3668 ExpectedDecl *New) {
3669 // C++11 [basic.scope.declarative]p4:
3670 // Given a set of declarations in a single declarative region, each of
3671 // which specifies the same unqualified name,
3672 // -- they shall all refer to the same entity, or all refer to functions
3673 // and function templates; or
3674 // -- exactly one declaration shall declare a class name or enumeration
3675 // name that is not a typedef name and the other declarations shall all
3676 // refer to the same variable or enumerator, or all refer to functions
3677 // and function templates; in this case the class name or enumeration
3678 // name is hidden (3.3.10).
3679
3680 // C++11 [namespace.udecl]p14:
3681 // If a function declaration in namespace scope or block scope has the
3682 // same name and the same parameter-type-list as a function introduced
3683 // by a using-declaration, and the declarations do not declare the same
3684 // function, the program is ill-formed.
3685
3686 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3687 if (Old &&
3688 !Old->getDeclContext()->getRedeclContext()->Equals(
3689 New->getDeclContext()->getRedeclContext()) &&
3690 !(isExternC(Old) && isExternC(New)))
3691 Old = nullptr;
3692
3693 if (!Old) {
3694 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3695 S.Diag(Loc: OldS->getTargetDecl()->getLocation(), DiagID: diag::note_using_decl_target);
3696 S.Diag(Loc: OldS->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
3697 return true;
3698 }
3699 return false;
3700}
3701
3702static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3703 const FunctionDecl *B) {
3704 assert(A->getNumParams() == B->getNumParams());
3705
3706 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3707 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3708 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3709 if (AttrA == AttrB)
3710 return true;
3711 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3712 AttrA->isDynamic() == AttrB->isDynamic();
3713 };
3714
3715 return std::equal(first1: A->param_begin(), last1: A->param_end(), first2: B->param_begin(), binary_pred: AttrEq);
3716}
3717
3718/// If necessary, adjust the semantic declaration context for a qualified
3719/// declaration to name the correct inline namespace within the qualifier.
3720static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3721 DeclaratorDecl *OldD) {
3722 // The only case where we need to update the DeclContext is when
3723 // redeclaration lookup for a qualified name finds a declaration
3724 // in an inline namespace within the context named by the qualifier:
3725 //
3726 // inline namespace N { int f(); }
3727 // int ::f(); // Sema DC needs adjusting from :: to N::.
3728 //
3729 // For unqualified declarations, the semantic context *can* change
3730 // along the redeclaration chain (for local extern declarations,
3731 // extern "C" declarations, and friend declarations in particular).
3732 if (!NewD->getQualifier())
3733 return;
3734
3735 // NewD is probably already in the right context.
3736 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3737 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3738 if (NamedDC->Equals(DC: SemaDC))
3739 return;
3740
3741 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3742 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3743 "unexpected context for redeclaration");
3744
3745 auto *LexDC = NewD->getLexicalDeclContext();
3746 auto FixSemaDC = [=](NamedDecl *D) {
3747 if (!D)
3748 return;
3749 D->setDeclContext(SemaDC);
3750 D->setLexicalDeclContext(LexDC);
3751 };
3752
3753 FixSemaDC(NewD);
3754 if (auto *FD = dyn_cast<FunctionDecl>(Val: NewD))
3755 FixSemaDC(FD->getDescribedFunctionTemplate());
3756 else if (auto *VD = dyn_cast<VarDecl>(Val: NewD))
3757 FixSemaDC(VD->getDescribedVarTemplate());
3758}
3759
3760bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3761 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3762 // Verify the old decl was also a function.
3763 FunctionDecl *Old = OldD->getAsFunction();
3764 if (!Old) {
3765 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: OldD)) {
3766 // We don't need to check the using friend pattern from other module unit
3767 // since we should have diagnosed such cases in its unit already.
3768 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3769 Diag(Loc: New->getLocation(), DiagID: diag::err_using_decl_friend);
3770 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
3771 DiagID: diag::note_using_decl_target);
3772 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
3773 << 0;
3774 return true;
3775 }
3776
3777 // Check whether the two declarations might declare the same function or
3778 // function template.
3779 if (FunctionTemplateDecl *NewTemplate =
3780 New->getDescribedFunctionTemplate()) {
3781 if (checkUsingShadowRedecl<FunctionTemplateDecl>(S&: *this, OldS: Shadow,
3782 New: NewTemplate))
3783 return true;
3784 OldD = Old = cast<FunctionTemplateDecl>(Val: Shadow->getTargetDecl())
3785 ->getAsFunction();
3786 } else {
3787 if (checkUsingShadowRedecl<FunctionDecl>(S&: *this, OldS: Shadow, New))
3788 return true;
3789 OldD = Old = cast<FunctionDecl>(Val: Shadow->getTargetDecl());
3790 }
3791 } else {
3792 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
3793 << New->getDeclName();
3794 notePreviousDefinition(Old: OldD, New: New->getLocation());
3795 return true;
3796 }
3797 }
3798
3799 // If the old declaration was found in an inline namespace and the new
3800 // declaration was qualified, update the DeclContext to match.
3801 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
3802
3803 // If the old declaration is invalid, just give up here.
3804 if (Old->isInvalidDecl())
3805 return true;
3806
3807 // Disallow redeclaration of some builtins.
3808 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3809 Diag(Loc: New->getLocation(), DiagID: diag::err_builtin_redeclare) << Old->getDeclName();
3810 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_builtin_declaration)
3811 << Old << Old->getType();
3812 return true;
3813 }
3814
3815 diag::kind PrevDiag;
3816 SourceLocation OldLocation;
3817 std::tie(args&: PrevDiag, args&: OldLocation) =
3818 getNoteDiagForInvalidRedeclaration(Old, New);
3819
3820 // Don't complain about this if we're in GNU89 mode and the old function
3821 // is an extern inline function.
3822 // Don't complain about specializations. They are not supposed to have
3823 // storage classes.
3824 if (!isa<CXXMethodDecl>(Val: New) && !isa<CXXMethodDecl>(Val: Old) &&
3825 New->getStorageClass() == SC_Static &&
3826 Old->hasExternalFormalLinkage() &&
3827 !New->getTemplateSpecializationInfo() &&
3828 !canRedefineFunction(FD: Old, LangOpts: getLangOpts())) {
3829 if (getLangOpts().MicrosoftExt) {
3830 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static) << New;
3831 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3832 } else {
3833 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static)
3834 << New << /*MixedLinkageUB=*/false;
3835 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3836 return true;
3837 }
3838 }
3839
3840 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3841 if (!Old->hasAttr<InternalLinkageAttr>()) {
3842 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
3843 << ILA;
3844 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3845 New->dropAttr<InternalLinkageAttr>();
3846 }
3847
3848 if (auto *EA = New->getAttr<ErrorAttr>()) {
3849 if (!Old->hasAttr<ErrorAttr>()) {
3850 Diag(Loc: EA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl) << EA;
3851 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3852 New->dropAttr<ErrorAttr>();
3853 }
3854 }
3855
3856 if (CheckRedeclarationInModule(New, Old))
3857 return true;
3858
3859 if (!getLangOpts().CPlusPlus) {
3860 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3861 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3862 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_overloadable_mismatch)
3863 << New << OldOvl;
3864
3865 // Try our best to find a decl that actually has the overloadable
3866 // attribute for the note. In most cases (e.g. programs with only one
3867 // broken declaration/definition), this won't matter.
3868 //
3869 // FIXME: We could do this if we juggled some extra state in
3870 // OverloadableAttr, rather than just removing it.
3871 const Decl *DiagOld = Old;
3872 if (OldOvl) {
3873 auto OldIter = llvm::find_if(Range: Old->redecls(), P: [](const Decl *D) {
3874 const auto *A = D->getAttr<OverloadableAttr>();
3875 return A && !A->isImplicit();
3876 });
3877 // If we've implicitly added *all* of the overloadable attrs to this
3878 // chain, emitting a "previous redecl" note is pointless.
3879 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3880 }
3881
3882 if (DiagOld)
3883 Diag(Loc: DiagOld->getLocation(),
3884 DiagID: diag::note_attribute_overloadable_prev_overload)
3885 << OldOvl;
3886
3887 if (OldOvl)
3888 New->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
3889 else
3890 New->dropAttr<OverloadableAttr>();
3891 }
3892 }
3893
3894 // It is not permitted to redeclare an SME function with different SME
3895 // attributes.
3896 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
3897 Diag(Loc: New->getLocation(), DiagID: diag::err_sme_attr_mismatch)
3898 << New->getType() << Old->getType();
3899 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3900 return true;
3901 }
3902
3903 // If a function is first declared with a calling convention, but is later
3904 // declared or defined without one, all following decls assume the calling
3905 // convention of the first.
3906 //
3907 // It's OK if a function is first declared without a calling convention,
3908 // but is later declared or defined with the default calling convention.
3909 //
3910 // To test if either decl has an explicit calling convention, we look for
3911 // AttributedType sugar nodes on the type as written. If they are missing or
3912 // were canonicalized away, we assume the calling convention was implicit.
3913 //
3914 // Note also that we DO NOT return at this point, because we still have
3915 // other tests to run.
3916 QualType OldQType = Context.getCanonicalType(T: Old->getType());
3917 QualType NewQType = Context.getCanonicalType(T: New->getType());
3918 const FunctionType *OldType = cast<FunctionType>(Val&: OldQType);
3919 const FunctionType *NewType = cast<FunctionType>(Val&: NewQType);
3920 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3921 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3922 bool RequiresAdjustment = false;
3923
3924 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3925 FunctionDecl *First = Old->getFirstDecl();
3926 const FunctionType *FT =
3927 First->getType().getCanonicalType()->castAs<FunctionType>();
3928 FunctionType::ExtInfo FI = FT->getExtInfo();
3929 bool NewCCExplicit = getCallingConvAttributedType(T: New->getType());
3930 if (!NewCCExplicit) {
3931 // Inherit the CC from the previous declaration if it was specified
3932 // there but not here.
3933 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3934 RequiresAdjustment = true;
3935 } else if (Old->getBuiltinID()) {
3936 // Builtin attribute isn't propagated to the new one yet at this point,
3937 // so we check if the old one is a builtin.
3938
3939 // Calling Conventions on a Builtin aren't really useful and setting a
3940 // default calling convention and cdecl'ing some builtin redeclarations is
3941 // common, so warn and ignore the calling convention on the redeclaration.
3942 Diag(Loc: New->getLocation(), DiagID: diag::warn_cconv_unsupported)
3943 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3944 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3945 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3946 RequiresAdjustment = true;
3947 } else {
3948 // Calling conventions aren't compatible, so complain.
3949 bool FirstCCExplicit = getCallingConvAttributedType(T: First->getType());
3950 Diag(Loc: New->getLocation(), DiagID: diag::err_cconv_change)
3951 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3952 << !FirstCCExplicit
3953 << (!FirstCCExplicit ? "" :
3954 FunctionType::getNameForCallConv(CC: FI.getCC()));
3955
3956 // Put the note on the first decl, since it is the one that matters.
3957 Diag(Loc: First->getLocation(), DiagID: diag::note_previous_declaration);
3958 return true;
3959 }
3960 }
3961
3962 // FIXME: diagnose the other way around?
3963 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3964 NewTypeInfo = NewTypeInfo.withNoReturn(noReturn: true);
3965 RequiresAdjustment = true;
3966 }
3967
3968 // If the declaration is marked with cfi_unchecked_callee but the definition
3969 // isn't, the definition is also cfi_unchecked_callee.
3970 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3971 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3972 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3973 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3974
3975 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3976 EPI2.CFIUncheckedCallee = true;
3977 NewQType = Context.getFunctionType(ResultTy: FPT2->getReturnType(),
3978 Args: FPT2->getParamTypes(), EPI: EPI2);
3979 NewType = cast<FunctionType>(Val&: NewQType);
3980 New->setType(NewQType);
3981 }
3982 }
3983 }
3984
3985 // Merge regparm attribute.
3986 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3987 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3988 if (NewTypeInfo.getHasRegParm()) {
3989 Diag(Loc: New->getLocation(), DiagID: diag::err_regparm_mismatch)
3990 << NewType->getRegParmType()
3991 << OldType->getRegParmType();
3992 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3993 return true;
3994 }
3995
3996 NewTypeInfo = NewTypeInfo.withRegParm(RegParm: OldTypeInfo.getRegParm());
3997 RequiresAdjustment = true;
3998 }
3999
4000 // Merge ns_returns_retained attribute.
4001 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
4002 if (NewTypeInfo.getProducesResult()) {
4003 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch)
4004 << "'ns_returns_retained'";
4005 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
4006 return true;
4007 }
4008
4009 NewTypeInfo = NewTypeInfo.withProducesResult(producesResult: true);
4010 RequiresAdjustment = true;
4011 }
4012
4013 if (OldTypeInfo.getNoCallerSavedRegs() !=
4014 NewTypeInfo.getNoCallerSavedRegs()) {
4015 if (NewTypeInfo.getNoCallerSavedRegs()) {
4016 AnyX86NoCallerSavedRegistersAttr *Attr =
4017 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
4018 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch) << Attr;
4019 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
4020 return true;
4021 }
4022
4023 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(noCallerSavedRegs: true);
4024 RequiresAdjustment = true;
4025 }
4026
4027 if (RequiresAdjustment) {
4028 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
4029 AdjustedType = Context.adjustFunctionType(Fn: AdjustedType, EInfo: NewTypeInfo);
4030 New->setType(QualType(AdjustedType, 0));
4031 NewQType = Context.getCanonicalType(T: New->getType());
4032 }
4033
4034 // If this redeclaration makes the function inline, we may need to add it to
4035 // UndefinedButUsed.
4036 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
4037 !getLangOpts().GNUInline && Old->isUsed(CheckUsedAttr: false) && !Old->isDefined() &&
4038 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
4039 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4040 y: SourceLocation()));
4041
4042 // If this redeclaration makes it newly gnu_inline, we don't want to warn
4043 // about it.
4044 if (New->hasAttr<GNUInlineAttr>() &&
4045 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
4046 UndefinedButUsed.erase(Key: Old->getCanonicalDecl());
4047 }
4048
4049 // If pass_object_size params don't match up perfectly, this isn't a valid
4050 // redeclaration.
4051 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
4052 !hasIdenticalPassObjectSizeAttrs(A: Old, B: New)) {
4053 Diag(Loc: New->getLocation(), DiagID: diag::err_different_pass_object_size_params)
4054 << New->getDeclName();
4055 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4056 return true;
4057 }
4058
4059 QualType OldQTypeForComparison = OldQType;
4060 if (Context.hasAnyFunctionEffects()) {
4061 const auto OldFX = Old->getFunctionEffects();
4062 const auto NewFX = New->getFunctionEffects();
4063 if (OldFX != NewFX) {
4064 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
4065 for (const auto &Diff : Diffs) {
4066 if (Diff.shouldDiagnoseRedeclaration(OldFunction: *Old, OldFX, NewFunction: *New, NewFX)) {
4067 Diag(Loc: New->getLocation(),
4068 DiagID: diag::warn_mismatched_func_effect_redeclaration)
4069 << Diff.effectName();
4070 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4071 }
4072 }
4073 // Following a warning, we could skip merging effects from the previous
4074 // declaration, but that would trigger an additional "conflicting types"
4075 // error.
4076 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4077 FunctionEffectSet::Conflicts MergeErrs;
4078 FunctionEffectSet MergedFX =
4079 FunctionEffectSet::getUnion(LHS: OldFX, RHS: NewFX, Errs&: MergeErrs);
4080 if (!MergeErrs.empty())
4081 diagnoseFunctionEffectMergeConflicts(Errs: MergeErrs, NewLoc: New->getLocation(),
4082 OldLoc: Old->getLocation());
4083
4084 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4085 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4086 QualType ModQT = Context.getFunctionType(ResultTy: NewFPT->getReturnType(),
4087 Args: NewFPT->getParamTypes(), EPI);
4088
4089 New->setType(ModQT);
4090 NewQType = New->getType();
4091
4092 // Revise OldQTForComparison to include the merged effects,
4093 // so as not to fail due to differences later.
4094 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4095 EPI = OldFPT->getExtProtoInfo();
4096 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4097 OldQTypeForComparison = Context.getFunctionType(
4098 ResultTy: OldFPT->getReturnType(), Args: OldFPT->getParamTypes(), EPI);
4099 }
4100 if (OldFX.empty()) {
4101 // A redeclaration may add the attribute to a previously seen function
4102 // body which needs to be verified.
4103 maybeAddDeclWithEffects(D: Old, FX: MergedFX);
4104 }
4105 }
4106 }
4107 }
4108
4109 if (getLangOpts().CPlusPlus) {
4110 OldQType = Context.getCanonicalType(T: Old->getType());
4111 NewQType = Context.getCanonicalType(T: New->getType());
4112
4113 // Go back to the type source info to compare the declared return types,
4114 // per C++1y [dcl.type.auto]p13:
4115 // Redeclarations or specializations of a function or function template
4116 // with a declared return type that uses a placeholder type shall also
4117 // use that placeholder, not a deduced type.
4118 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4119 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4120 if (!Context.hasSameType(T1: OldDeclaredReturnType, T2: NewDeclaredReturnType) &&
4121 canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewDeclaredReturnType,
4122 OldT: OldDeclaredReturnType)) {
4123 QualType ResQT;
4124 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4125 OldDeclaredReturnType->isObjCObjectPointerType())
4126 // FIXME: This does the wrong thing for a deduced return type.
4127 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4128 if (ResQT.isNull()) {
4129 if (New->isCXXClassMember() && New->isOutOfLine())
4130 Diag(Loc: New->getLocation(), DiagID: diag::err_member_def_does_not_match_ret_type)
4131 << New << New->getReturnTypeSourceRange();
4132 else if (Old->isExternC() && New->isExternC() &&
4133 !Old->hasAttr<OverloadableAttr>() &&
4134 !New->hasAttr<OverloadableAttr>())
4135 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4136 else
4137 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_diff_return_type)
4138 << New->getReturnTypeSourceRange();
4139 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType()
4140 << Old->getReturnTypeSourceRange();
4141 return true;
4142 }
4143 else
4144 NewQType = ResQT;
4145 }
4146
4147 QualType OldReturnType = OldType->getReturnType();
4148 QualType NewReturnType = cast<FunctionType>(Val&: NewQType)->getReturnType();
4149 if (OldReturnType != NewReturnType) {
4150 // If this function has a deduced return type and has already been
4151 // defined, copy the deduced value from the old declaration.
4152 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4153 if (OldAT && OldAT->isDeduced()) {
4154 QualType DT = OldAT->getDeducedType();
4155 if (DT.isNull()) {
4156 New->setType(SubstAutoTypeDependent(TypeWithAuto: New->getType()));
4157 NewQType = Context.getCanonicalType(T: SubstAutoTypeDependent(TypeWithAuto: NewQType));
4158 } else {
4159 New->setType(SubstAutoType(TypeWithAuto: New->getType(), Replacement: DT));
4160 NewQType = Context.getCanonicalType(T: SubstAutoType(TypeWithAuto: NewQType, Replacement: DT));
4161 }
4162 }
4163 }
4164
4165 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
4166 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
4167 if (OldMethod && NewMethod) {
4168 // Preserve triviality.
4169 NewMethod->setTrivial(OldMethod->isTrivial());
4170
4171 // MSVC allows explicit template specialization at class scope:
4172 // 2 CXXMethodDecls referring to the same function will be injected.
4173 // We don't want a redeclaration error.
4174 bool IsClassScopeExplicitSpecialization =
4175 OldMethod->isFunctionTemplateSpecialization() &&
4176 NewMethod->isFunctionTemplateSpecialization();
4177 bool isFriend = NewMethod->getFriendObjectKind();
4178
4179 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4180 !IsClassScopeExplicitSpecialization) {
4181 // -- Member function declarations with the same name and the
4182 // same parameter types cannot be overloaded if any of them
4183 // is a static member function declaration.
4184 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4185 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_static_nonstatic_member);
4186 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4187 return true;
4188 }
4189
4190 // C++ [class.mem]p1:
4191 // [...] A member shall not be declared twice in the
4192 // member-specification, except that a nested class or member
4193 // class template can be declared and then later defined.
4194 if (!inTemplateInstantiation()) {
4195 unsigned NewDiag;
4196 if (isa<CXXConstructorDecl>(Val: OldMethod))
4197 NewDiag = diag::err_constructor_redeclared;
4198 else if (isa<CXXDestructorDecl>(Val: NewMethod))
4199 NewDiag = diag::err_destructor_redeclared;
4200 else if (isa<CXXConversionDecl>(Val: NewMethod))
4201 NewDiag = diag::err_conv_function_redeclared;
4202 else
4203 NewDiag = diag::err_member_redeclared;
4204
4205 Diag(Loc: New->getLocation(), DiagID: NewDiag);
4206 } else {
4207 Diag(Loc: New->getLocation(), DiagID: diag::err_member_redeclared_in_instantiation)
4208 << New << New->getType();
4209 }
4210 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4211 return true;
4212
4213 // Complain if this is an explicit declaration of a special
4214 // member that was initially declared implicitly.
4215 //
4216 // As an exception, it's okay to befriend such methods in order
4217 // to permit the implicit constructor/destructor/operator calls.
4218 } else if (OldMethod->isImplicit()) {
4219 if (isFriend) {
4220 NewMethod->setImplicit();
4221 } else {
4222 Diag(Loc: NewMethod->getLocation(),
4223 DiagID: diag::err_definition_of_implicitly_declared_member)
4224 << New << OldMethod->getSpecialMemberKind();
4225 return true;
4226 }
4227 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4228 Diag(Loc: NewMethod->getLocation(),
4229 DiagID: diag::err_definition_of_explicitly_defaulted_member)
4230 << OldMethod->getSpecialMemberKind();
4231 return true;
4232 }
4233 }
4234
4235 // C++1z [over.load]p2
4236 // Certain function declarations cannot be overloaded:
4237 // -- Function declarations that differ only in the return type,
4238 // the exception specification, or both cannot be overloaded.
4239
4240 // Check the exception specifications match. This may recompute the type of
4241 // both Old and New if it resolved exception specifications, so grab the
4242 // types again after this. Because this updates the type, we do this before
4243 // any of the other checks below, which may update the "de facto" NewQType
4244 // but do not necessarily update the type of New.
4245 if (CheckEquivalentExceptionSpec(Old, New))
4246 return true;
4247
4248 // C++11 [dcl.attr.noreturn]p1:
4249 // The first declaration of a function shall specify the noreturn
4250 // attribute if any declaration of that function specifies the noreturn
4251 // attribute.
4252 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4253 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4254 Diag(Loc: NRA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4255 << NRA;
4256 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4257 }
4258
4259 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4260 // When a function is declared with SYCL_EXTERNAL, that macro must be
4261 // used on the first declaration of that function in the translation unit.
4262 // Redeclarations of the function in the same translation unit may
4263 // optionally use SYCL_EXTERNAL, but this is not required.
4264 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4265 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4266 Diag(Loc: SEA->getLocation(), DiagID: diag::warn_sycl_external_missing_on_first_decl)
4267 << SEA;
4268 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4269 }
4270
4271 // (C++98 8.3.5p3):
4272 // All declarations for a function shall agree exactly in both the
4273 // return type and the parameter-type-list.
4274 // We also want to respect all the extended bits except noreturn.
4275
4276 // noreturn should now match unless the old type info didn't have it.
4277 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4278 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4279 const FunctionType *OldTypeForComparison
4280 = Context.adjustFunctionType(Fn: OldType, EInfo: OldTypeInfo.withNoReturn(noReturn: true));
4281 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4282 assert(OldQTypeForComparison.isCanonical());
4283 }
4284
4285 if (haveIncompatibleLanguageLinkages(Old, New)) {
4286 // As a special case, retain the language linkage from previous
4287 // declarations of a friend function as an extension.
4288 //
4289 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4290 // and is useful because there's otherwise no way to specify language
4291 // linkage within class scope.
4292 //
4293 // Check cautiously as the friend object kind isn't yet complete.
4294 if (New->getFriendObjectKind() != Decl::FOK_None) {
4295 Diag(Loc: New->getLocation(), DiagID: diag::ext_retained_language_linkage) << New;
4296 Diag(Loc: OldLocation, DiagID: PrevDiag);
4297 } else {
4298 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4299 Diag(Loc: OldLocation, DiagID: PrevDiag);
4300 return true;
4301 }
4302 }
4303
4304 // HLSL check parameters for matching ABI specifications.
4305 if (getLangOpts().HLSL) {
4306 if (HLSL().CheckCompatibleParameterABI(New, Old))
4307 return true;
4308
4309 // If no errors are generated when checking parameter ABIs we can check if
4310 // the two declarations have the same type ignoring the ABIs and if so,
4311 // the declarations can be merged. This case for merging is only valid in
4312 // HLSL because there are no valid cases of merging mismatched parameter
4313 // ABIs except the HLSL implicit in and explicit in.
4314 if (Context.hasSameFunctionTypeIgnoringParamABI(T: OldQTypeForComparison,
4315 U: NewQType))
4316 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4317 // Fall through for conflicting redeclarations and redefinitions.
4318 }
4319
4320 // If the function types are compatible, merge the declarations. Ignore the
4321 // exception specifier because it was already checked above in
4322 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4323 // about incompatible types under -fms-compatibility.
4324 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(T: OldQTypeForComparison,
4325 U: NewQType))
4326 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4327
4328 // If the types are imprecise (due to dependent constructs in friends or
4329 // local extern declarations), it's OK if they differ. We'll check again
4330 // during instantiation.
4331 if (!canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewQType, OldT: OldQType))
4332 return false;
4333
4334 // Fall through for conflicting redeclarations and redefinitions.
4335 }
4336
4337 // C: Function types need to be compatible, not identical. This handles
4338 // duplicate function decls like "void f(int); void f(enum X);" properly.
4339 if (!getLangOpts().CPlusPlus) {
4340 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4341 // type is specified by a function definition that contains a (possibly
4342 // empty) identifier list, both shall agree in the number of parameters
4343 // and the type of each parameter shall be compatible with the type that
4344 // results from the application of default argument promotions to the
4345 // type of the corresponding identifier. ...
4346 // This cannot be handled by ASTContext::typesAreCompatible() because that
4347 // doesn't know whether the function type is for a definition or not when
4348 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4349 // we need to cover here is that the number of arguments agree as the
4350 // default argument promotion rules were already checked by
4351 // ASTContext::typesAreCompatible().
4352 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4353 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4354 if (Old->hasInheritedPrototype())
4355 Old = Old->getCanonicalDecl();
4356 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4357 Diag(Loc: Old->getLocation(), DiagID: PrevDiag) << Old << Old->getType();
4358 return true;
4359 }
4360
4361 // If we are merging two functions where only one of them has a prototype,
4362 // we may have enough information to decide to issue a diagnostic that the
4363 // function without a prototype will change behavior in C23. This handles
4364 // cases like:
4365 // void i(); void i(int j);
4366 // void i(int j); void i();
4367 // void i(); void i(int j) {}
4368 // See ActOnFinishFunctionBody() for other cases of the behavior change
4369 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4370 // type without a prototype.
4371 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4372 !New->isImplicit() && !Old->isImplicit()) {
4373 const FunctionDecl *WithProto, *WithoutProto;
4374 if (New->hasWrittenPrototype()) {
4375 WithProto = New;
4376 WithoutProto = Old;
4377 } else {
4378 WithProto = Old;
4379 WithoutProto = New;
4380 }
4381
4382 if (WithProto->getNumParams() != 0) {
4383 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4384 // The one without the prototype will be changing behavior in C23, so
4385 // warn about that one so long as it's a user-visible declaration.
4386 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4387 if (WithoutProto == New)
4388 IsWithoutProtoADef = NewDeclIsDefn;
4389 else
4390 IsWithProtoADef = NewDeclIsDefn;
4391 Diag(Loc: WithoutProto->getLocation(),
4392 DiagID: diag::warn_non_prototype_changes_behavior)
4393 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4394 << (WithoutProto == Old) << IsWithProtoADef;
4395
4396 // The reason the one without the prototype will be changing behavior
4397 // is because of the one with the prototype, so note that so long as
4398 // it's a user-visible declaration. There is one exception to this:
4399 // when the new declaration is a definition without a prototype, the
4400 // old declaration with a prototype is not the cause of the issue,
4401 // and that does not need to be noted because the one with a
4402 // prototype will not change behavior in C23.
4403 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4404 !IsWithoutProtoADef)
4405 Diag(Loc: WithProto->getLocation(), DiagID: diag::note_conflicting_prototype);
4406 }
4407 }
4408 }
4409
4410 if (Context.typesAreCompatible(T1: OldQType, T2: NewQType)) {
4411 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4412 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4413 const FunctionProtoType *OldProto = nullptr;
4414 if (MergeTypeWithOld && isa<FunctionNoProtoType>(Val: NewFuncType) &&
4415 (OldProto = dyn_cast<FunctionProtoType>(Val: OldFuncType))) {
4416 // The old declaration provided a function prototype, but the
4417 // new declaration does not. Merge in the prototype.
4418 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4419 NewQType = Context.getFunctionType(ResultTy: NewFuncType->getReturnType(),
4420 Args: OldProto->getParamTypes(),
4421 EPI: OldProto->getExtProtoInfo());
4422 New->setType(NewQType);
4423 New->setHasInheritedPrototype();
4424
4425 // Synthesize parameters with the same types.
4426 SmallVector<ParmVarDecl *, 16> Params;
4427 for (const auto &ParamType : OldProto->param_types()) {
4428 ParmVarDecl *Param = ParmVarDecl::Create(
4429 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
4430 T: ParamType, /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
4431 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
4432 Param->setImplicit();
4433 Params.push_back(Elt: Param);
4434 }
4435
4436 New->setParams(Params);
4437 }
4438
4439 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4440 }
4441 }
4442
4443 // Check if the function types are compatible when pointer size address
4444 // spaces are ignored.
4445 if (Context.hasSameFunctionTypeIgnoringPtrSizes(T: OldQType, U: NewQType))
4446 return false;
4447
4448 // GNU C permits a K&R definition to follow a prototype declaration
4449 // if the declared types of the parameters in the K&R definition
4450 // match the types in the prototype declaration, even when the
4451 // promoted types of the parameters from the K&R definition differ
4452 // from the types in the prototype. GCC then keeps the types from
4453 // the prototype.
4454 //
4455 // If a variadic prototype is followed by a non-variadic K&R definition,
4456 // the K&R definition becomes variadic. This is sort of an edge case, but
4457 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4458 // C99 6.9.1p8.
4459 if (!getLangOpts().CPlusPlus &&
4460 Old->hasPrototype() && !New->hasPrototype() &&
4461 New->getType()->getAs<FunctionProtoType>() &&
4462 Old->getNumParams() == New->getNumParams()) {
4463 SmallVector<QualType, 16> ArgTypes;
4464 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4465 const FunctionProtoType *OldProto
4466 = Old->getType()->getAs<FunctionProtoType>();
4467 const FunctionProtoType *NewProto
4468 = New->getType()->getAs<FunctionProtoType>();
4469
4470 // Determine whether this is the GNU C extension.
4471 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4472 NewProto->getReturnType());
4473 bool LooseCompatible = !MergedReturn.isNull();
4474 for (unsigned Idx = 0, End = Old->getNumParams();
4475 LooseCompatible && Idx != End; ++Idx) {
4476 ParmVarDecl *OldParm = Old->getParamDecl(i: Idx);
4477 ParmVarDecl *NewParm = New->getParamDecl(i: Idx);
4478 if (Context.typesAreCompatible(T1: OldParm->getType(),
4479 T2: NewProto->getParamType(i: Idx))) {
4480 ArgTypes.push_back(Elt: NewParm->getType());
4481 } else if (Context.typesAreCompatible(T1: OldParm->getType(),
4482 T2: NewParm->getType(),
4483 /*CompareUnqualified=*/true)) {
4484 GNUCompatibleParamWarning Warn = { .OldParm: OldParm, .NewParm: NewParm,
4485 .PromotedType: NewProto->getParamType(i: Idx) };
4486 Warnings.push_back(Elt: Warn);
4487 ArgTypes.push_back(Elt: NewParm->getType());
4488 } else
4489 LooseCompatible = false;
4490 }
4491
4492 if (LooseCompatible) {
4493 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4494 Diag(Loc: Warnings[Warn].NewParm->getLocation(),
4495 DiagID: diag::ext_param_promoted_not_compatible_with_prototype)
4496 << Warnings[Warn].PromotedType
4497 << Warnings[Warn].OldParm->getType();
4498 if (Warnings[Warn].OldParm->getLocation().isValid())
4499 Diag(Loc: Warnings[Warn].OldParm->getLocation(),
4500 DiagID: diag::note_previous_declaration);
4501 }
4502
4503 if (MergeTypeWithOld)
4504 New->setType(Context.getFunctionType(ResultTy: MergedReturn, Args: ArgTypes,
4505 EPI: OldProto->getExtProtoInfo()));
4506 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4507 }
4508
4509 // Fall through to diagnose conflicting types.
4510 }
4511
4512 // A function that has already been declared has been redeclared or
4513 // defined with a different type; show an appropriate diagnostic.
4514
4515 // If the previous declaration was an implicitly-generated builtin
4516 // declaration, then at the very least we should use a specialized note.
4517 unsigned BuiltinID;
4518 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4519 // If it's actually a library-defined builtin function like 'malloc'
4520 // or 'printf', just warn about the incompatible redeclaration.
4521 if (Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) {
4522 Diag(Loc: New->getLocation(), DiagID: diag::warn_redecl_library_builtin) << New;
4523 Diag(Loc: OldLocation, DiagID: diag::note_previous_builtin_declaration)
4524 << Old << Old->getType();
4525 return false;
4526 }
4527
4528 PrevDiag = diag::note_previous_builtin_declaration;
4529 }
4530
4531 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New->getDeclName();
4532 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4533 return true;
4534}
4535
4536bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4537 Scope *S, bool MergeTypeWithOld) {
4538 // Merge the attributes
4539 mergeDeclAttributes(New, Old);
4540
4541 // Merge "pure" flag.
4542 if (Old->isPureVirtual())
4543 New->setIsPureVirtual();
4544
4545 // Merge "used" flag.
4546 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4547 New->setIsUsed();
4548
4549 // Merge attributes from the parameters. These can mismatch with K&R
4550 // declarations.
4551 if (New->getNumParams() == Old->getNumParams())
4552 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4553 ParmVarDecl *NewParam = New->getParamDecl(i);
4554 ParmVarDecl *OldParam = Old->getParamDecl(i);
4555 mergeParamDeclAttributes(newDecl: NewParam, oldDecl: OldParam, S&: *this);
4556 mergeParamDeclTypes(NewParam, OldParam, S&: *this);
4557 }
4558
4559 if (getLangOpts().CPlusPlus)
4560 return MergeCXXFunctionDecl(New, Old, S);
4561
4562 // Merge the function types so the we get the composite types for the return
4563 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4564 // was visible.
4565 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4566 if (!Merged.isNull() && MergeTypeWithOld)
4567 New->setType(Merged);
4568
4569 return false;
4570}
4571
4572void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4573 ObjCMethodDecl *oldMethod) {
4574 // Merge the attributes, including deprecated/unavailable
4575 AvailabilityMergeKind MergeKind =
4576 isa<ObjCProtocolDecl>(Val: oldMethod->getDeclContext())
4577 ? (oldMethod->isOptional()
4578 ? AvailabilityMergeKind::OptionalProtocolImplementation
4579 : AvailabilityMergeKind::ProtocolImplementation)
4580 : isa<ObjCImplDecl>(Val: newMethod->getDeclContext())
4581 ? AvailabilityMergeKind::Redeclaration
4582 : AvailabilityMergeKind::Override;
4583
4584 mergeDeclAttributes(New: newMethod, Old: oldMethod, AMK: MergeKind);
4585
4586 // Merge attributes from the parameters.
4587 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4588 oe = oldMethod->param_end();
4589 for (ObjCMethodDecl::param_iterator
4590 ni = newMethod->param_begin(), ne = newMethod->param_end();
4591 ni != ne && oi != oe; ++ni, ++oi)
4592 mergeParamDeclAttributes(newDecl: *ni, oldDecl: *oi, S&: *this);
4593
4594 ObjC().CheckObjCMethodOverride(NewMethod: newMethod, Overridden: oldMethod);
4595}
4596
4597static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4598 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4599
4600 S.Diag(Loc: New->getLocation(), DiagID: New->isThisDeclarationADefinition()
4601 ? diag::err_redefinition_different_type
4602 : diag::err_redeclaration_different_type)
4603 << New->getDeclName() << New->getType() << Old->getType();
4604
4605 diag::kind PrevDiag;
4606 SourceLocation OldLocation;
4607 std::tie(args&: PrevDiag, args&: OldLocation)
4608 = getNoteDiagForInvalidRedeclaration(Old, New);
4609 S.Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4610 New->setInvalidDecl();
4611}
4612
4613void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4614 bool MergeTypeWithOld) {
4615 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4616 return;
4617
4618 QualType MergedT;
4619 if (getLangOpts().CPlusPlus) {
4620 if (New->getType()->isUndeducedType()) {
4621 // We don't know what the new type is until the initializer is attached.
4622 return;
4623 } else if (Context.hasSameType(T1: New->getType(), T2: Old->getType())) {
4624 // These could still be something that needs exception specs checked.
4625 return MergeVarDeclExceptionSpecs(New, Old);
4626 }
4627 // C++ [basic.link]p10:
4628 // [...] the types specified by all declarations referring to a given
4629 // object or function shall be identical, except that declarations for an
4630 // array object can specify array types that differ by the presence or
4631 // absence of a major array bound (8.3.4).
4632 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4633 const ArrayType *OldArray = Context.getAsArrayType(T: Old->getType());
4634 const ArrayType *NewArray = Context.getAsArrayType(T: New->getType());
4635
4636 // We are merging a variable declaration New into Old. If it has an array
4637 // bound, and that bound differs from Old's bound, we should diagnose the
4638 // mismatch.
4639 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4640 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4641 PrevVD = PrevVD->getPreviousDecl()) {
4642 QualType PrevVDTy = PrevVD->getType();
4643 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4644 continue;
4645
4646 if (!Context.hasSameType(T1: New->getType(), T2: PrevVDTy))
4647 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old: PrevVD);
4648 }
4649 }
4650
4651 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4652 if (Context.hasSameType(T1: OldArray->getElementType(),
4653 T2: NewArray->getElementType()))
4654 MergedT = New->getType();
4655 }
4656 // FIXME: Check visibility. New is hidden but has a complete type. If New
4657 // has no array bound, it should not inherit one from Old, if Old is not
4658 // visible.
4659 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4660 if (Context.hasSameType(T1: OldArray->getElementType(),
4661 T2: NewArray->getElementType()))
4662 MergedT = Old->getType();
4663 }
4664 }
4665 else if (New->getType()->isObjCObjectPointerType() &&
4666 Old->getType()->isObjCObjectPointerType()) {
4667 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4668 Old->getType());
4669 }
4670 } else {
4671 // C 6.2.7p2:
4672 // All declarations that refer to the same object or function shall have
4673 // compatible type.
4674 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4675 }
4676 if (MergedT.isNull()) {
4677 // It's OK if we couldn't merge types if either type is dependent, for a
4678 // block-scope variable. In other cases (static data members of class
4679 // templates, variable templates, ...), we require the types to be
4680 // equivalent.
4681 // FIXME: The C++ standard doesn't say anything about this.
4682 if ((New->getType()->isDependentType() ||
4683 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4684 // If the old type was dependent, we can't merge with it, so the new type
4685 // becomes dependent for now. We'll reproduce the original type when we
4686 // instantiate the TypeSourceInfo for the variable.
4687 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4688 New->setType(Context.DependentTy);
4689 return;
4690 }
4691 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old);
4692 }
4693
4694 // Don't actually update the type on the new declaration if the old
4695 // declaration was an extern declaration in a different scope.
4696 if (MergeTypeWithOld)
4697 New->setType(MergedT);
4698}
4699
4700static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4701 LookupResult &Previous) {
4702 // C11 6.2.7p4:
4703 // For an identifier with internal or external linkage declared
4704 // in a scope in which a prior declaration of that identifier is
4705 // visible, if the prior declaration specifies internal or
4706 // external linkage, the type of the identifier at the later
4707 // declaration becomes the composite type.
4708 //
4709 // If the variable isn't visible, we do not merge with its type.
4710 if (Previous.isShadowed())
4711 return false;
4712
4713 if (S.getLangOpts().CPlusPlus) {
4714 // C++11 [dcl.array]p3:
4715 // If there is a preceding declaration of the entity in the same
4716 // scope in which the bound was specified, an omitted array bound
4717 // is taken to be the same as in that earlier declaration.
4718 return NewVD->isPreviousDeclInSameBlockScope() ||
4719 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4720 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4721 } else {
4722 // If the old declaration was function-local, don't merge with its
4723 // type unless we're in the same function.
4724 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4725 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4726 }
4727}
4728
4729void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4730 // If the new decl is already invalid, don't do any other checking.
4731 if (New->isInvalidDecl())
4732 return;
4733
4734 if (!shouldLinkPossiblyHiddenDecl(Old&: Previous, New))
4735 return;
4736
4737 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4738
4739 // Verify the old decl was also a variable or variable template.
4740 VarDecl *Old = nullptr;
4741 VarTemplateDecl *OldTemplate = nullptr;
4742 if (Previous.isSingleResult()) {
4743 if (NewTemplate) {
4744 OldTemplate = dyn_cast<VarTemplateDecl>(Val: Previous.getFoundDecl());
4745 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4746
4747 if (auto *Shadow =
4748 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4749 if (checkUsingShadowRedecl<VarTemplateDecl>(S&: *this, OldS: Shadow, New: NewTemplate))
4750 return New->setInvalidDecl();
4751 } else {
4752 Old = dyn_cast<VarDecl>(Val: Previous.getFoundDecl());
4753
4754 if (auto *Shadow =
4755 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4756 if (checkUsingShadowRedecl<VarDecl>(S&: *this, OldS: Shadow, New))
4757 return New->setInvalidDecl();
4758 }
4759 }
4760 if (!Old) {
4761 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
4762 << New->getDeclName();
4763 notePreviousDefinition(Old: Previous.getRepresentativeDecl(),
4764 New: New->getLocation());
4765 return New->setInvalidDecl();
4766 }
4767
4768 // If the old declaration was found in an inline namespace and the new
4769 // declaration was qualified, update the DeclContext to match.
4770 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
4771
4772 // Ensure the template parameters are compatible.
4773 if (NewTemplate &&
4774 !TemplateParameterListsAreEqual(New: NewTemplate->getTemplateParameters(),
4775 Old: OldTemplate->getTemplateParameters(),
4776 /*Complain=*/true, Kind: TPL_TemplateMatch))
4777 return New->setInvalidDecl();
4778
4779 // C++ [class.mem]p1:
4780 // A member shall not be declared twice in the member-specification [...]
4781 //
4782 // Here, we need only consider static data members.
4783 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4784 Diag(Loc: New->getLocation(), DiagID: diag::err_duplicate_member)
4785 << New->getIdentifier();
4786 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4787 New->setInvalidDecl();
4788 }
4789
4790 if (NewTemplate && OldTemplate)
4791 mergeDeclAttributes(New: NewTemplate, Old: OldTemplate);
4792
4793 mergeDeclAttributes(New, Old);
4794
4795 // Warn if an already-defined variable is made a weak_import in a subsequent
4796 // declaration
4797 if (New->hasAttr<WeakImportAttr>())
4798 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4799 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4800 Diag(Loc: New->getLocation(), DiagID: diag::warn_weak_import) << New->getDeclName();
4801 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
4802 // Remove weak_import attribute on new declaration.
4803 New->dropAttr<WeakImportAttr>();
4804 break;
4805 }
4806 }
4807
4808 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4809 if (!Old->hasAttr<InternalLinkageAttr>()) {
4810 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4811 << ILA;
4812 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4813 New->dropAttr<InternalLinkageAttr>();
4814 }
4815
4816 // Merge the types.
4817 VarDecl *MostRecent = Old->getMostRecentDecl();
4818 if (MostRecent != Old) {
4819 MergeVarDeclTypes(New, Old: MostRecent,
4820 MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: MostRecent, Previous));
4821 if (New->isInvalidDecl())
4822 return;
4823 }
4824
4825 MergeVarDeclTypes(New, Old, MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: Old, Previous));
4826 if (New->isInvalidDecl())
4827 return;
4828
4829 diag::kind PrevDiag;
4830 SourceLocation OldLocation;
4831 std::tie(args&: PrevDiag, args&: OldLocation) =
4832 getNoteDiagForInvalidRedeclaration(Old, New);
4833
4834 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4835 if (New->getStorageClass() == SC_Static &&
4836 !New->isStaticDataMember() &&
4837 Old->hasExternalFormalLinkage()) {
4838 if (getLangOpts().MicrosoftExt) {
4839 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static)
4840 << New->getDeclName();
4841 Diag(Loc: OldLocation, DiagID: PrevDiag);
4842 } else {
4843 // This is the same internal/external linkage conflict as C2y 6.7.1p7;
4844 // before C2y it was undefined behavior (C11 6.2.2p7), so note that in
4845 // the older C language modes.
4846 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static)
4847 << New->getDeclName()
4848 << (!getLangOpts().CPlusPlus && !getLangOpts().C2y);
4849 Diag(Loc: OldLocation, DiagID: PrevDiag);
4850 return New->setInvalidDecl();
4851 }
4852 }
4853
4854 // C2y 6.7.1p7: an identifier shall not appear with both internal and
4855 // external linkage within a translation unit. Before C2y this was UB
4856 // (C11 6.2.2p7).
4857 //
4858 // In C, a local shadow prevents a block-scope extern from inheriting the
4859 // file-scope static's internal linkage (C2y 6.2.2p6), so it defaults to
4860 // external linkage, creating the conflict.
4861 //
4862 // In C++, block-scope extern declarations target the enclosing namespace
4863 // scope ([dcl.meaning.general]/3.5), bypassing local shadows entirely, so
4864 // the extern always inherits internal linkage. No conflict arises.
4865 if (!getLangOpts().CPlusPlus && New->isLocalVarDecl() &&
4866 New->hasExternalStorage() && Previous.isShadowed() &&
4867 Old->getFormalLinkage() == Linkage::Internal) {
4868 Diag(Loc: New->getLocation(), DiagID: diag::err_internal_extern_mismatch)
4869 << New->getDeclName() << getLangOpts().C2y;
4870 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
4871 return New->setInvalidDecl();
4872 }
4873
4874 // C99 6.2.2p4:
4875 // For an identifier declared with the storage-class specifier
4876 // extern in a scope in which a prior declaration of that
4877 // identifier is visible,23) if the prior declaration specifies
4878 // internal or external linkage, the linkage of the identifier at
4879 // the later declaration is the same as the linkage specified at
4880 // the prior declaration. If no prior declaration is visible, or
4881 // if the prior declaration specifies no linkage, then the
4882 // identifier has external linkage.
4883 if (New->hasExternalStorage() && Old->hasLinkage())
4884 /* Okay */;
4885 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4886 !New->isStaticDataMember() &&
4887 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4888 Diag(Loc: New->getLocation(), DiagID: diag::err_non_static_static) << New->getDeclName();
4889 Diag(Loc: OldLocation, DiagID: PrevDiag);
4890 return New->setInvalidDecl();
4891 }
4892
4893 // Check if extern is followed by non-extern and vice-versa.
4894 if (New->hasExternalStorage() &&
4895 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4896 Diag(Loc: New->getLocation(), DiagID: diag::err_extern_non_extern) << New->getDeclName();
4897 Diag(Loc: OldLocation, DiagID: PrevDiag);
4898 return New->setInvalidDecl();
4899 }
4900 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4901 !New->hasExternalStorage()) {
4902 Diag(Loc: New->getLocation(), DiagID: diag::err_non_extern_extern) << New->getDeclName();
4903 Diag(Loc: OldLocation, DiagID: PrevDiag);
4904 return New->setInvalidDecl();
4905 }
4906
4907 if (CheckRedeclarationInModule(New, Old))
4908 return;
4909
4910 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4911
4912 // FIXME: The test for external storage here seems wrong? We still
4913 // need to check for mismatches.
4914 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4915 // Don't complain about out-of-line definitions of static members.
4916 !(Old->getLexicalDeclContext()->isRecord() &&
4917 !New->getLexicalDeclContext()->isRecord())) {
4918 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New->getDeclName();
4919 Diag(Loc: OldLocation, DiagID: PrevDiag);
4920 return New->setInvalidDecl();
4921 }
4922
4923 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4924 if (VarDecl *Def = Old->getDefinition()) {
4925 // C++1z [dcl.fcn.spec]p4:
4926 // If the definition of a variable appears in a translation unit before
4927 // its first declaration as inline, the program is ill-formed.
4928 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
4929 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
4930 }
4931 }
4932
4933 // If this redeclaration makes the variable inline, we may need to add it to
4934 // UndefinedButUsed.
4935 if (!Old->isInline() && New->isInline() && Old->isUsed(CheckUsedAttr: false) &&
4936 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4937 !Old->isInAnotherModuleUnit())
4938 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4939 y: SourceLocation()));
4940
4941 if (New->getTLSKind() != Old->getTLSKind()) {
4942 if (!Old->getTLSKind()) {
4943 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_non_thread) << New->getDeclName();
4944 Diag(Loc: OldLocation, DiagID: PrevDiag);
4945 } else if (!New->getTLSKind()) {
4946 Diag(Loc: New->getLocation(), DiagID: diag::err_non_thread_thread) << New->getDeclName();
4947 Diag(Loc: OldLocation, DiagID: PrevDiag);
4948 } else {
4949 // Do not allow redeclaration to change the variable between requiring
4950 // static and dynamic initialization.
4951 // FIXME: GCC allows this, but uses the TLS keyword on the first
4952 // declaration to determine the kind. Do we need to be compatible here?
4953 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_thread_different_kind)
4954 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4955 Diag(Loc: OldLocation, DiagID: PrevDiag);
4956 }
4957 }
4958
4959 // C++ doesn't have tentative definitions, so go right ahead and check here.
4960 if (getLangOpts().CPlusPlus) {
4961 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4962 Old->getCanonicalDecl()->isConstexpr()) {
4963 // This definition won't be a definition any more once it's been merged.
4964 Diag(Loc: New->getLocation(),
4965 DiagID: diag::warn_deprecated_redundant_constexpr_static_def);
4966 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4967 VarDecl *Def = Old->getDefinition();
4968 if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New))
4969 return;
4970 if (Old->isInvalidDecl())
4971 New->setInvalidDecl();
4972 }
4973 } else {
4974 // C++ may not have a tentative definition rule, but it has a different
4975 // rule about what constitutes a definition in the first place. See
4976 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4977 // contains the extern specifier and doesn't have an initializer, it's fine
4978 // in C++.
4979 if (New->getTLSKind() != VarDecl::TLS_None &&
4980 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4981 VarDecl *Def = Old->getDefinition();
4982 if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New)) {
4983 return;
4984 }
4985 } else if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4986 Diag(Loc: New->getLocation(), DiagID: diag::warn_cxx_compat_tentative_definition)
4987 << New;
4988 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4989 }
4990 }
4991
4992 if (haveIncompatibleLanguageLinkages(Old, New)) {
4993 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4994 Diag(Loc: OldLocation, DiagID: PrevDiag);
4995 New->setInvalidDecl();
4996 return;
4997 }
4998
4999 // Merge "used" flag.
5000 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
5001 New->setIsUsed();
5002
5003 // Keep a chain of previous declarations.
5004 New->setPreviousDecl(Old);
5005 if (NewTemplate)
5006 NewTemplate->setPreviousDecl(OldTemplate);
5007
5008 // Inherit access appropriately.
5009 New->setAccess(Old->getAccess());
5010 if (NewTemplate)
5011 NewTemplate->setAccess(New->getAccess());
5012
5013 if (Old->isInline())
5014 New->setImplicitlyInline();
5015}
5016
5017void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
5018 SourceManager &SrcMgr = getSourceManager();
5019 auto FNewDecLoc = SrcMgr.getDecomposedLoc(Loc: New);
5020 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Loc: Old->getLocation());
5021 auto *FNew = SrcMgr.getFileEntryForID(FID: FNewDecLoc.first);
5022 auto FOld = SrcMgr.getFileEntryRefForID(FID: FOldDecLoc.first);
5023 auto &HSI = PP.getHeaderSearchInfo();
5024 StringRef HdrFilename =
5025 SrcMgr.getFilename(SpellingLoc: SrcMgr.getSpellingLoc(Loc: Old->getLocation()));
5026
5027 auto noteFromModuleOrInclude = [&](Module *Mod,
5028 SourceLocation IncLoc) -> bool {
5029 // Redefinition errors with modules are common with non modular mapped
5030 // headers, example: a non-modular header H in module A that also gets
5031 // included directly in a TU. Pointing twice to the same header/definition
5032 // is confusing, try to get better diagnostics when modules is on.
5033 if (IncLoc.isValid()) {
5034 if (Mod) {
5035 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_modules_same_file)
5036 << HdrFilename.str() << Mod->getFullModuleName();
5037 if (!Mod->DefinitionLoc.isInvalid())
5038 Diag(Loc: Mod->DefinitionLoc, DiagID: diag::note_defined_here)
5039 << Mod->getFullModuleName();
5040 } else {
5041 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_include_same_file)
5042 << HdrFilename.str();
5043 }
5044 return true;
5045 }
5046
5047 return false;
5048 };
5049
5050 // Is it the same file and same offset? Provide more information on why
5051 // this leads to a redefinition error.
5052 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
5053 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FID: FOldDecLoc.first);
5054 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FID: FNewDecLoc.first);
5055 bool EmittedDiag =
5056 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
5057 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
5058
5059 // If the header has no guards, emit a note suggesting one.
5060 if (FOld && !HSI.isFileMultipleIncludeGuarded(File: *FOld))
5061 Diag(Loc: Old->getLocation(), DiagID: diag::note_use_ifdef_guards);
5062
5063 if (EmittedDiag)
5064 return;
5065 }
5066
5067 // Redefinition coming from different files or couldn't do better above.
5068 if (Old->getLocation().isValid())
5069 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
5070}
5071
5072bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
5073 if ((!hasVisibleDefinition(D: Old) ||
5074 isFromSameSingleIncludeHeader(PrevD: Old, NewLoc: New->getLocation())) &&
5075 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
5076 isa<VarTemplateSpecializationDecl>(Val: New) ||
5077 New->getDescribedVarTemplate() ||
5078 !New->getTemplateParameterLists().empty() ||
5079 New->getDeclContext()->isDependentContext() ||
5080 New->hasAttr<SelectAnyAttr>())) {
5081 // The previous definition is hidden, and multiple definitions are
5082 // permitted (in separate TUs). Demote this to a declaration.
5083 New->demoteThisDefinitionToDeclaration();
5084
5085 // Make the canonical definition visible.
5086 if (auto *OldTD = Old->getDescribedVarTemplate())
5087 makeMergedDefinitionVisible(ND: OldTD);
5088 makeMergedDefinitionVisible(ND: Old);
5089 return false;
5090 } else {
5091 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New;
5092 notePreviousDefinition(Old, New: New->getLocation());
5093 New->setInvalidDecl();
5094 return true;
5095 }
5096}
5097
5098Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5099 DeclSpec &DS,
5100 const ParsedAttributesView &DeclAttrs,
5101 RecordDecl *&AnonRecord) {
5102 return ParsedFreeStandingDeclSpec(
5103 S, AS, DS, DeclAttrs, TemplateParams: MultiTemplateParamsArg(), IsExplicitInstantiation: false, AnonRecord);
5104}
5105
5106// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5107// disambiguate entities defined in different scopes.
5108// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5109// compatibility.
5110// We will pick our mangling number depending on which version of MSVC is being
5111// targeted.
5112static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5113 return LO.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015)
5114 ? S->getMSCurManglingNumber()
5115 : S->getMSLastManglingNumber();
5116}
5117
5118void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5119 if (!Context.getLangOpts().CPlusPlus)
5120 return;
5121
5122 if (isa<CXXRecordDecl>(Val: Tag->getParent())) {
5123 // If this tag is the direct child of a class, number it if
5124 // it is anonymous.
5125 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5126 return;
5127 MangleNumberingContext &MCtx =
5128 Context.getManglingNumberContext(DC: Tag->getParent());
5129 Context.setManglingNumber(
5130 ND: Tag, Number: MCtx.getManglingNumber(
5131 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5132 return;
5133 }
5134
5135 // If this tag isn't a direct child of a class, number it if it is local.
5136 MangleNumberingContext *MCtx;
5137 Decl *ManglingContextDecl;
5138 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5139 getCurrentMangleNumberContext(DC: Tag->getDeclContext());
5140 if (MCtx) {
5141 Context.setManglingNumber(
5142 ND: Tag, Number: MCtx->getManglingNumber(
5143 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5144 }
5145}
5146
5147namespace {
5148struct NonCLikeKind {
5149 enum {
5150 None,
5151 BaseClass,
5152 DefaultMemberInit,
5153 Lambda,
5154 Friend,
5155 OtherMember,
5156 Invalid,
5157 } Kind = None;
5158 SourceRange Range;
5159
5160 explicit operator bool() { return Kind != None; }
5161};
5162}
5163
5164/// Determine whether a class is C-like, according to the rules of C++
5165/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5166static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5167 if (RD->isInvalidDecl())
5168 return {.Kind: NonCLikeKind::Invalid, .Range: {}};
5169
5170 // C++ [dcl.typedef]p9: [P1766R1]
5171 // An unnamed class with a typedef name for linkage purposes shall not
5172 //
5173 // -- have any base classes
5174 if (RD->getNumBases())
5175 return {.Kind: NonCLikeKind::BaseClass,
5176 .Range: SourceRange(RD->bases_begin()->getBeginLoc(),
5177 RD->bases_end()[-1].getEndLoc())};
5178 bool Invalid = false;
5179 for (Decl *D : RD->decls()) {
5180 // Don't complain about things we already diagnosed.
5181 if (D->isInvalidDecl()) {
5182 Invalid = true;
5183 continue;
5184 }
5185
5186 // -- have any [...] default member initializers
5187 if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
5188 if (FD->hasInClassInitializer()) {
5189 auto *Init = FD->getInClassInitializer();
5190 return {.Kind: NonCLikeKind::DefaultMemberInit,
5191 .Range: Init ? Init->getSourceRange() : D->getSourceRange()};
5192 }
5193 continue;
5194 }
5195
5196 // FIXME: We don't allow friend declarations. This violates the wording of
5197 // P1766, but not the intent.
5198 if (isa<FriendDecl>(Val: D))
5199 return {.Kind: NonCLikeKind::Friend, .Range: D->getSourceRange()};
5200
5201 // -- declare any members other than non-static data members, member
5202 // enumerations, or member classes,
5203 if (isa<StaticAssertDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D) ||
5204 isa<EnumDecl>(Val: D))
5205 continue;
5206 auto *MemberRD = dyn_cast<CXXRecordDecl>(Val: D);
5207 if (!MemberRD) {
5208 if (D->isImplicit())
5209 continue;
5210 return {.Kind: NonCLikeKind::OtherMember, .Range: D->getSourceRange()};
5211 }
5212
5213 // -- contain a lambda-expression,
5214 if (MemberRD->isLambda())
5215 return {.Kind: NonCLikeKind::Lambda, .Range: MemberRD->getSourceRange()};
5216
5217 // and all member classes shall also satisfy these requirements
5218 // (recursively).
5219 if (MemberRD->isThisDeclarationADefinition()) {
5220 if (auto Kind = getNonCLikeKindForAnonymousStruct(RD: MemberRD))
5221 return Kind;
5222 }
5223 }
5224
5225 return {.Kind: Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, .Range: {}};
5226}
5227
5228void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5229 TypedefNameDecl *NewTD) {
5230 if (TagFromDeclSpec->isInvalidDecl())
5231 return;
5232
5233 // Do nothing if the tag already has a name for linkage purposes.
5234 if (TagFromDeclSpec->hasNameForLinkage())
5235 return;
5236
5237 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5238 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5239
5240 // The type must match the tag exactly; no qualifiers allowed.
5241 if (!Context.hasSameType(T1: NewTD->getUnderlyingType(),
5242 T2: Context.getCanonicalTagType(TD: TagFromDeclSpec))) {
5243 if (getLangOpts().CPlusPlus)
5244 Context.addTypedefNameForUnnamedTagDecl(TD: TagFromDeclSpec, TND: NewTD);
5245 return;
5246 }
5247
5248 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5249 // An unnamed class with a typedef name for linkage purposes shall [be
5250 // C-like].
5251 //
5252 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5253 // shouldn't happen, but there are constructs that the language rule doesn't
5254 // disallow for which we can't reasonably avoid computing linkage early.
5255 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TagFromDeclSpec);
5256 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5257 : NonCLikeKind();
5258 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5259 if (NonCLike || ChangesLinkage) {
5260 if (NonCLike.Kind == NonCLikeKind::Invalid)
5261 return;
5262
5263 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5264 if (ChangesLinkage) {
5265 // If the linkage changes, we can't accept this as an extension.
5266 if (NonCLike.Kind == NonCLikeKind::None)
5267 DiagID = diag::err_typedef_changes_linkage;
5268 else
5269 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5270 }
5271
5272 SourceLocation FixitLoc =
5273 getLocForEndOfToken(Loc: TagFromDeclSpec->getInnerLocStart());
5274 llvm::SmallString<40> TextToInsert;
5275 TextToInsert += ' ';
5276 TextToInsert += NewTD->getIdentifier()->getName();
5277
5278 Diag(Loc: FixitLoc, DiagID)
5279 << isa<TypeAliasDecl>(Val: NewTD)
5280 << FixItHint::CreateInsertion(InsertionLoc: FixitLoc, Code: TextToInsert);
5281 if (NonCLike.Kind != NonCLikeKind::None) {
5282 Diag(Loc: NonCLike.Range.getBegin(), DiagID: diag::note_non_c_like_anon_struct)
5283 << NonCLike.Kind - 1 << NonCLike.Range;
5284 }
5285 Diag(Loc: NewTD->getLocation(), DiagID: diag::note_typedef_for_linkage_here)
5286 << NewTD << isa<TypeAliasDecl>(Val: NewTD);
5287
5288 if (ChangesLinkage)
5289 return;
5290 }
5291
5292 // Otherwise, set this as the anon-decl typedef for the tag.
5293 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5294
5295 // Now that we have a name for the tag, process API notes again.
5296 ProcessAPINotes(D: TagFromDeclSpec);
5297}
5298
5299static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5300 DeclSpec::TST T = DS.getTypeSpecType();
5301 switch (T) {
5302 case DeclSpec::TST_class:
5303 return 0;
5304 case DeclSpec::TST_struct:
5305 return 1;
5306 case DeclSpec::TST_interface:
5307 return 2;
5308 case DeclSpec::TST_union:
5309 return 3;
5310 case DeclSpec::TST_enum:
5311 if (const auto *ED = dyn_cast<EnumDecl>(Val: DS.getRepAsDecl())) {
5312 if (ED->isScopedUsingClassTag())
5313 return 5;
5314 if (ED->isScoped())
5315 return 6;
5316 }
5317 return 4;
5318 default:
5319 llvm_unreachable("unexpected type specifier");
5320 }
5321}
5322
5323Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5324 DeclSpec &DS,
5325 const ParsedAttributesView &DeclAttrs,
5326 MultiTemplateParamsArg TemplateParams,
5327 bool IsExplicitInstantiation,
5328 RecordDecl *&AnonRecord,
5329 SourceLocation EllipsisLoc) {
5330 Decl *TagD = nullptr;
5331 TagDecl *Tag = nullptr;
5332 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5333 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5334 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5335 DS.getTypeSpecType() == DeclSpec::TST_union ||
5336 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5337 TagD = DS.getRepAsDecl();
5338
5339 if (!TagD) // We probably had an error
5340 return nullptr;
5341
5342 // Note that the above type specs guarantee that the
5343 // type rep is a Decl, whereas in many of the others
5344 // it's a Type.
5345 if (isa<TagDecl>(Val: TagD))
5346 Tag = cast<TagDecl>(Val: TagD);
5347 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: TagD))
5348 Tag = CTD->getTemplatedDecl();
5349 }
5350
5351 if (Tag) {
5352 handleTagNumbering(Tag, TagScope: S);
5353 Tag->setFreeStanding();
5354 if (Tag->isInvalidDecl())
5355 return Tag;
5356 }
5357
5358 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5359 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5360 // or incomplete types shall not be restrict-qualified."
5361 if (TypeQuals & DeclSpec::TQ_restrict)
5362 Diag(Loc: DS.getRestrictSpecLoc(),
5363 DiagID: diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5364 << DS.getSourceRange();
5365 }
5366
5367 if (DS.isInlineSpecified())
5368 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
5369 << getLangOpts().CPlusPlus17;
5370
5371 if (DS.hasConstexprSpecifier()) {
5372 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5373 // and definitions of functions and variables.
5374 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5375 // the declaration of a function or function template
5376 if (Tag)
5377 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_tag)
5378 << GetDiagnosticTypeSpecifierID(DS)
5379 << static_cast<int>(DS.getConstexprSpecifier());
5380 else if (getLangOpts().C23)
5381 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_c23_constexpr_not_variable);
5382 else
5383 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_wrong_decl_kind)
5384 << static_cast<int>(DS.getConstexprSpecifier());
5385 // Don't emit warnings after this error.
5386 return TagD;
5387 }
5388
5389 DiagnoseFunctionSpecifiers(DS);
5390
5391 if (DS.isFriendSpecified()) {
5392 // If we're dealing with a decl but not a TagDecl, assume that
5393 // whatever routines created it handled the friendship aspect.
5394 if (TagD && !Tag)
5395 return nullptr;
5396 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5397 }
5398
5399 assert(EllipsisLoc.isInvalid() &&
5400 "Friend ellipsis but not friend-specified?");
5401
5402 // Track whether this decl-specifier declares anything.
5403 bool DeclaresAnything = true;
5404
5405 // Handle anonymous struct definitions.
5406 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Val: Tag)) {
5407 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5408 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5409 if (getLangOpts().CPlusPlus ||
5410 Record->getDeclContext()->isRecord()) {
5411 // If CurContext is a DeclContext that can contain statements,
5412 // RecursiveASTVisitor won't visit the decls that
5413 // BuildAnonymousStructOrUnion() will put into CurContext.
5414 // Also store them here so that they can be part of the
5415 // DeclStmt that gets created in this case.
5416 // FIXME: Also return the IndirectFieldDecls created by
5417 // BuildAnonymousStructOr union, for the same reason?
5418 if (CurContext->isFunctionOrMethod())
5419 AnonRecord = Record;
5420 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5421 Policy: Context.getPrintingPolicy());
5422 }
5423
5424 DeclaresAnything = false;
5425 }
5426 }
5427
5428 // C11 6.7.2.1p2:
5429 // A struct-declaration that does not declare an anonymous structure or
5430 // anonymous union shall contain a struct-declarator-list.
5431 //
5432 // This rule also existed in C89 and C99; the grammar for struct-declaration
5433 // did not permit a struct-declaration without a struct-declarator-list.
5434 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5435 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5436 // Check for Microsoft C extension: anonymous struct/union member.
5437 // Handle 2 kinds of anonymous struct/union:
5438 // struct STRUCT;
5439 // union UNION;
5440 // and
5441 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5442 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5443 if ((Tag && Tag->getDeclName()) ||
5444 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5445 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Val: Tag)
5446 : DS.getRepAsType().get()->getAsRecordDecl();
5447 if (Record && getLangOpts().MSAnonymousStructs) {
5448 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_ms_anonymous_record)
5449 << Record->isUnion() << DS.getSourceRange();
5450 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5451 }
5452
5453 DeclaresAnything = false;
5454 }
5455 }
5456
5457 // Skip all the checks below if we have a type error.
5458 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5459 (TagD && TagD->isInvalidDecl()))
5460 return TagD;
5461
5462 if (getLangOpts().CPlusPlus &&
5463 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5464 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Val: Tag))
5465 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5466 !Enum->isInvalidDecl())
5467 DeclaresAnything = false;
5468
5469 if (!DS.isMissingDeclaratorOk()) {
5470 // Customize diagnostic for a typedef missing a name.
5471 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5472 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_typedef_without_a_name)
5473 << DS.getSourceRange();
5474 else
5475 DeclaresAnything = false;
5476 }
5477
5478 if (DS.isModulePrivateSpecified() &&
5479 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5480 Diag(Loc: DS.getModulePrivateSpecLoc(), DiagID: diag::err_module_private_local_class)
5481 << Tag->getTagKind()
5482 << FixItHint::CreateRemoval(RemoveRange: DS.getModulePrivateSpecLoc());
5483
5484 ActOnDocumentableDecl(D: TagD);
5485
5486 // C 6.7/2:
5487 // A declaration [...] shall declare at least a declarator [...], a tag,
5488 // or the members of an enumeration.
5489 // C++ [dcl.dcl]p3:
5490 // [If there are no declarators], and except for the declaration of an
5491 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5492 // names into the program, or shall redeclare a name introduced by a
5493 // previous declaration.
5494 if (!DeclaresAnything) {
5495 // In C, we allow this as a (popular) extension / bug. Don't bother
5496 // producing further diagnostics for redundant qualifiers after this.
5497 Diag(Loc: DS.getBeginLoc(), DiagID: (IsExplicitInstantiation || !TemplateParams.empty())
5498 ? diag::err_no_declarators
5499 : diag::ext_no_declarators)
5500 << DS.getSourceRange();
5501 return TagD;
5502 }
5503
5504 // C++ [dcl.stc]p1:
5505 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5506 // init-declarator-list of the declaration shall not be empty.
5507 // C++ [dcl.fct.spec]p1:
5508 // If a cv-qualifier appears in a decl-specifier-seq, the
5509 // init-declarator-list of the declaration shall not be empty.
5510 //
5511 // Spurious qualifiers here appear to be valid in C.
5512 unsigned DiagID = diag::warn_standalone_specifier;
5513 if (getLangOpts().CPlusPlus)
5514 DiagID = diag::ext_standalone_specifier;
5515
5516 // Note that a linkage-specification sets a storage class, but
5517 // 'extern "C" struct foo;' is actually valid and not theoretically
5518 // useless.
5519 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5520 if (SCS == DeclSpec::SCS_mutable)
5521 // Since mutable is not a viable storage class specifier in C, there is
5522 // no reason to treat it as an extension. Instead, diagnose as an error.
5523 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_nonmember);
5524 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5525 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID)
5526 << DeclSpec::getSpecifierName(S: SCS);
5527 }
5528
5529 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5530 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID)
5531 << DeclSpec::getSpecifierName(S: TSCS);
5532 if (DS.getTypeQualifiers()) {
5533 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5534 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "const";
5535 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5536 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "volatile";
5537 // Restrict is covered above.
5538 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5539 Diag(Loc: DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5540 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5541 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5542 }
5543
5544 // Warn about ignored type attributes, for example:
5545 // __attribute__((aligned)) struct A;
5546 // Attributes should be placed after tag to apply to type declaration.
5547 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5548 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5549 if (TypeSpecType == DeclSpec::TST_class ||
5550 TypeSpecType == DeclSpec::TST_struct ||
5551 TypeSpecType == DeclSpec::TST_interface ||
5552 TypeSpecType == DeclSpec::TST_union ||
5553 TypeSpecType == DeclSpec::TST_enum) {
5554
5555 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5556 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5557 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5558 DiagnosticId = diag::warn_attribute_ignored;
5559 else if (AL.isRegularKeywordAttribute())
5560 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5561 else
5562 DiagnosticId = diag::warn_declspec_attribute_ignored;
5563 Diag(Loc: AL.getLoc(), DiagID: DiagnosticId)
5564 << AL << GetDiagnosticTypeSpecifierID(DS);
5565 };
5566
5567 llvm::for_each(Range&: DS.getAttributes(), F: EmitAttributeDiagnostic);
5568 llvm::for_each(Range: DeclAttrs, F: EmitAttributeDiagnostic);
5569 }
5570 }
5571
5572 return TagD;
5573}
5574
5575/// We are trying to inject an anonymous member into the given scope;
5576/// check if there's an existing declaration that can't be overloaded.
5577///
5578/// \return true if this is a forbidden redeclaration
5579static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5580 DeclContext *Owner,
5581 DeclarationName Name,
5582 SourceLocation NameLoc, bool IsUnion,
5583 StorageClass SC) {
5584 LookupResult R(SemaRef, Name, NameLoc,
5585 Owner->isRecord() ? Sema::LookupMemberName
5586 : Sema::LookupOrdinaryName,
5587 RedeclarationKind::ForVisibleRedeclaration);
5588 if (!SemaRef.LookupName(R, S)) return false;
5589
5590 // Pick a representative declaration.
5591 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5592 assert(PrevDecl && "Expected a non-null Decl");
5593
5594 if (!SemaRef.isDeclInScope(D: PrevDecl, Ctx: Owner, S))
5595 return false;
5596
5597 if (SC == StorageClass::SC_None &&
5598 PrevDecl->isPlaceholderVar(LangOpts: SemaRef.getLangOpts()) &&
5599 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5600 if (!Owner->isRecord())
5601 SemaRef.DiagPlaceholderVariableDefinition(Loc: NameLoc);
5602 return false;
5603 }
5604
5605 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_anonymous_record_member_redecl)
5606 << IsUnion << Name;
5607 SemaRef.Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
5608
5609 return true;
5610}
5611
5612void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5613 if (auto *RD = dyn_cast_if_present<RecordDecl>(Val: D))
5614 DiagPlaceholderFieldDeclDefinitions(Record: RD);
5615}
5616
5617void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5618 if (!getLangOpts().CPlusPlus)
5619 return;
5620
5621 // This function can be parsed before we have validated the
5622 // structure as an anonymous struct
5623 if (Record->isAnonymousStructOrUnion())
5624 return;
5625
5626 const NamedDecl *First = 0;
5627 for (const Decl *D : Record->decls()) {
5628 const NamedDecl *ND = dyn_cast<NamedDecl>(Val: D);
5629 if (!ND || !ND->isPlaceholderVar(LangOpts: getLangOpts()))
5630 continue;
5631 if (!First)
5632 First = ND;
5633 else
5634 DiagPlaceholderVariableDefinition(Loc: ND->getLocation());
5635 }
5636}
5637
5638/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5639/// anonymous struct or union AnonRecord into the owning context Owner
5640/// and scope S. This routine will be invoked just after we realize
5641/// that an unnamed union or struct is actually an anonymous union or
5642/// struct, e.g.,
5643///
5644/// @code
5645/// union {
5646/// int i;
5647/// float f;
5648/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5649/// // f into the surrounding scope.x
5650/// @endcode
5651///
5652/// This routine is recursive, injecting the names of nested anonymous
5653/// structs/unions into the owning context and scope as well.
5654static bool
5655InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5656 RecordDecl *AnonRecord, AccessSpecifier AS,
5657 StorageClass SC,
5658 SmallVectorImpl<NamedDecl *> &Chaining) {
5659 bool Invalid = false;
5660
5661 // Look every FieldDecl and IndirectFieldDecl with a name.
5662 for (auto *D : AnonRecord->decls()) {
5663 if ((isa<FieldDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D)) &&
5664 cast<NamedDecl>(Val: D)->getDeclName()) {
5665 ValueDecl *VD = cast<ValueDecl>(Val: D);
5666 // C++ [class.union]p2:
5667 // The names of the members of an anonymous union shall be
5668 // distinct from the names of any other entity in the
5669 // scope in which the anonymous union is declared.
5670
5671 bool FieldInvalid = CheckAnonMemberRedeclaration(
5672 SemaRef, S, Owner, Name: VD->getDeclName(), NameLoc: VD->getLocation(),
5673 IsUnion: AnonRecord->isUnion(), SC);
5674 if (FieldInvalid)
5675 Invalid = true;
5676
5677 // Inject the IndirectFieldDecl even if invalid, because later
5678 // diagnostics may depend on it being present, see findDefaultInitializer.
5679
5680 // C++ [class.union]p2:
5681 // For the purpose of name lookup, after the anonymous union
5682 // definition, the members of the anonymous union are
5683 // considered to have been defined in the scope in which the
5684 // anonymous union is declared.
5685 unsigned OldChainingSize = Chaining.size();
5686 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(Val: VD))
5687 Chaining.append(in_start: IF->chain_begin(), in_end: IF->chain_end());
5688 else
5689 Chaining.push_back(Elt: VD);
5690
5691 assert(Chaining.size() >= 2);
5692 NamedDecl **NamedChain =
5693 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5694 for (unsigned i = 0; i < Chaining.size(); i++)
5695 NamedChain[i] = Chaining[i];
5696
5697 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5698 C&: SemaRef.Context, DC: Owner, L: VD->getLocation(), Id: VD->getIdentifier(),
5699 T: VD->getType(), CH: {NamedChain, Chaining.size()});
5700
5701 for (const auto *Attr : VD->attrs())
5702 IndirectField->addAttr(A: Attr->clone(C&: SemaRef.Context));
5703
5704 IndirectField->setAccess(AS);
5705 IndirectField->setImplicit();
5706 IndirectField->setInvalidDecl(FieldInvalid);
5707 SemaRef.PushOnScopeChains(D: IndirectField, S);
5708
5709 // That includes picking up the appropriate access specifier.
5710 if (AS != AS_none)
5711 IndirectField->setAccess(AS);
5712
5713 Chaining.resize(N: OldChainingSize);
5714 }
5715 }
5716
5717 return Invalid;
5718}
5719
5720/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5721/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5722/// illegal input values are mapped to SC_None.
5723static StorageClass
5724StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5725 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5726 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5727 "Parser allowed 'typedef' as storage class VarDecl.");
5728 switch (StorageClassSpec) {
5729 case DeclSpec::SCS_unspecified: return SC_None;
5730 case DeclSpec::SCS_extern:
5731 if (DS.isExternInLinkageSpec())
5732 return SC_None;
5733 return SC_Extern;
5734 case DeclSpec::SCS_static: return SC_Static;
5735 case DeclSpec::SCS_auto: return SC_Auto;
5736 case DeclSpec::SCS_register: return SC_Register;
5737 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5738 // Illegal SCSs map to None: error reporting is up to the caller.
5739 case DeclSpec::SCS_mutable: // Fall through.
5740 case DeclSpec::SCS_typedef: return SC_None;
5741 }
5742 llvm_unreachable("unknown storage class specifier");
5743}
5744
5745static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5746 assert(Record->hasInClassInitializer());
5747
5748 for (const auto *I : Record->decls()) {
5749 const auto *FD = dyn_cast<FieldDecl>(Val: I);
5750 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
5751 FD = IFD->getAnonField();
5752 if (FD && FD->hasInClassInitializer())
5753 return FD->getLocation();
5754 }
5755
5756 llvm_unreachable("couldn't find in-class initializer");
5757}
5758
5759static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5760 SourceLocation DefaultInitLoc) {
5761 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5762 return;
5763
5764 S.Diag(Loc: DefaultInitLoc, DiagID: diag::err_multiple_mem_union_initialization);
5765 S.Diag(Loc: findDefaultInitializer(Record: Parent), DiagID: diag::note_previous_initializer) << 0;
5766}
5767
5768static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5769 CXXRecordDecl *AnonUnion) {
5770 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5771 return;
5772
5773 checkDuplicateDefaultInit(S, Parent, DefaultInitLoc: findDefaultInitializer(Record: AnonUnion));
5774}
5775
5776Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5777 AccessSpecifier AS,
5778 RecordDecl *Record,
5779 const PrintingPolicy &Policy) {
5780 DeclContext *Owner = Record->getDeclContext();
5781
5782 // Diagnose whether this anonymous struct/union is an extension.
5783 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5784 Diag(Loc: Record->getLocation(), DiagID: diag::ext_anonymous_union);
5785 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5786 Diag(Loc: Record->getLocation(), DiagID: diag::ext_gnu_anonymous_struct);
5787 else if (!Record->isUnion() && !getLangOpts().C11)
5788 Diag(Loc: Record->getLocation(), DiagID: diag::ext_c11_anonymous_struct);
5789
5790 // C and C++ require different kinds of checks for anonymous
5791 // structs/unions.
5792 bool Invalid = false;
5793 if (getLangOpts().CPlusPlus) {
5794 const char *PrevSpec = nullptr;
5795 if (Record->isUnion()) {
5796 // C++ [class.union]p6:
5797 // C++17 [class.union.anon]p2:
5798 // Anonymous unions declared in a named namespace or in the
5799 // global namespace shall be declared static.
5800 unsigned DiagID;
5801 DeclContext *OwnerScope = Owner->getRedeclContext();
5802 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5803 (OwnerScope->isTranslationUnit() ||
5804 (OwnerScope->isNamespace() &&
5805 !cast<NamespaceDecl>(Val: OwnerScope)->isAnonymousNamespace()))) {
5806 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_union_not_static)
5807 << FixItHint::CreateInsertion(InsertionLoc: Record->getLocation(), Code: "static ");
5808
5809 // Recover by adding 'static'.
5810 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_static, Loc: SourceLocation(),
5811 PrevSpec, DiagID, Policy);
5812 }
5813 // C++ [class.union]p6:
5814 // A storage class is not allowed in a declaration of an
5815 // anonymous union in a class scope.
5816 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5817 isa<RecordDecl>(Val: Owner)) {
5818 Diag(Loc: DS.getStorageClassSpecLoc(),
5819 DiagID: diag::err_anonymous_union_with_storage_spec)
5820 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
5821
5822 // Recover by removing the storage specifier.
5823 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_unspecified,
5824 Loc: SourceLocation(),
5825 PrevSpec, DiagID, Policy: Context.getPrintingPolicy());
5826 }
5827 }
5828
5829 // Ignore const/volatile/restrict qualifiers.
5830 if (DS.getTypeQualifiers()) {
5831 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5832 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::ext_anonymous_struct_union_qualified)
5833 << Record->isUnion() << "const"
5834 << FixItHint::CreateRemoval(RemoveRange: DS.getConstSpecLoc());
5835 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5836 Diag(Loc: DS.getVolatileSpecLoc(),
5837 DiagID: diag::ext_anonymous_struct_union_qualified)
5838 << Record->isUnion() << "volatile"
5839 << FixItHint::CreateRemoval(RemoveRange: DS.getVolatileSpecLoc());
5840 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5841 Diag(Loc: DS.getRestrictSpecLoc(),
5842 DiagID: diag::ext_anonymous_struct_union_qualified)
5843 << Record->isUnion() << "restrict"
5844 << FixItHint::CreateRemoval(RemoveRange: DS.getRestrictSpecLoc());
5845 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5846 Diag(Loc: DS.getAtomicSpecLoc(),
5847 DiagID: diag::ext_anonymous_struct_union_qualified)
5848 << Record->isUnion() << "_Atomic"
5849 << FixItHint::CreateRemoval(RemoveRange: DS.getAtomicSpecLoc());
5850 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5851 Diag(Loc: DS.getUnalignedSpecLoc(),
5852 DiagID: diag::ext_anonymous_struct_union_qualified)
5853 << Record->isUnion() << "__unaligned"
5854 << FixItHint::CreateRemoval(RemoveRange: DS.getUnalignedSpecLoc());
5855
5856 DS.ClearTypeQualifiers();
5857 }
5858
5859 // C++ [class.union]p2:
5860 // The member-specification of an anonymous union shall only
5861 // define non-static data members. [Note: nested types and
5862 // functions cannot be declared within an anonymous union. ]
5863 for (auto *Mem : Record->decls()) {
5864 // Ignore invalid declarations; we already diagnosed them.
5865 if (Mem->isInvalidDecl())
5866 continue;
5867
5868 if (auto *FD = dyn_cast<FieldDecl>(Val: Mem)) {
5869 // C++ [class.union]p3:
5870 // An anonymous union shall not have private or protected
5871 // members (clause 11).
5872 assert(FD->getAccess() != AS_none);
5873 if (FD->getAccess() != AS_public) {
5874 Diag(Loc: FD->getLocation(), DiagID: diag::err_anonymous_record_nonpublic_member)
5875 << Record->isUnion() << (FD->getAccess() == AS_protected);
5876 Invalid = true;
5877 }
5878
5879 // C++ [class.union]p1
5880 // An object of a class with a non-trivial constructor, a non-trivial
5881 // copy constructor, a non-trivial destructor, or a non-trivial copy
5882 // assignment operator cannot be a member of a union, nor can an
5883 // array of such objects.
5884 if (CheckNontrivialField(FD))
5885 Invalid = true;
5886 } else if (Mem->isImplicit()) {
5887 // Any implicit members are fine.
5888 } else if (isa<TagDecl>(Val: Mem) && Mem->getDeclContext() != Record) {
5889 // This is a type that showed up in an
5890 // elaborated-type-specifier inside the anonymous struct or
5891 // union, but which actually declares a type outside of the
5892 // anonymous struct or union. It's okay.
5893 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Val: Mem)) {
5894 if (!MemRecord->isAnonymousStructOrUnion() &&
5895 MemRecord->getDeclName()) {
5896 // Visual C++ allows type definition in anonymous struct or union.
5897 if (getLangOpts().MicrosoftExt)
5898 Diag(Loc: MemRecord->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5899 << Record->isUnion();
5900 else {
5901 // This is a nested type declaration.
5902 Diag(Loc: MemRecord->getLocation(), DiagID: diag::err_anonymous_record_with_type)
5903 << Record->isUnion();
5904 Invalid = true;
5905 }
5906 } else {
5907 // This is an anonymous type definition within another anonymous type.
5908 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5909 // not part of standard C++.
5910 Diag(Loc: MemRecord->getLocation(),
5911 DiagID: diag::ext_anonymous_record_with_anonymous_type)
5912 << Record->isUnion();
5913 }
5914 } else if (isa<AccessSpecDecl>(Val: Mem)) {
5915 // Any access specifier is fine.
5916 } else if (isa<StaticAssertDecl>(Val: Mem)) {
5917 // In C++1z, static_assert declarations are also fine.
5918 } else {
5919 // We have something that isn't a non-static data
5920 // member. Complain about it.
5921 unsigned DK = diag::err_anonymous_record_bad_member;
5922 if (isa<TypeDecl>(Val: Mem))
5923 DK = diag::err_anonymous_record_with_type;
5924 else if (isa<FunctionDecl>(Val: Mem))
5925 DK = diag::err_anonymous_record_with_function;
5926 else if (isa<VarDecl>(Val: Mem))
5927 DK = diag::err_anonymous_record_with_static;
5928
5929 // Visual C++ allows type definition in anonymous struct or union.
5930 if (getLangOpts().MicrosoftExt &&
5931 DK == diag::err_anonymous_record_with_type)
5932 Diag(Loc: Mem->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5933 << Record->isUnion();
5934 else {
5935 Diag(Loc: Mem->getLocation(), DiagID: DK) << Record->isUnion();
5936 Invalid = true;
5937 }
5938 }
5939 }
5940
5941 // C++11 [class.union]p8 (DR1460):
5942 // At most one variant member of a union may have a
5943 // brace-or-equal-initializer.
5944 if (cast<CXXRecordDecl>(Val: Record)->hasInClassInitializer() &&
5945 Owner->isRecord())
5946 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Owner),
5947 AnonUnion: cast<CXXRecordDecl>(Val: Record));
5948 }
5949
5950 if (!Record->isUnion() && !Owner->isRecord()) {
5951 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_struct_not_member)
5952 << getLangOpts().CPlusPlus;
5953 Invalid = true;
5954 }
5955
5956 // C++ [dcl.dcl]p3:
5957 // [If there are no declarators], and except for the declaration of an
5958 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5959 // names into the program
5960 // C++ [class.mem]p2:
5961 // each such member-declaration shall either declare at least one member
5962 // name of the class or declare at least one unnamed bit-field
5963 //
5964 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5965 if (getLangOpts().CPlusPlus && Record->field_empty())
5966 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_no_declarators) << DS.getSourceRange();
5967
5968 // Mock up a declarator.
5969 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5970 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5971 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5972 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5973
5974 // Create a declaration for this anonymous struct/union.
5975 NamedDecl *Anon = nullptr;
5976 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Val: Owner)) {
5977 Anon = FieldDecl::Create(
5978 C: Context, DC: OwningClass, StartLoc: DS.getBeginLoc(), IdLoc: Record->getLocation(),
5979 /*IdentifierInfo=*/Id: nullptr, T: Context.getCanonicalTagType(TD: Record), TInfo,
5980 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5981 /*InitStyle=*/ICIS_NoInit);
5982 Anon->setAccess(AS);
5983 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5984
5985 if (getLangOpts().CPlusPlus)
5986 FieldCollector->Add(D: cast<FieldDecl>(Val: Anon));
5987 } else {
5988 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5989 if (SCSpec == DeclSpec::SCS_mutable) {
5990 // mutable can only appear on non-static class members, so it's always
5991 // an error here
5992 Diag(Loc: Record->getLocation(), DiagID: diag::err_mutable_nonmember);
5993 Invalid = true;
5994 SC = SC_None;
5995 }
5996
5997 Anon = VarDecl::Create(C&: Context, DC: Owner, StartLoc: DS.getBeginLoc(),
5998 IdLoc: Record->getLocation(), /*IdentifierInfo=*/Id: nullptr,
5999 T: Context.getCanonicalTagType(TD: Record), TInfo, S: SC);
6000 if (Invalid)
6001 Anon->setInvalidDecl();
6002
6003 ProcessDeclAttributes(S, D: Anon, PD: Dc);
6004
6005 // Default-initialize the implicit variable. This initialization will be
6006 // trivial in almost all cases, except if a union member has an in-class
6007 // initializer:
6008 // union { int n = 0; };
6009 ActOnUninitializedDecl(dcl: Anon);
6010 }
6011 Anon->setImplicit();
6012
6013 // Mark this as an anonymous struct/union type.
6014 Record->setAnonymousStructOrUnion(true);
6015
6016 // Add the anonymous struct/union object to the current
6017 // context. We'll be referencing this object when we refer to one of
6018 // its members.
6019 Owner->addDecl(D: Anon);
6020
6021 // Inject the members of the anonymous struct/union into the owning
6022 // context and into the identifier resolver chain for name lookup
6023 // purposes.
6024 SmallVector<NamedDecl*, 2> Chain;
6025 Chain.push_back(Elt: Anon);
6026
6027 if (InjectAnonymousStructOrUnionMembers(SemaRef&: *this, S, Owner, AnonRecord: Record, AS, SC,
6028 Chaining&: Chain))
6029 Invalid = true;
6030
6031 if (VarDecl *NewVD = dyn_cast<VarDecl>(Val: Anon)) {
6032 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6033 MangleNumberingContext *MCtx;
6034 Decl *ManglingContextDecl;
6035 std::tie(args&: MCtx, args&: ManglingContextDecl) =
6036 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
6037 if (MCtx) {
6038 Context.setManglingNumber(
6039 ND: NewVD, Number: MCtx->getManglingNumber(
6040 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
6041 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
6042 }
6043 }
6044 }
6045
6046 if (Invalid)
6047 Anon->setInvalidDecl();
6048
6049 return Anon;
6050}
6051
6052Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
6053 RecordDecl *Record) {
6054 assert(Record && "expected a record!");
6055
6056 // Mock up a declarator.
6057 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
6058 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
6059 assert(TInfo && "couldn't build declarator info for anonymous struct");
6060
6061 auto *ParentDecl = cast<RecordDecl>(Val: CurContext);
6062 CanQualType RecTy = Context.getCanonicalTagType(TD: Record);
6063
6064 // Create a declaration for this anonymous struct.
6065 NamedDecl *Anon =
6066 FieldDecl::Create(C: Context, DC: ParentDecl, StartLoc: DS.getBeginLoc(), IdLoc: DS.getBeginLoc(),
6067 /*IdentifierInfo=*/Id: nullptr, T: RecTy, TInfo,
6068 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
6069 /*InitStyle=*/ICIS_NoInit);
6070 Anon->setImplicit();
6071
6072 // Add the anonymous struct object to the current context.
6073 CurContext->addDecl(D: Anon);
6074
6075 // Inject the members of the anonymous struct into the current
6076 // context and into the identifier resolver chain for name lookup
6077 // purposes.
6078 SmallVector<NamedDecl*, 2> Chain;
6079 Chain.push_back(Elt: Anon);
6080
6081 RecordDecl *RecordDef = Record->getDefinition();
6082 if (RequireCompleteSizedType(Loc: Anon->getLocation(), T: RecTy,
6083 DiagID: diag::err_field_incomplete_or_sizeless) ||
6084 InjectAnonymousStructOrUnionMembers(
6085 SemaRef&: *this, S, Owner: CurContext, AnonRecord: RecordDef, AS: AS_none,
6086 SC: StorageClassSpecToVarDeclStorageClass(DS), Chaining&: Chain)) {
6087 Anon->setInvalidDecl();
6088 ParentDecl->setInvalidDecl();
6089 }
6090
6091 return Anon;
6092}
6093
6094DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
6095 return GetNameFromUnqualifiedId(Name: D.getName());
6096}
6097
6098DeclarationNameInfo
6099Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
6100 DeclarationNameInfo NameInfo;
6101 NameInfo.setLoc(Name.StartLocation);
6102
6103 switch (Name.getKind()) {
6104
6105 case UnqualifiedIdKind::IK_ImplicitSelfParam:
6106 case UnqualifiedIdKind::IK_Identifier:
6107 NameInfo.setName(Name.Identifier);
6108 return NameInfo;
6109
6110 case UnqualifiedIdKind::IK_DeductionGuideName: {
6111 // C++ [temp.deduct.guide]p3:
6112 // The simple-template-id shall name a class template specialization.
6113 // The template-name shall be the same identifier as the template-name
6114 // of the simple-template-id.
6115 // These together intend to imply that the template-name shall name a
6116 // class template.
6117 // FIXME: template<typename T> struct X {};
6118 // template<typename T> using Y = X<T>;
6119 // Y(int) -> Y<int>;
6120 // satisfies these rules but does not name a class template.
6121 TemplateName TN = Name.TemplateName.get().get();
6122 auto *Template = TN.getAsTemplateDecl();
6123 if (!Template || !isa<ClassTemplateDecl>(Val: Template)) {
6124 Diag(Loc: Name.StartLocation,
6125 DiagID: diag::err_deduction_guide_name_not_class_template)
6126 << (int)getTemplateNameKindForDiagnostics(Name: TN) << TN;
6127 if (Template)
6128 NoteTemplateLocation(Decl: *Template);
6129 return DeclarationNameInfo();
6130 }
6131
6132 NameInfo.setName(
6133 Context.DeclarationNames.getCXXDeductionGuideName(TD: Template));
6134 return NameInfo;
6135 }
6136
6137 case UnqualifiedIdKind::IK_OperatorFunctionId:
6138 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6139 Op: Name.OperatorFunctionId.Operator));
6140 NameInfo.setCXXOperatorNameRange(SourceRange(
6141 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
6142 return NameInfo;
6143
6144 case UnqualifiedIdKind::IK_LiteralOperatorId:
6145 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6146 II: Name.Identifier));
6147 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
6148 return NameInfo;
6149
6150 case UnqualifiedIdKind::IK_ConversionFunctionId: {
6151 TypeSourceInfo *TInfo;
6152 QualType Ty = GetTypeFromParser(Ty: Name.ConversionFunctionId, TInfo: &TInfo);
6153 if (Ty.isNull())
6154 return DeclarationNameInfo();
6155 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6156 Ty: Context.getCanonicalType(T: Ty)));
6157 NameInfo.setNamedTypeInfo(TInfo);
6158 return NameInfo;
6159 }
6160
6161 case UnqualifiedIdKind::IK_ConstructorName: {
6162 TypeSourceInfo *TInfo;
6163 QualType Ty = GetTypeFromParser(Ty: Name.ConstructorName, TInfo: &TInfo);
6164 if (Ty.isNull())
6165 return DeclarationNameInfo();
6166 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6167 Ty: Context.getCanonicalType(T: Ty)));
6168 NameInfo.setNamedTypeInfo(TInfo);
6169 return NameInfo;
6170 }
6171
6172 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
6173 // In well-formed code, we can only have a constructor
6174 // template-id that refers to the current context, so go there
6175 // to find the actual type being constructed.
6176 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(Val: CurContext);
6177 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6178 return DeclarationNameInfo();
6179
6180 // Determine the type of the class being constructed.
6181 CanQualType CurClassType = Context.getCanonicalTagType(TD: CurClass);
6182
6183 // FIXME: Check two things: that the template-id names the same type as
6184 // CurClassType, and that the template-id does not occur when the name
6185 // was qualified.
6186
6187 NameInfo.setName(
6188 Context.DeclarationNames.getCXXConstructorName(Ty: CurClassType));
6189 // FIXME: should we retrieve TypeSourceInfo?
6190 NameInfo.setNamedTypeInfo(nullptr);
6191 return NameInfo;
6192 }
6193
6194 case UnqualifiedIdKind::IK_DestructorName: {
6195 TypeSourceInfo *TInfo;
6196 QualType Ty = GetTypeFromParser(Ty: Name.DestructorName, TInfo: &TInfo);
6197 if (Ty.isNull())
6198 return DeclarationNameInfo();
6199 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6200 Ty: Context.getCanonicalType(T: Ty)));
6201 NameInfo.setNamedTypeInfo(TInfo);
6202 return NameInfo;
6203 }
6204
6205 case UnqualifiedIdKind::IK_TemplateId: {
6206 TemplateName TName = Name.TemplateId->Template.get();
6207 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6208 return Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
6209 }
6210
6211 } // switch (Name.getKind())
6212
6213 llvm_unreachable("Unknown name kind");
6214}
6215
6216static QualType getCoreType(QualType Ty) {
6217 do {
6218 if (Ty->isPointerOrReferenceType())
6219 Ty = Ty->getPointeeType();
6220 else if (Ty->isArrayType())
6221 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6222 else
6223 return Ty.withoutLocalFastQualifiers();
6224 } while (true);
6225}
6226
6227/// hasSimilarParameters - Determine whether the C++ functions Declaration
6228/// and Definition have "nearly" matching parameters. This heuristic is
6229/// used to improve diagnostics in the case where an out-of-line function
6230/// definition doesn't match any declaration within the class or namespace.
6231/// Also sets Params to the list of indices to the parameters that differ
6232/// between the declaration and the definition. If hasSimilarParameters
6233/// returns true and Params is empty, then all of the parameters match.
6234static bool hasSimilarParameters(ASTContext &Context,
6235 FunctionDecl *Declaration,
6236 FunctionDecl *Definition,
6237 SmallVectorImpl<unsigned> &Params) {
6238 Params.clear();
6239 if (Declaration->param_size() != Definition->param_size())
6240 return false;
6241 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6242 QualType DeclParamTy = Declaration->getParamDecl(i: Idx)->getType();
6243 QualType DefParamTy = Definition->getParamDecl(i: Idx)->getType();
6244
6245 // The parameter types are identical
6246 if (Context.hasSameUnqualifiedType(T1: DefParamTy, T2: DeclParamTy))
6247 continue;
6248
6249 QualType DeclParamBaseTy = getCoreType(Ty: DeclParamTy);
6250 QualType DefParamBaseTy = getCoreType(Ty: DefParamTy);
6251 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6252 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6253
6254 if (Context.hasSameUnqualifiedType(T1: DeclParamBaseTy, T2: DefParamBaseTy) ||
6255 (DeclTyName && DeclTyName == DefTyName))
6256 Params.push_back(Elt: Idx);
6257 else // The two parameters aren't even close
6258 return false;
6259 }
6260
6261 return true;
6262}
6263
6264/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6265/// declarator needs to be rebuilt in the current instantiation.
6266/// Any bits of declarator which appear before the name are valid for
6267/// consideration here. That's specifically the type in the decl spec
6268/// and the base type in any member-pointer chunks.
6269static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6270 DeclarationName Name) {
6271 // The types we specifically need to rebuild are:
6272 // - typenames, typeofs, and decltypes
6273 // - types which will become injected class names
6274 // Of course, we also need to rebuild any type referencing such a
6275 // type. It's safest to just say "dependent", but we call out a
6276 // few cases here.
6277
6278 DeclSpec &DS = D.getMutableDeclSpec();
6279 switch (DS.getTypeSpecType()) {
6280 case DeclSpec::TST_typename:
6281 case DeclSpec::TST_typeofType:
6282 case DeclSpec::TST_typeof_unqualType:
6283#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6284#include "clang/Basic/BuiltinTraits.inc"
6285 case DeclSpec::TST_atomic: {
6286 // Grab the type from the parser.
6287 TypeSourceInfo *TSI = nullptr;
6288 QualType T = S.GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TSI);
6289 if (T.isNull() || !T->isInstantiationDependentType()) break;
6290
6291 // Make sure there's a type source info. This isn't really much
6292 // of a waste; most dependent types should have type source info
6293 // attached already.
6294 if (!TSI)
6295 TSI = S.Context.getTrivialTypeSourceInfo(T, Loc: DS.getTypeSpecTypeLoc());
6296
6297 // Rebuild the type in the current instantiation.
6298 TSI = S.RebuildTypeInCurrentInstantiation(T: TSI, Loc: D.getIdentifierLoc(), Name);
6299 if (!TSI) return true;
6300
6301 // Store the new type back in the decl spec.
6302 ParsedType LocType = S.CreateParsedType(T: TSI->getType(), TInfo: TSI);
6303 DS.UpdateTypeRep(Rep: LocType);
6304 break;
6305 }
6306
6307 case DeclSpec::TST_decltype:
6308 case DeclSpec::TST_typeof_unqualExpr:
6309 case DeclSpec::TST_typeofExpr: {
6310 Expr *E = DS.getRepAsExpr();
6311 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6312 if (Result.isInvalid()) return true;
6313 DS.UpdateExprRep(Rep: Result.get());
6314 break;
6315 }
6316
6317 default:
6318 // Nothing to do for these decl specs.
6319 break;
6320 }
6321
6322 // It doesn't matter what order we do this in.
6323 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6324 DeclaratorChunk &Chunk = D.getTypeObject(i: I);
6325
6326 // The only type information in the declarator which can come
6327 // before the declaration name is the base type of a member
6328 // pointer.
6329 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6330 continue;
6331
6332 // Rebuild the scope specifier in-place.
6333 CXXScopeSpec &SS = Chunk.Mem.Scope();
6334 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6335 return true;
6336 }
6337
6338 return false;
6339}
6340
6341/// Returns true if the declaration is declared in a system header or from a
6342/// system macro.
6343static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6344 return SM.isInSystemHeader(Loc: D->getLocation()) ||
6345 SM.isInSystemMacro(loc: D->getLocation());
6346}
6347
6348void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6349 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6350 // of system decl.
6351 if (D->getPreviousDecl() || D->isImplicit())
6352 return;
6353 ReservedIdentifierStatus Status = D->isReserved(LangOpts: getLangOpts());
6354 if (Status != ReservedIdentifierStatus::NotReserved &&
6355 !isFromSystemHeader(SM&: Context.getSourceManager(), D)) {
6356 Diag(Loc: D->getLocation(), DiagID: diag::warn_reserved_extern_symbol)
6357 << D << static_cast<int>(Status);
6358 }
6359}
6360
6361Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6362 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6363
6364 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6365 // declaration only if the `bind_to_declaration` extension is set.
6366 SmallVector<FunctionDecl *, 4> Bases;
6367 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6368 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6369 TP: llvm::omp::TraitProperty::
6370 implementation_extension_bind_to_declaration))
6371 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6372 S, D, TemplateParameterLists: MultiTemplateParamsArg(), Bases);
6373
6374 Decl *Dcl = HandleDeclarator(S, D, TemplateParameterLists: MultiTemplateParamsArg());
6375
6376 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6377 Dcl && Dcl->getDeclContext()->isFileContext())
6378 Dcl->setTopLevelDeclInObjCContainer();
6379
6380 if (!Bases.empty())
6381 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
6382 Bases);
6383
6384 return Dcl;
6385}
6386
6387bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6388 DeclarationNameInfo NameInfo) {
6389 DeclarationName Name = NameInfo.getName();
6390
6391 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC);
6392 while (Record && Record->isAnonymousStructOrUnion())
6393 Record = dyn_cast<CXXRecordDecl>(Val: Record->getParent());
6394 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6395 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_member_name_of_class) << Name;
6396 return true;
6397 }
6398
6399 return false;
6400}
6401
6402bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6403 DeclarationName Name,
6404 SourceLocation Loc,
6405 TemplateIdAnnotation *TemplateId,
6406 bool IsMemberSpecialization) {
6407 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6408 "without nested-name-specifier");
6409 DeclContext *Cur = CurContext;
6410 while (isa<LinkageSpecDecl>(Val: Cur) || isa<CapturedDecl>(Val: Cur))
6411 Cur = Cur->getParent();
6412
6413 // If the user provided a superfluous scope specifier that refers back to the
6414 // class in which the entity is already declared, diagnose and ignore it.
6415 //
6416 // class X {
6417 // void X::f();
6418 // };
6419 //
6420 // Note, it was once ill-formed to give redundant qualification in all
6421 // contexts, but that rule was removed by DR482.
6422 if (Cur->Equals(DC)) {
6423 if (Cur->isRecord()) {
6424 Diag(Loc, DiagID: LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6425 : diag::err_member_extra_qualification)
6426 << Name << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
6427 SS.clear();
6428 } else {
6429 Diag(Loc, DiagID: diag::warn_namespace_member_extra_qualification) << Name;
6430 }
6431 return false;
6432 }
6433
6434 // Check whether the qualifying scope encloses the scope of the original
6435 // declaration. For a template-id, we perform the checks in
6436 // CheckTemplateSpecializationScope.
6437 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6438 Cur = Cur->getEnclosingNonExpansionStatementContext();
6439 if (Cur->isRecord())
6440 Diag(Loc, DiagID: diag::err_member_qualification)
6441 << Name << SS.getRange();
6442 else if (isa<TranslationUnitDecl>(Val: DC))
6443 Diag(Loc, DiagID: diag::err_invalid_declarator_global_scope)
6444 << Name << SS.getRange();
6445 else if (isa<FunctionDecl>(Val: Cur))
6446 Diag(Loc, DiagID: diag::err_invalid_declarator_in_function)
6447 << Name << SS.getRange();
6448 else if (isa<BlockDecl>(Val: Cur))
6449 Diag(Loc, DiagID: diag::err_invalid_declarator_in_block)
6450 << Name << SS.getRange();
6451 else if (isa<ExportDecl>(Val: Cur)) {
6452 if (!isa<NamespaceDecl>(Val: DC))
6453 Diag(Loc, DiagID: diag::err_export_non_namespace_scope_name)
6454 << Name << SS.getRange();
6455 else
6456 // The cases that DC is not NamespaceDecl should be handled in
6457 // CheckRedeclarationExported.
6458 return false;
6459 } else
6460 Diag(Loc, DiagID: diag::err_invalid_declarator_scope)
6461 << Name << cast<NamedDecl>(Val: Cur) << cast<NamedDecl>(Val: DC) << SS.getRange();
6462
6463 return true;
6464 }
6465
6466 if (Cur->isRecord()) {
6467 // C++26 [temp.expl.spec]p3 (Adopted as a DR in CWG727):
6468 // An explicit specialization may be declared in any scope in which the
6469 // corresponding primary template may be defined.
6470 if (IsMemberSpecialization)
6471 return false;
6472
6473 // Cannot qualify members within a class.
6474 Diag(Loc, DiagID: diag::err_member_qualification)
6475 << Name << SS.getRange();
6476 SS.clear();
6477
6478 // C++ constructors and destructors with incorrect scopes can break
6479 // our AST invariants by having the wrong underlying types. If
6480 // that's the case, then drop this declaration entirely.
6481 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6482 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6483 !Context.hasSameType(
6484 T1: Name.getCXXNameType(),
6485 T2: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: Cur))))
6486 return true;
6487
6488 return false;
6489 }
6490
6491 // C++23 [temp.names]p5:
6492 // The keyword template shall not appear immediately after a declarative
6493 // nested-name-specifier.
6494 //
6495 // First check the template-id (if any), and then check each component of the
6496 // nested-name-specifier in reverse order.
6497 //
6498 // FIXME: nested-name-specifiers in friend declarations are declarative,
6499 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6500 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6501 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6502 << FixItHint::CreateRemoval(RemoveRange: TemplateId->TemplateKWLoc);
6503
6504 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6505 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6506 TL = std::exchange(obj&: NextTL, new_val: TypeLoc())) {
6507 SourceLocation TemplateKeywordLoc;
6508 switch (TL.getTypeLocClass()) {
6509 case TypeLoc::TemplateSpecialization: {
6510 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6511 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6512 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6513 Diag(Loc, DiagID: diag::ext_alias_template_in_declarative_nns)
6514 << TST.getLocalSourceRange();
6515 break;
6516 }
6517 case TypeLoc::Decltype:
6518 case TypeLoc::PackIndexing: {
6519 const Type *T = TL.getTypePtr();
6520 // C++23 [expr.prim.id.qual]p2:
6521 // [...] A declarative nested-name-specifier shall not have a
6522 // computed-type-specifier.
6523 //
6524 // CWG2858 changed this from 'decltype-specifier' to
6525 // 'computed-type-specifier'.
6526 Diag(Loc, DiagID: diag::err_computed_type_in_declarative_nns)
6527 << T->isDecltypeType() << TL.getSourceRange();
6528 break;
6529 }
6530 case TypeLoc::DependentName:
6531 NextTL =
6532 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6533 break;
6534 default:
6535 break;
6536 }
6537 if (TemplateKeywordLoc.isValid())
6538 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6539 << FixItHint::CreateRemoval(RemoveRange: TemplateKeywordLoc);
6540 }
6541
6542 return false;
6543}
6544
6545NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6546 MultiTemplateParamsArg TemplateParamLists) {
6547 // TODO: consider using NameInfo for diagnostic.
6548 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6549 DeclarationName Name = NameInfo.getName();
6550
6551 // All of these full declarators require an identifier. If it doesn't have
6552 // one, the ParsedFreeStandingDeclSpec action should be used.
6553 if (D.isDecompositionDeclarator()) {
6554 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6555 } else if (!Name) {
6556 if (!D.isInvalidType()) // Reject this if we think it is valid.
6557 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_declarator_need_ident)
6558 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6559 return nullptr;
6560 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_DeclarationType))
6561 return nullptr;
6562
6563 DeclContext *DC = CurContext;
6564 if (D.getCXXScopeSpec().isInvalid())
6565 D.setInvalidType();
6566 else if (D.getCXXScopeSpec().isSet()) {
6567 if (DiagnoseUnexpandedParameterPack(SS: D.getCXXScopeSpec(),
6568 UPPC: UPPC_DeclarationQualifier))
6569 return nullptr;
6570
6571 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6572 DC = computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext);
6573 if (!DC || isa<EnumDecl>(Val: DC)) {
6574 // If we could not compute the declaration context, it's because the
6575 // declaration context is dependent but does not refer to a class,
6576 // class template, or class template partial specialization. Complain
6577 // and return early, to avoid the coming semantic disaster.
6578 Diag(Loc: D.getIdentifierLoc(),
6579 DiagID: diag::err_template_qualified_declarator_no_match)
6580 << D.getCXXScopeSpec().getScopeRep()
6581 << D.getCXXScopeSpec().getRange();
6582 return nullptr;
6583 }
6584 bool IsDependentContext = DC->isDependentContext();
6585
6586 if (!IsDependentContext &&
6587 RequireCompleteDeclContext(SS&: D.getCXXScopeSpec(), DC))
6588 return nullptr;
6589
6590 // If a class is incomplete, do not parse entities inside it.
6591 if (isa<CXXRecordDecl>(Val: DC) && !cast<CXXRecordDecl>(Val: DC)->hasDefinition()) {
6592 Diag(Loc: D.getIdentifierLoc(),
6593 DiagID: diag::err_member_def_undefined_record)
6594 << Name << DC << D.getCXXScopeSpec().getRange();
6595 return nullptr;
6596 }
6597 if (!D.getDeclSpec().isFriendSpecified()) {
6598 TemplateIdAnnotation *TemplateId =
6599 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6600 ? D.getName().TemplateId
6601 : nullptr;
6602 if (diagnoseQualifiedDeclaration(SS&: D.getCXXScopeSpec(), DC, Name,
6603 Loc: D.getIdentifierLoc(), TemplateId,
6604 /*IsMemberSpecialization=*/false)) {
6605 if (DC->isRecord())
6606 return nullptr;
6607
6608 D.setInvalidType();
6609 } else if (CurContext->isRecord() && !CurContext->Equals(DC)) {
6610 D.setInvalidType();
6611 }
6612 }
6613
6614 // Check whether we need to rebuild the type of the given
6615 // declaration in the current instantiation.
6616 if (EnteringContext && IsDependentContext &&
6617 TemplateParamLists.size() != 0) {
6618 ContextRAII SavedContext(*this, DC);
6619 if (RebuildDeclaratorInCurrentInstantiation(S&: *this, D, Name))
6620 D.setInvalidType();
6621 }
6622 }
6623
6624 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6625 QualType R = TInfo->getType();
6626
6627 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
6628 UPPC: UPPC_DeclarationType))
6629 D.setInvalidType();
6630
6631 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6632 forRedeclarationInCurContext());
6633
6634 // See if this is a redefinition of a variable in the same scope.
6635 if (!D.getCXXScopeSpec().isSet()) {
6636 bool IsLinkageLookup = false;
6637 bool CreateBuiltins = false;
6638
6639 // If the declaration we're planning to build will be a function
6640 // or object with linkage, then look for another declaration with
6641 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6642 //
6643 // If the declaration we're planning to build will be declared with
6644 // external linkage in the translation unit, create any builtin with
6645 // the same name.
6646 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6647 /* Do nothing*/;
6648 else if (CurContext->isFunctionOrMethod() &&
6649 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6650 R->isFunctionType())) {
6651 IsLinkageLookup = true;
6652 CreateBuiltins =
6653 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6654 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6655 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6656 CreateBuiltins = true;
6657
6658 if (IsLinkageLookup) {
6659 Previous.clear(Kind: LookupRedeclarationWithLinkage);
6660 Previous.setRedeclarationKind(
6661 RedeclarationKind::ForExternalRedeclaration);
6662 }
6663
6664 LookupName(R&: Previous, S, AllowBuiltinCreation: CreateBuiltins);
6665 } else { // Something like "int foo::x;"
6666 LookupQualifiedName(R&: Previous, LookupCtx: DC);
6667
6668 // C++ [dcl.meaning]p1:
6669 // When the declarator-id is qualified, the declaration shall refer to a
6670 // previously declared member of the class or namespace to which the
6671 // qualifier refers (or, in the case of a namespace, of an element of the
6672 // inline namespace set of that namespace (7.3.1)) or to a specialization
6673 // thereof; [...]
6674 //
6675 // Note that we already checked the context above, and that we do not have
6676 // enough information to make sure that Previous contains the declaration
6677 // we want to match. For example, given:
6678 //
6679 // class X {
6680 // void f();
6681 // void f(float);
6682 // };
6683 //
6684 // void X::f(int) { } // ill-formed
6685 //
6686 // In this case, Previous will point to the overload set
6687 // containing the two f's declared in X, but neither of them
6688 // matches.
6689
6690 RemoveUsingDecls(R&: Previous);
6691 }
6692
6693 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6694 TPD && TPD->isTemplateParameter()) {
6695 // Older versions of clang allowed the names of function/variable templates
6696 // to shadow the names of their template parameters. For the compatibility
6697 // purposes we detect such cases and issue a default-to-error warning that
6698 // can be disabled with -Wno-strict-primary-template-shadow.
6699 if (!D.isInvalidType()) {
6700 bool AllowForCompatibility = false;
6701 if (Scope *DeclParent = S->getDeclParent();
6702 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6703 AllowForCompatibility = DeclParent->Contains(rhs: *TemplateParamParent) &&
6704 TemplateParamParent->isDeclScope(D: TPD);
6705 }
6706 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl: TPD,
6707 SupportedForCompatibility: AllowForCompatibility);
6708 }
6709
6710 // Just pretend that we didn't see the previous declaration.
6711 Previous.clear();
6712 }
6713
6714 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6715 // Forget that the previous declaration is the injected-class-name.
6716 Previous.clear();
6717
6718 // In C++, the previous declaration we find might be a tag type
6719 // (class or enum). In this case, the new declaration will hide the
6720 // tag type. Note that this applies to functions, function templates, and
6721 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6722 if (Previous.isSingleTagDecl() &&
6723 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6724 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6725 Previous.clear();
6726
6727 // Check that there are no default arguments other than in the parameters
6728 // of a function declaration (C++ only).
6729 if (getLangOpts().CPlusPlus)
6730 CheckExtraCXXDefaultArguments(D);
6731
6732 /// Get the innermost enclosing declaration scope.
6733 S = S->getDeclParent();
6734
6735 NamedDecl *New;
6736
6737 bool AddToScope = true;
6738 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6739 if (TemplateParamLists.size()) {
6740 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_typedef);
6741 return nullptr;
6742 }
6743
6744 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6745 } else if (R->isFunctionType()) {
6746 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6747 TemplateParamLists,
6748 AddToScope);
6749 } else {
6750 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6751 AddToScope);
6752 }
6753
6754 if (!New)
6755 return nullptr;
6756
6757 warnOnCTypeHiddenInCPlusPlus(D: New);
6758
6759 // If this has an identifier and is not a function template specialization,
6760 // add it to the scope stack.
6761 if (New->getDeclName() && AddToScope)
6762 PushOnScopeChains(D: New, S);
6763
6764 if (OpenMP().isInOpenMPDeclareTargetContext())
6765 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
6766
6767 return New;
6768}
6769
6770/// Helper method to turn variable array types into constant array
6771/// types in certain situations which would otherwise be errors (for
6772/// GCC compatibility).
6773static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6774 ASTContext &Context,
6775 bool &SizeIsNegative,
6776 llvm::APSInt &Oversized) {
6777 // This method tries to turn a variable array into a constant
6778 // array even when the size isn't an ICE. This is necessary
6779 // for compatibility with code that depends on gcc's buggy
6780 // constant expression folding, like struct {char x[(int)(char*)2];}
6781 SizeIsNegative = false;
6782 Oversized = 0;
6783
6784 if (T->isDependentType())
6785 return QualType();
6786
6787 QualifierCollector Qs;
6788 const Type *Ty = Qs.strip(type: T);
6789
6790 if (const PointerType* PTy = dyn_cast<PointerType>(Val: Ty)) {
6791 QualType Pointee = PTy->getPointeeType();
6792 QualType FixedType =
6793 TryToFixInvalidVariablyModifiedType(T: Pointee, Context, SizeIsNegative,
6794 Oversized);
6795 if (FixedType.isNull()) return FixedType;
6796 FixedType = Context.getPointerType(T: FixedType);
6797 return Qs.apply(Context, QT: FixedType);
6798 }
6799 if (const ParenType* PTy = dyn_cast<ParenType>(Val: Ty)) {
6800 QualType Inner = PTy->getInnerType();
6801 QualType FixedType =
6802 TryToFixInvalidVariablyModifiedType(T: Inner, Context, SizeIsNegative,
6803 Oversized);
6804 if (FixedType.isNull()) return FixedType;
6805 FixedType = Context.getParenType(NamedType: FixedType);
6806 return Qs.apply(Context, QT: FixedType);
6807 }
6808
6809 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(Val&: T);
6810 if (!VLATy)
6811 return QualType();
6812
6813 QualType ElemTy = VLATy->getElementType();
6814 if (ElemTy->isVariablyModifiedType()) {
6815 ElemTy = TryToFixInvalidVariablyModifiedType(T: ElemTy, Context,
6816 SizeIsNegative, Oversized);
6817 if (ElemTy.isNull())
6818 return QualType();
6819 }
6820
6821 Expr::EvalResult Result;
6822 if (!VLATy->getSizeExpr() ||
6823 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Ctx: Context))
6824 return QualType();
6825
6826 llvm::APSInt Res = Result.Val.getInt();
6827
6828 // Check whether the array size is negative.
6829 if (Res.isSigned() && Res.isNegative()) {
6830 SizeIsNegative = true;
6831 return QualType();
6832 }
6833
6834 // Check whether the array is too large to be addressed.
6835 unsigned ActiveSizeBits =
6836 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6837 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6838 ? ConstantArrayType::getNumAddressingBits(Context, ElementType: ElemTy, NumElements: Res)
6839 : Res.getActiveBits();
6840 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6841 Oversized = std::move(Res);
6842 return QualType();
6843 }
6844
6845 QualType FoldedArrayType = Context.getConstantArrayType(
6846 EltTy: ElemTy, ArySize: Res, SizeExpr: VLATy->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6847 return Qs.apply(Context, QT: FoldedArrayType);
6848}
6849
6850static void
6851FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6852 SrcTL = SrcTL.getUnqualifiedLoc();
6853 DstTL = DstTL.getUnqualifiedLoc();
6854 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6855 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6856 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getPointeeLoc(),
6857 DstTL: DstPTL.getPointeeLoc());
6858 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6859 return;
6860 }
6861 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6862 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6863 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getInnerLoc(),
6864 DstTL: DstPTL.getInnerLoc());
6865 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6866 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6867 return;
6868 }
6869 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6870 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6871 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6872 TypeLoc DstElemTL = DstATL.getElementLoc();
6873 if (VariableArrayTypeLoc SrcElemATL =
6874 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6875 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6876 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcElemATL, DstTL: DstElemATL);
6877 } else {
6878 DstElemTL.initializeFullCopy(Other: SrcElemTL);
6879 }
6880 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6881 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6882 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6883}
6884
6885/// Helper method to turn variable array types into constant array
6886/// types in certain situations which would otherwise be errors (for
6887/// GCC compatibility).
6888static TypeSourceInfo*
6889TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6890 ASTContext &Context,
6891 bool &SizeIsNegative,
6892 llvm::APSInt &Oversized) {
6893 QualType FixedTy
6894 = TryToFixInvalidVariablyModifiedType(T: TInfo->getType(), Context,
6895 SizeIsNegative, Oversized);
6896 if (FixedTy.isNull())
6897 return nullptr;
6898 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(T: FixedTy);
6899 FixInvalidVariablyModifiedTypeLoc(SrcTL: TInfo->getTypeLoc(),
6900 DstTL: FixedTInfo->getTypeLoc());
6901 return FixedTInfo;
6902}
6903
6904bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6905 QualType &T, SourceLocation Loc,
6906 unsigned FailedFoldDiagID) {
6907 bool SizeIsNegative;
6908 llvm::APSInt Oversized;
6909 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6910 TInfo, Context, SizeIsNegative, Oversized);
6911 if (FixedTInfo) {
6912 Diag(Loc, DiagID: diag::ext_vla_folded_to_constant);
6913 TInfo = FixedTInfo;
6914 T = FixedTInfo->getType();
6915 return true;
6916 }
6917
6918 if (SizeIsNegative)
6919 Diag(Loc, DiagID: diag::err_typecheck_negative_array_size);
6920 else if (Oversized.getBoolValue())
6921 Diag(Loc, DiagID: diag::err_array_too_large) << toString(
6922 I: Oversized, Radix: 10, Signed: Oversized.isSigned(), /*formatAsCLiteral=*/false,
6923 /*UpperCase=*/false, /*InsertSeparators=*/true);
6924 else if (FailedFoldDiagID)
6925 Diag(Loc, DiagID: FailedFoldDiagID);
6926 return false;
6927}
6928
6929void
6930Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6931 if (!getLangOpts().CPlusPlus &&
6932 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6933 // Don't need to track declarations in the TU in C.
6934 return;
6935
6936 // Note that we have a locally-scoped external with this name.
6937 Context.getExternCContextDecl()->makeDeclVisibleInContext(D: ND);
6938}
6939
6940NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6941 // FIXME: We can have multiple results via __attribute__((overloadable)).
6942 auto Result = Context.getExternCContextDecl()->lookup(Name);
6943 return Result.empty() ? nullptr : *Result.begin();
6944}
6945
6946void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6947 // FIXME: We should probably indicate the identifier in question to avoid
6948 // confusion for constructs like "virtual int a(), b;"
6949 if (DS.isVirtualSpecified())
6950 Diag(Loc: DS.getVirtualSpecLoc(),
6951 DiagID: diag::err_virtual_non_function);
6952
6953 if (DS.hasExplicitSpecifier())
6954 Diag(Loc: DS.getExplicitSpecLoc(),
6955 DiagID: diag::err_explicit_non_function);
6956
6957 if (DS.isNoreturnSpecified())
6958 Diag(Loc: DS.getNoreturnSpecLoc(),
6959 DiagID: diag::err_noreturn_non_function);
6960}
6961
6962NamedDecl*
6963Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6964 TypeSourceInfo *TInfo, LookupResult &Previous) {
6965 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6966 if (D.getCXXScopeSpec().isSet()) {
6967 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_typedef_declarator)
6968 << D.getCXXScopeSpec().getRange();
6969 D.setInvalidType();
6970 // Pretend we didn't see the scope specifier.
6971 DC = CurContext;
6972 Previous.clear();
6973 }
6974
6975 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
6976
6977 if (D.getDeclSpec().isInlineSpecified())
6978 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
6979 DiagID: (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6980 ? diag::warn_ms_inline_non_function
6981 : diag::err_inline_non_function)
6982 << getLangOpts().CPlusPlus17;
6983 if (D.getDeclSpec().hasConstexprSpecifier())
6984 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
6985 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6986
6987 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6988 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6989 Diag(Loc: D.getName().StartLocation,
6990 DiagID: diag::err_deduction_guide_invalid_specifier)
6991 << "typedef";
6992 else
6993 Diag(Loc: D.getName().StartLocation, DiagID: diag::err_typedef_not_identifier)
6994 << D.getName().getSourceRange();
6995 return nullptr;
6996 }
6997
6998 TypedefDecl *NewTD = ParseTypedefDecl(S, D, T: TInfo->getType(), TInfo);
6999 if (!NewTD) return nullptr;
7000
7001 // Handle attributes prior to checking for duplicates in MergeVarDecl
7002 ProcessDeclAttributes(S, D: NewTD, PD: D);
7003
7004 CheckTypedefForVariablyModifiedType(S, D: NewTD);
7005
7006 bool Redeclaration = D.isRedeclaration();
7007 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, D: NewTD, Previous, Redeclaration);
7008 D.setRedeclaration(Redeclaration);
7009 return ND;
7010}
7011
7012void
7013Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
7014 // C99 6.7.7p2: If a typedef name specifies a variably modified type
7015 // then it shall have block scope.
7016 // Note that variably modified types must be fixed before merging the decl so
7017 // that redeclarations will match.
7018 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
7019 QualType T = TInfo->getType();
7020 if (T->isVariablyModifiedType()) {
7021 setFunctionHasBranchProtectedScope();
7022
7023 if (S->getFnParent() == nullptr) {
7024 bool SizeIsNegative;
7025 llvm::APSInt Oversized;
7026 TypeSourceInfo *FixedTInfo =
7027 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7028 SizeIsNegative,
7029 Oversized);
7030 if (FixedTInfo) {
7031 Diag(Loc: NewTD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
7032 NewTD->setTypeSourceInfo(FixedTInfo);
7033 } else {
7034 if (SizeIsNegative)
7035 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_typecheck_negative_array_size);
7036 else if (T->isVariableArrayType())
7037 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope);
7038 else if (Oversized.getBoolValue())
7039 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_array_too_large)
7040 << toString(I: Oversized, Radix: 10);
7041 else
7042 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
7043 NewTD->setInvalidDecl();
7044 }
7045 }
7046 }
7047}
7048
7049NamedDecl*
7050Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
7051 LookupResult &Previous, bool &Redeclaration) {
7052
7053 // Find the shadowed declaration before filtering for scope.
7054 NamedDecl *ShadowedDecl = getShadowedDeclaration(D: NewTD, R: Previous);
7055
7056 // Merge the decl with the existing one if appropriate. If the decl is
7057 // in an outer scope, it isn't the same thing.
7058 FilterLookupForScope(R&: Previous, Ctx: DC, S, /*ConsiderLinkage*/false,
7059 /*AllowInlineNamespace*/false);
7060 filterNonConflictingPreviousTypedefDecls(S&: *this, Decl: NewTD, Previous);
7061 if (!Previous.empty()) {
7062 Redeclaration = true;
7063 MergeTypedefNameDecl(S, New: NewTD, OldDecls&: Previous);
7064 } else {
7065 inferGslPointerAttribute(TD: NewTD);
7066 }
7067
7068 if (ShadowedDecl && !Redeclaration)
7069 CheckShadow(D: NewTD, ShadowedDecl, R: Previous);
7070
7071 // If this is the C FILE type, notify the AST context.
7072 if (IdentifierInfo *II = NewTD->getIdentifier())
7073 if (!NewTD->isInvalidDecl() &&
7074 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7075 switch (II->getNotableIdentifierID()) {
7076 case tok::NotableIdentifierKind::FILE:
7077 Context.setFILEDecl(NewTD);
7078 break;
7079 case tok::NotableIdentifierKind::jmp_buf:
7080 Context.setjmp_bufDecl(NewTD);
7081 break;
7082 case tok::NotableIdentifierKind::sigjmp_buf:
7083 Context.setsigjmp_bufDecl(NewTD);
7084 break;
7085 case tok::NotableIdentifierKind::ucontext_t:
7086 Context.setucontext_tDecl(NewTD);
7087 break;
7088 case tok::NotableIdentifierKind::float_t:
7089 case tok::NotableIdentifierKind::double_t:
7090 NewTD->addAttr(A: AvailableOnlyInDefaultEvalMethodAttr::Create(Ctx&: Context));
7091 break;
7092 default:
7093 break;
7094 }
7095 }
7096
7097 return NewTD;
7098}
7099
7100/// Determines whether the given declaration is an out-of-scope
7101/// previous declaration.
7102///
7103/// This routine should be invoked when name lookup has found a
7104/// previous declaration (PrevDecl) that is not in the scope where a
7105/// new declaration by the same name is being introduced. If the new
7106/// declaration occurs in a local scope, previous declarations with
7107/// linkage may still be considered previous declarations (C99
7108/// 6.2.2p4-5, C++ [basic.link]p6).
7109///
7110/// \param PrevDecl the previous declaration found by name
7111/// lookup
7112///
7113/// \param DC the context in which the new declaration is being
7114/// declared.
7115///
7116/// \returns true if PrevDecl is an out-of-scope previous declaration
7117/// for a new delcaration with the same name.
7118static bool
7119isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
7120 ASTContext &Context) {
7121 if (!PrevDecl)
7122 return false;
7123
7124 if (!PrevDecl->hasLinkage())
7125 return false;
7126
7127 if (Context.getLangOpts().CPlusPlus) {
7128 // C++ [basic.link]p6:
7129 // If there is a visible declaration of an entity with linkage
7130 // having the same name and type, ignoring entities declared
7131 // outside the innermost enclosing namespace scope, the block
7132 // scope declaration declares that same entity and receives the
7133 // linkage of the previous declaration.
7134 DeclContext *OuterContext = DC->getRedeclContext();
7135 if (!OuterContext->isFunctionOrMethod())
7136 // This rule only applies to block-scope declarations.
7137 return false;
7138
7139 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7140 if (PrevOuterContext->isRecord())
7141 // We found a member function: ignore it.
7142 return false;
7143
7144 // Find the innermost enclosing namespace for the new and
7145 // previous declarations.
7146 OuterContext = OuterContext->getEnclosingNamespaceContext();
7147 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7148
7149 // The previous declaration is in a different namespace, so it
7150 // isn't the same function.
7151 if (!OuterContext->Equals(DC: PrevOuterContext))
7152 return false;
7153 }
7154
7155 return true;
7156}
7157
7158static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
7159 CXXScopeSpec &SS = D.getCXXScopeSpec();
7160 if (!SS.isSet()) return;
7161 DD->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
7162}
7163
7164void Sema::deduceOpenCLAddressSpace(VarDecl *Var) {
7165 LangAS ImplAS = LangAS::opencl_private;
7166 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7167 // __opencl_c_program_scope_global_variables feature, the address space
7168 // for a variable at program scope or a static or extern variable inside
7169 // a function are inferred to be __global.
7170 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()) &&
7171 Var->hasGlobalStorage())
7172 ImplAS = LangAS::opencl_global;
7173 Var->assignAddressSpace(Ctxt: Context, AS: ImplAS);
7174}
7175
7176static bool checkWeakAttrCompatibility(Sema &S, const NamedDecl &ND,
7177 const WeakAttr &Attr) {
7178 const NamedDecl *D = &ND;
7179 // IFuncAttr is not inherited, so a redeclaration may need to check the
7180 // attributes on the definition instead.
7181 if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND))
7182 if (const FunctionDecl *Def = FD->getDefinition())
7183 D = Def;
7184 return DiagnoseMutualExclusions(S, D, A: &Attr);
7185}
7186
7187static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7188 // 'weak' only applies to declarations with external linkage.
7189 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7190 if (!ND.isExternallyVisible()) {
7191 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weak_static);
7192 ND.dropAttr<WeakAttr>();
7193 } else if (!checkWeakAttrCompatibility(S, ND, Attr: *Attr)) {
7194 // A forward #pragma weak adds the attribute without checking mutual
7195 // exclusions during attribute processing.
7196 ND.dropAttr<WeakAttr>();
7197 }
7198 }
7199}
7200
7201static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7202 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7203 if (ND.isExternallyVisible()) {
7204 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weakref_not_static);
7205 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7206 }
7207 }
7208}
7209
7210static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7211 if (auto *VD = dyn_cast<VarDecl>(Val: &ND)) {
7212 if (VD->hasInit()) {
7213 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7214 assert(VD->isThisDeclarationADefinition() &&
7215 "Broken AliasAttr handled late!");
7216 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << VD << 0;
7217 VD->dropAttr<AliasAttr>();
7218 }
7219 }
7220 }
7221}
7222
7223static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7224 // 'selectany' only applies to externally visible variable declarations.
7225 // It does not apply to functions.
7226 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7227 if (isa<FunctionDecl>(Val: ND) || !ND.isExternallyVisible()) {
7228 S.Diag(Loc: Attr->getLocation(),
7229 DiagID: diag::err_attribute_selectany_non_extern_data);
7230 ND.dropAttr<SelectAnyAttr>();
7231 }
7232 }
7233}
7234
7235static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND) {
7236 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7237 if (!ND.isExternallyVisible())
7238 S.Diag(Loc: Attr->getLocation(),
7239 DiagID: diag::warn_attribute_hybrid_patchable_non_extern);
7240 }
7241}
7242
7243static void checkInheritableAttr(Sema &S, NamedDecl &ND) {
7244 if (const InheritableAttr *Attr = getDLLAttr(D: &ND)) {
7245 auto *VD = dyn_cast<VarDecl>(Val: &ND);
7246 bool IsAnonymousNS = false;
7247 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7248 if (VD) {
7249 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: VD->getDeclContext());
7250 while (NS && !IsAnonymousNS) {
7251 IsAnonymousNS = NS->isAnonymousNamespace();
7252 NS = dyn_cast<NamespaceDecl>(Val: NS->getParent());
7253 }
7254 }
7255 // dll attributes require external linkage. Static locals may have external
7256 // linkage but still cannot be explicitly imported or exported.
7257 // In Microsoft mode, a variable defined in anonymous namespace must have
7258 // external linkage in order to be exported.
7259 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7260 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7261 (!AnonNSInMicrosoftMode &&
7262 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7263 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_attribute_dll_not_extern)
7264 << &ND << Attr;
7265 ND.setInvalidDecl();
7266 }
7267 }
7268}
7269
7270static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND) {
7271 // Check the attributes on the function type and function params, if any.
7272 if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND)) {
7273 FD = FD->getMostRecentDecl();
7274 // Don't declare this variable in the second operand of the for-statement;
7275 // GCC miscompiles that by ending its lifetime before evaluating the
7276 // third operand. See gcc.gnu.org/PR86769.
7277 AttributedTypeLoc ATL;
7278 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7279 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7280 TL = ATL.getModifiedLoc()) {
7281 // The [[lifetimebound]] attribute can be applied to the implicit object
7282 // parameter of a non-static member function (other than a ctor or dtor)
7283 // by applying it to the function type.
7284 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7285 const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
7286 int NoImplicitObjectError = -1;
7287 if (!MD)
7288 NoImplicitObjectError = 0;
7289 else if (MD->isStatic())
7290 NoImplicitObjectError = 1;
7291 else if (MD->isExplicitObjectMemberFunction())
7292 NoImplicitObjectError = 2;
7293 if (NoImplicitObjectError != -1) {
7294 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_no_object_param)
7295 << NoImplicitObjectError << A->getRange();
7296 } else if (isa<CXXConstructorDecl>(Val: MD) || isa<CXXDestructorDecl>(Val: MD)) {
7297 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_ctor_dtor)
7298 << isa<CXXDestructorDecl>(Val: MD) << A->getRange();
7299 } else if (MD->getReturnType()->isVoidType()) {
7300 S.Diag(
7301 Loc: MD->getLocation(),
7302 DiagID: diag::
7303 err_lifetimebound_implicit_object_parameter_void_return_type);
7304 }
7305 }
7306 }
7307
7308 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7309 const ParmVarDecl *P = FD->getParamDecl(i: I);
7310
7311 // The [[lifetimebound]] attribute can be applied to a function parameter
7312 // only if the function returns a value.
7313 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7314 if (!isa<CXXConstructorDecl>(Val: FD) && FD->getReturnType()->isVoidType()) {
7315 S.Diag(Loc: A->getLocation(),
7316 DiagID: diag::err_lifetimebound_parameter_void_return_type);
7317 }
7318 }
7319 }
7320 }
7321}
7322
7323static void checkModularFormatAttr(Sema &S, NamedDecl &ND) {
7324 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7325 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_modular_format_attribute_no_format);
7326}
7327
7328static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7329 // Ensure that an auto decl is deduced otherwise the checks below might cache
7330 // the wrong linkage.
7331 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7332
7333 checkWeakAttr(S, ND);
7334 checkWeakRefAttr(S, ND);
7335 checkAliasAttr(S, ND);
7336 checkSelectAnyAttr(S, ND);
7337 checkHybridPatchableAttr(S, ND);
7338 checkInheritableAttr(S, ND);
7339 checkLifetimeBoundAttr(S, ND);
7340}
7341
7342static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7343 NamedDecl *NewDecl,
7344 bool IsSpecialization,
7345 bool IsDefinition) {
7346 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7347 return;
7348
7349 bool IsTemplate = false;
7350 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(Val: OldDecl)) {
7351 OldDecl = OldTD->getTemplatedDecl();
7352 IsTemplate = true;
7353 if (!IsSpecialization)
7354 IsDefinition = false;
7355 }
7356 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(Val: NewDecl)) {
7357 NewDecl = NewTD->getTemplatedDecl();
7358 IsTemplate = true;
7359 }
7360
7361 if (!OldDecl || !NewDecl)
7362 return;
7363
7364 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7365 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7366 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7367 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7368
7369 // dllimport and dllexport are inheritable attributes so we have to exclude
7370 // inherited attribute instances.
7371 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7372 (NewExportAttr && !NewExportAttr->isInherited());
7373
7374 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7375 // the only exception being explicit specializations.
7376 // Implicitly generated declarations are also excluded for now because there
7377 // is no other way to switch these to use dllimport or dllexport.
7378 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7379
7380 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7381 // Allow with a warning for free functions and global variables.
7382 bool JustWarn = false;
7383 if (!OldDecl->isCXXClassMember()) {
7384 auto *VD = dyn_cast<VarDecl>(Val: OldDecl);
7385 if (VD && !VD->getDescribedVarTemplate())
7386 JustWarn = true;
7387 auto *FD = dyn_cast<FunctionDecl>(Val: OldDecl);
7388 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7389 JustWarn = true;
7390 }
7391
7392 // We cannot change a declaration that's been used because IR has already
7393 // been emitted. Dllimported functions will still work though (modulo
7394 // address equality) as they can use the thunk.
7395 if (OldDecl->isUsed())
7396 if (!isa<FunctionDecl>(Val: OldDecl) || !NewImportAttr)
7397 JustWarn = false;
7398
7399 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7400 : diag::err_attribute_dll_redeclaration;
7401 S.Diag(Loc: NewDecl->getLocation(), DiagID)
7402 << NewDecl
7403 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7404 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7405 if (!JustWarn) {
7406 NewDecl->setInvalidDecl();
7407 return;
7408 }
7409 }
7410
7411 // A redeclaration is not allowed to drop a dllimport attribute, the only
7412 // exceptions being inline function definitions (except for function
7413 // templates), local extern declarations, qualified friend declarations or
7414 // special MSVC extension: in the last case, the declaration is treated as if
7415 // it were marked dllexport.
7416 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7417 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7418 if (const auto *VD = dyn_cast<VarDecl>(Val: NewDecl)) {
7419 // Ignore static data because out-of-line definitions are diagnosed
7420 // separately.
7421 IsStaticDataMember = VD->isStaticDataMember();
7422 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7423 VarDecl::DeclarationOnly;
7424 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: NewDecl)) {
7425 IsInline = FD->isInlined();
7426 IsQualifiedFriend = FD->getQualifier() &&
7427 FD->getFriendObjectKind() == Decl::FOK_Declared;
7428 }
7429
7430 if (OldImportAttr && !HasNewAttr &&
7431 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7432 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7433 if (IsMicrosoftABI && IsDefinition) {
7434 if (IsSpecialization) {
7435 S.Diag(
7436 Loc: NewDecl->getLocation(),
7437 DiagID: diag::err_attribute_dllimport_function_specialization_definition);
7438 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_attribute);
7439 NewDecl->dropAttr<DLLImportAttr>();
7440 } else {
7441 S.Diag(Loc: NewDecl->getLocation(),
7442 DiagID: diag::warn_redeclaration_without_import_attribute)
7443 << NewDecl;
7444 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7445 NewDecl->dropAttr<DLLImportAttr>();
7446 NewDecl->addAttr(A: DLLExportAttr::CreateImplicit(
7447 Ctx&: S.Context, Range: NewImportAttr->getRange()));
7448 }
7449 } else if (IsMicrosoftABI && IsSpecialization) {
7450 assert(!IsDefinition);
7451 // MSVC allows this. Keep the inherited attribute.
7452 } else {
7453 S.Diag(Loc: NewDecl->getLocation(),
7454 DiagID: diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7455 << NewDecl << OldImportAttr;
7456 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7457 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_previous_attribute);
7458 OldDecl->dropAttr<DLLImportAttr>();
7459 NewDecl->dropAttr<DLLImportAttr>();
7460 }
7461 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7462 // In MinGW, seeing a function declared inline drops the dllimport
7463 // attribute.
7464 OldDecl->dropAttr<DLLImportAttr>();
7465 NewDecl->dropAttr<DLLImportAttr>();
7466 S.Diag(Loc: NewDecl->getLocation(),
7467 DiagID: diag::warn_dllimport_dropped_from_inline_function)
7468 << NewDecl << OldImportAttr;
7469 }
7470
7471 // A specialization of a class template member function is processed here
7472 // since it's a redeclaration. If the parent class is dllexport, the
7473 // specialization inherits that attribute. This doesn't happen automatically
7474 // since the parent class isn't instantiated until later.
7475 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDecl)) {
7476 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7477 !NewImportAttr && !NewExportAttr) {
7478 if (const DLLExportAttr *ParentExportAttr =
7479 MD->getParent()->getAttr<DLLExportAttr>()) {
7480 DLLExportAttr *NewAttr = ParentExportAttr->clone(C&: S.Context);
7481 NewAttr->setInherited(true);
7482 NewDecl->addAttr(A: NewAttr);
7483 }
7484 }
7485 }
7486}
7487
7488/// Given that we are within the definition of the given function,
7489/// will that definition behave like C99's 'inline', where the
7490/// definition is discarded except for optimization purposes?
7491static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7492 // Try to avoid calling GetGVALinkageForFunction.
7493
7494 // All cases of this require the 'inline' keyword.
7495 if (!FD->isInlined()) return false;
7496
7497 // This is only possible in C++ with the gnu_inline attribute.
7498 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7499 return false;
7500
7501 // Okay, go ahead and call the relatively-more-expensive function.
7502 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7503}
7504
7505/// Determine whether a variable is extern "C" prior to attaching
7506/// an initializer. We can't just call isExternC() here, because that
7507/// will also compute and cache whether the declaration is externally
7508/// visible, which might change when we attach the initializer.
7509///
7510/// This can only be used if the declaration is known to not be a
7511/// redeclaration of an internal linkage declaration.
7512///
7513/// For instance:
7514///
7515/// auto x = []{};
7516///
7517/// Attaching the initializer here makes this declaration not externally
7518/// visible, because its type has internal linkage.
7519///
7520/// FIXME: This is a hack.
7521template<typename T>
7522static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7523 if (S.getLangOpts().CPlusPlus) {
7524 // In C++, the overloadable attribute negates the effects of extern "C".
7525 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7526 return false;
7527
7528 // So do CUDA's host/device attributes.
7529 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7530 D->template hasAttr<CUDAHostAttr>()))
7531 return false;
7532 }
7533 return D->isExternC();
7534}
7535
7536static bool shouldConsiderLinkage(const VarDecl *VD) {
7537 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7538 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(Val: DC) ||
7539 isa<OMPDeclareMapperDecl>(Val: DC))
7540 return VD->hasExternalStorage();
7541 if (DC->isFileContext())
7542 return true;
7543 if (DC->isRecord())
7544 return false;
7545 if (DC->getDeclKind() == Decl::HLSLBuffer)
7546 return false;
7547
7548 if (isa<RequiresExprBodyDecl, CXXExpansionStmtDecl>(Val: DC))
7549 return false;
7550 llvm_unreachable("Unexpected context");
7551}
7552
7553static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7554 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7555 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7556 isa<OMPDeclareReductionDecl>(Val: DC) || isa<OMPDeclareMapperDecl>(Val: DC))
7557 return true;
7558 if (DC->isRecord() || isa<CXXExpansionStmtDecl>(Val: DC))
7559 return false;
7560 llvm_unreachable("Unexpected context");
7561}
7562
7563static bool hasParsedAttr(Scope *S, const Declarator &PD,
7564 ParsedAttr::Kind Kind) {
7565 // Check decl attributes on the DeclSpec.
7566 if (PD.getDeclSpec().getAttributes().hasAttribute(K: Kind))
7567 return true;
7568
7569 // Walk the declarator structure, checking decl attributes that were in a type
7570 // position to the decl itself.
7571 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7572 if (PD.getTypeObject(i: I).getAttrs().hasAttribute(K: Kind))
7573 return true;
7574 }
7575
7576 // Finally, check attributes on the decl itself.
7577 return PD.getAttributes().hasAttribute(K: Kind) ||
7578 PD.getDeclarationAttributes().hasAttribute(K: Kind);
7579}
7580
7581bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7582 if (!DC->isFunctionOrMethod())
7583 return false;
7584
7585 // If this is a local extern function or variable declared within a function
7586 // template, don't add it into the enclosing namespace scope until it is
7587 // instantiated; it might have a dependent type right now.
7588 if (DC->isDependentContext())
7589 return true;
7590
7591 // C++11 [basic.link]p7:
7592 // When a block scope declaration of an entity with linkage is not found to
7593 // refer to some other declaration, then that entity is a member of the
7594 // innermost enclosing namespace.
7595 //
7596 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7597 // semantically-enclosing namespace, not a lexically-enclosing one.
7598 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(Val: DC))
7599 DC = DC->getParent();
7600 return true;
7601}
7602
7603/// Returns true if given declaration has external C language linkage.
7604static bool isDeclExternC(const Decl *D) {
7605 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
7606 return FD->isExternC();
7607 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
7608 return VD->isExternC();
7609
7610 llvm_unreachable("Unknown type of decl!");
7611}
7612
7613/// Returns true if there hasn't been any invalid type diagnosed.
7614static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7615 DeclContext *DC = NewVD->getDeclContext();
7616 QualType R = NewVD->getType();
7617
7618 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7619 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7620 // argument.
7621 if (R->isImageType() || R->isPipeType()) {
7622 Se.Diag(Loc: NewVD->getLocation(),
7623 DiagID: diag::err_opencl_type_can_only_be_used_as_function_parameter)
7624 << R;
7625 NewVD->setInvalidDecl();
7626 return false;
7627 }
7628
7629 // OpenCL v1.2 s6.9.r:
7630 // The event type cannot be used to declare a program scope variable.
7631 // OpenCL v2.0 s6.9.q:
7632 // The clk_event_t and reserve_id_t types cannot be declared in program
7633 // scope.
7634 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7635 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7636 Se.Diag(Loc: NewVD->getLocation(),
7637 DiagID: diag::err_invalid_type_for_program_scope_var)
7638 << R;
7639 NewVD->setInvalidDecl();
7640 return false;
7641 }
7642 }
7643
7644 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7645 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
7646 LO: Se.getLangOpts())) {
7647 QualType NR = R.getCanonicalType();
7648 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7649 NR->isReferenceType()) {
7650 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7651 NR->isFunctionReferenceType()) {
7652 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_pointer)
7653 << NR->isReferenceType();
7654 NewVD->setInvalidDecl();
7655 return false;
7656 }
7657 NR = NR->getPointeeType();
7658 }
7659 }
7660
7661 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
7662 LO: Se.getLangOpts())) {
7663 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7664 // half array type (unless the cl_khr_fp16 extension is enabled).
7665 if (Se.Context.getBaseElementType(QT: R)->isHalfType()) {
7666 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_half_declaration) << R;
7667 NewVD->setInvalidDecl();
7668 return false;
7669 }
7670 }
7671
7672 // OpenCL v1.2 s6.9.r:
7673 // The event type cannot be used with the __local, __constant and __global
7674 // address space qualifiers.
7675 if (R->isEventT()) {
7676 if (R.getAddressSpace() != LangAS::opencl_private) {
7677 Se.Diag(Loc: NewVD->getBeginLoc(), DiagID: diag::err_event_t_addr_space_qual);
7678 NewVD->setInvalidDecl();
7679 return false;
7680 }
7681 }
7682
7683 if (R->isSamplerT()) {
7684 // OpenCL v1.2 s6.9.b p4:
7685 // The sampler type cannot be used with the __local and __global address
7686 // space qualifiers.
7687 if (R.getAddressSpace() == LangAS::opencl_local ||
7688 R.getAddressSpace() == LangAS::opencl_global) {
7689 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wrong_sampler_addressspace);
7690 NewVD->setInvalidDecl();
7691 }
7692
7693 // OpenCL v1.2 s6.12.14.1:
7694 // A global sampler must be declared with either the constant address
7695 // space qualifier or with the const qualifier.
7696 if (DC->isTranslationUnit() &&
7697 !(R.getAddressSpace() == LangAS::opencl_constant ||
7698 R.isConstQualified())) {
7699 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_nonconst_global_sampler);
7700 NewVD->setInvalidDecl();
7701 }
7702 if (NewVD->isInvalidDecl())
7703 return false;
7704 }
7705
7706 return true;
7707}
7708
7709template <typename AttrTy>
7710static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7711 const TypedefNameDecl *TND = TT->getDecl();
7712 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7713 AttrTy *Clone = Attribute->clone(S.Context);
7714 Clone->setInherited(true);
7715 D->addAttr(A: Clone);
7716 }
7717}
7718
7719// This function emits warning and a corresponding note based on the
7720// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7721// declarations of an annotated type must be const qualified.
7722static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7723 QualType VarType = VD->getType().getCanonicalType();
7724
7725 // Ignore local declarations (for now) and those with const qualification.
7726 // TODO: Local variables should not be allowed if their type declaration has
7727 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7728 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7729 return;
7730
7731 if (VarType->isArrayType()) {
7732 // Retrieve element type for array declarations.
7733 VarType = S.getASTContext().getBaseElementType(QT: VarType);
7734 }
7735
7736 const RecordDecl *RD = VarType->getAsRecordDecl();
7737
7738 // Check if the record declaration is present and if it has any attributes.
7739 if (RD == nullptr)
7740 return;
7741
7742 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7743 S.Diag(Loc: VD->getLocation(), DiagID: diag::warn_var_decl_not_read_only) << RD;
7744 S.Diag(Loc: ConstDecl->getLocation(), DiagID: diag::note_enforce_read_only_placement);
7745 return;
7746 }
7747}
7748
7749void Sema::ProcessPragmaExport(DeclaratorDecl *NewD) {
7750 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7751 "NewD is not a function or variable");
7752
7753 if (PendingExportedNames.empty())
7754 return;
7755 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: NewD)) {
7756 if (getLangOpts().CPlusPlus && !FD->isExternC())
7757 return;
7758 }
7759 IdentifierInfo *IdentName = NewD->getIdentifier();
7760 if (IdentName == nullptr)
7761 return;
7762 auto PendingName = PendingExportedNames.find(Val: IdentName);
7763 if (PendingName != PendingExportedNames.end()) {
7764 auto &Label = PendingName->second;
7765 if (!Label.Used) {
7766 Label.Used = true;
7767 if (NewD->hasExternalFormalLinkage())
7768 mergeVisibilityType(D: NewD, Loc: Label.NameLoc, Type: VisibilityAttr::Default);
7769 else
7770 Diag(Loc: Label.NameLoc, DiagID: diag::warn_pragma_not_applied) << "export" << NewD;
7771 }
7772 }
7773}
7774
7775// Checks if VD is declared at global scope or with C language linkage.
7776static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7777 return Name.getAsIdentifierInfo() &&
7778 Name.getAsIdentifierInfo()->isStr(Str: "main") &&
7779 !VD->getDescribedVarTemplate() &&
7780 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7781 VD->isExternC());
7782}
7783
7784void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7785 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7786
7787 // Quickly return if the function does not have an `asm` attribute.
7788 if (E == nullptr)
7789 return;
7790
7791 // The parser guarantees this is a string.
7792 StringLiteral *SE = cast<StringLiteral>(Val: E);
7793 StringRef Label = SE->getString();
7794 QualType R = TInfo->getType();
7795 if (R->isIncompleteType())
7796 return;
7797 if (S->getFnParent() != nullptr) {
7798 switch (SC) {
7799 case SC_None:
7800 case SC_Auto:
7801 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_asm_label_on_auto_decl) << Label;
7802 break;
7803 case SC_Register:
7804 // Local Named register
7805 if (!Context.getTargetInfo().isValidGCCRegisterName(Name: Label) &&
7806 DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: getCurFunctionDecl()))
7807 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7808 break;
7809 case SC_Static:
7810 case SC_Extern:
7811 case SC_PrivateExtern:
7812 break;
7813 }
7814 } else if (SC == SC_Register) {
7815 // Global Named register
7816 if (DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) {
7817 const auto &TI = Context.getTargetInfo();
7818 bool HasSizeMismatch;
7819
7820 if (!TI.isValidGCCRegisterName(Name: Label))
7821 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7822 else if (!TI.validateGlobalRegisterVariable(RegName: Label, RegSize: Context.getTypeSize(T: R),
7823 HasSizeMismatch))
7824 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_invalid_global_var_reg) << Label;
7825 else if (HasSizeMismatch)
7826 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_register_size_mismatch) << Label;
7827 }
7828
7829 if (!R->isIntegralType(Ctx: Context) && !R->isPointerType()) {
7830 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
7831 DiagID: diag::err_asm_unsupported_register_type)
7832 << TInfo->getTypeLoc().getSourceRange();
7833 NewVD->setInvalidDecl(true);
7834 }
7835 }
7836}
7837
7838NamedDecl *Sema::ActOnVariableDeclarator(
7839 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7840 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7841 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7842 QualType R = TInfo->getType();
7843 DeclarationName Name = GetNameForDeclarator(D).getName();
7844
7845 IdentifierInfo *II = Name.getAsIdentifierInfo();
7846 bool IsPlaceholderVariable = false;
7847
7848 if (D.isDecompositionDeclarator()) {
7849 // Take the name of the first declarator as our name for diagnostic
7850 // purposes.
7851 auto &Decomp = D.getDecompositionDeclarator();
7852 if (!Decomp.bindings().empty()) {
7853 II = Decomp.bindings()[0].Name;
7854 Name = II;
7855 }
7856 } else if (!II) {
7857 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_variable_name) << Name;
7858 return nullptr;
7859 }
7860
7861
7862 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7863 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS: D.getDeclSpec());
7864 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7865 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7866
7867 IsPlaceholderVariable = true;
7868
7869 if (!Previous.empty()) {
7870 NamedDecl *PrevDecl = *Previous.begin();
7871 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7872 DC: DC->getRedeclContext());
7873 if (SameDC && isDeclInScope(D: PrevDecl, Ctx: CurContext, S, AllowInlineNamespace: false)) {
7874 IsPlaceholderVariable = !isa<ParmVarDecl>(Val: PrevDecl);
7875 if (IsPlaceholderVariable)
7876 DiagPlaceholderVariableDefinition(Loc: D.getIdentifierLoc());
7877 }
7878 }
7879 }
7880
7881 // dllimport globals without explicit storage class are treated as extern. We
7882 // have to change the storage class this early to get the right DeclContext.
7883 if (SC == SC_None && !DC->isRecord() &&
7884 hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLImport) &&
7885 !hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLExport))
7886 SC = SC_Extern;
7887
7888 DeclContext *OriginalDC = DC;
7889 bool IsLocalExternDecl = SC == SC_Extern &&
7890 adjustContextForLocalExternDecl(DC);
7891
7892 if (SCSpec == DeclSpec::SCS_mutable) {
7893 // mutable can only appear on non-static class members, so it's always
7894 // an error here
7895 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_mutable_nonmember);
7896 D.setInvalidType();
7897 SC = SC_None;
7898 }
7899
7900 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7901 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7902 loc: D.getDeclSpec().getStorageClassSpecLoc())) {
7903 // In C++11, the 'register' storage class specifier is deprecated.
7904 // Suppress the warning in system macros, it's used in macros in some
7905 // popular C system headers, such as in glibc's htonl() macro.
7906 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7907 DiagID: getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7908 : diag::warn_deprecated_register)
7909 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7910 }
7911
7912 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
7913
7914 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7915 // C99 6.9p2: The storage-class specifiers auto and register shall not
7916 // appear in the declaration specifiers in an external declaration.
7917 // Global Register+Asm is a GNU extension we support.
7918 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7919 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_typecheck_sclass_fscope);
7920 D.setInvalidType();
7921 }
7922 }
7923
7924 // If this variable has a VLA type and an initializer, try to
7925 // fold to a constant-sized type. This is otherwise invalid.
7926 if (D.hasInitializer() && R->isVariableArrayType())
7927 tryToFixVariablyModifiedVarType(TInfo, T&: R, Loc: D.getIdentifierLoc(),
7928 /*DiagID=*/FailedFoldDiagID: 0);
7929
7930 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7931 const AutoType *AT = TL.getTypePtr();
7932 CheckConstrainedAuto(AutoT: AT, Loc: TL.getConceptNameLoc());
7933 }
7934
7935 bool IsMemberSpecialization = false;
7936 bool IsVariableTemplateSpecialization = false;
7937 bool IsPartialSpecialization = false;
7938 bool IsVariableTemplate = false;
7939 VarDecl *NewVD = nullptr;
7940 VarTemplateDecl *NewTemplate = nullptr;
7941 TemplateParameterList *TemplateParams = nullptr;
7942 if (!getLangOpts().CPlusPlus) {
7943 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
7944 Id: II, T: R, TInfo, S: SC);
7945
7946 if (R->getContainedDeducedType())
7947 ParsingInitForAutoVars.insert(Ptr: NewVD);
7948
7949 if (D.isInvalidType())
7950 NewVD->setInvalidDecl();
7951
7952 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7953 NewVD->hasLocalStorage())
7954 checkNonTrivialCUnion(QT: NewVD->getType(), Loc: NewVD->getLocation(),
7955 UseContext: NonTrivialCUnionContext::AutoVar, NonTrivialKind: NTCUK_Destruct);
7956 } else {
7957 bool Invalid = false;
7958 // Match up the template parameter lists with the scope specifier, then
7959 // determine whether we have a template or a template specialization.
7960 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7961 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
7962 SS: D.getCXXScopeSpec(),
7963 TemplateId: D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7964 ? D.getName().TemplateId
7965 : nullptr,
7966 ParamLists: TemplateParamLists,
7967 /*never a friend*/ IsFriend: false, IsMemberSpecialization, Invalid);
7968
7969 if (TemplateParams) {
7970 if (DC->isDependentContext()) {
7971 ContextRAII SavedContext(*this, DC);
7972 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
7973 Invalid = true;
7974 }
7975
7976 if (!TemplateParams->size() &&
7977 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7978 // There is an extraneous 'template<>' for this variable. Complain
7979 // about it, but allow the declaration of the variable.
7980 Diag(Loc: TemplateParams->getTemplateLoc(),
7981 DiagID: diag::err_template_variable_noparams)
7982 << II
7983 << SourceRange(TemplateParams->getTemplateLoc(),
7984 TemplateParams->getRAngleLoc());
7985 TemplateParams = nullptr;
7986 } else {
7987 // Check that we can declare a template here.
7988 if (CheckTemplateDeclScope(S, TemplateParams))
7989 return nullptr;
7990
7991 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7992 // This is an explicit specialization or a partial specialization.
7993 IsVariableTemplateSpecialization = true;
7994 IsPartialSpecialization = TemplateParams->size() > 0;
7995 } else { // if (TemplateParams->size() > 0)
7996 // This is a template declaration.
7997 IsVariableTemplate = true;
7998
7999 // Only C++1y supports variable templates (N3651).
8000 DiagCompat(Loc: D.getIdentifierLoc(), CompatDiagId: diag_compat::variable_template);
8001 }
8002 }
8003 } else {
8004 // Check that we can declare a member specialization here.
8005 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
8006 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
8007 return nullptr;
8008 assert((Invalid ||
8009 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
8010 "should have a 'template<>' for this decl");
8011 }
8012
8013 bool IsExplicitSpecialization =
8014 IsVariableTemplateSpecialization && !IsPartialSpecialization;
8015
8016 // C++ [temp.expl.spec]p2:
8017 // The declaration in an explicit-specialization shall not be an
8018 // export-declaration. An explicit specialization shall not use a
8019 // storage-class-specifier other than thread_local.
8020 //
8021 // We use the storage-class-specifier from DeclSpec because we may have
8022 // added implicit 'extern' for declarations with __declspec(dllimport)!
8023 if (SCSpec != DeclSpec::SCS_unspecified &&
8024 (IsExplicitSpecialization || IsMemberSpecialization)) {
8025 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8026 DiagID: diag::ext_explicit_specialization_storage_class)
8027 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8028 }
8029
8030 if (CurContext->isRecord()) {
8031 if (SC == SC_Static) {
8032 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
8033 // Walk up the enclosing DeclContexts to check for any that are
8034 // incompatible with static data members.
8035 const DeclContext *FunctionOrMethod = nullptr;
8036 const CXXRecordDecl *AnonStruct = nullptr;
8037 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
8038 if (Ctxt->isFunctionOrMethod()) {
8039 FunctionOrMethod = Ctxt;
8040 break;
8041 }
8042 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Val: Ctxt);
8043 if (ParentDecl && !ParentDecl->getDeclName()) {
8044 AnonStruct = ParentDecl;
8045 break;
8046 }
8047 }
8048 if (FunctionOrMethod) {
8049 // C++ [class.static.data]p5: A local class shall not have static
8050 // data members.
8051 Diag(Loc: D.getIdentifierLoc(),
8052 DiagID: diag::err_static_data_member_not_allowed_in_local_class)
8053 << Name << RD->getDeclName() << RD->getTagKind();
8054 Invalid = true;
8055 } else if (AnonStruct) {
8056 // C++ [class.static.data]p4: Unnamed classes and classes contained
8057 // directly or indirectly within unnamed classes shall not contain
8058 // static data members.
8059 Diag(Loc: D.getIdentifierLoc(),
8060 DiagID: diag::err_static_data_member_not_allowed_in_anon_struct)
8061 << Name << AnonStruct->getTagKind();
8062 Invalid = true;
8063 } else if (RD->isUnion()) {
8064 // C++98 [class.union]p1: If a union contains a static data member,
8065 // the program is ill-formed. C++11 drops this restriction.
8066 DiagCompat(Loc: D.getIdentifierLoc(),
8067 CompatDiagId: diag_compat::static_data_member_in_union)
8068 << Name;
8069 }
8070 }
8071 } else if (IsVariableTemplate || IsPartialSpecialization) {
8072 // There is no such thing as a member field template.
8073 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_member)
8074 << II << TemplateParams->getSourceRange();
8075 // Recover by pretending this is a static data member template.
8076 SC = SC_Static;
8077 }
8078 } else if (DC->isRecord()) {
8079 // This is an out-of-line definition of a static data member.
8080 switch (SC) {
8081 case SC_None:
8082 break;
8083 case SC_Static:
8084 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8085 DiagID: diag::err_static_out_of_line)
8086 << FixItHint::CreateRemoval(
8087 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8088 break;
8089 case SC_Auto:
8090 case SC_Register:
8091 case SC_Extern:
8092 // [dcl.stc] p2: The auto or register specifiers shall be applied only
8093 // to names of variables declared in a block or to function parameters.
8094 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
8095 // of class members
8096
8097 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8098 DiagID: diag::err_storage_class_for_static_member)
8099 << FixItHint::CreateRemoval(
8100 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8101 break;
8102 case SC_PrivateExtern:
8103 llvm_unreachable("C storage class in c++!");
8104 }
8105 }
8106
8107 if (IsVariableTemplateSpecialization) {
8108 SourceLocation TemplateKWLoc =
8109 TemplateParamLists.size() > 0
8110 ? TemplateParamLists[0]->getTemplateLoc()
8111 : SourceLocation();
8112 DeclResult Res = ActOnVarTemplateSpecialization(
8113 S, D, TSI: TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8114 IsPartialSpecialization);
8115 if (Res.isInvalid())
8116 return nullptr;
8117 NewVD = cast<VarDecl>(Val: Res.get());
8118 AddToScope = false;
8119 } else if (D.isDecompositionDeclarator()) {
8120 NewVD = DecompositionDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8121 LSquareLoc: D.getIdentifierLoc(), RSquareLoc: D.getEndLoc(), T: R,
8122 TInfo, S: SC, Bindings);
8123 } else
8124 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8125 IdLoc: D.getIdentifierLoc(), Id: II, T: R, TInfo, S: SC);
8126
8127 // If this is supposed to be a variable template, create it as such.
8128 if (IsVariableTemplate) {
8129 NewTemplate =
8130 VarTemplateDecl::Create(C&: Context, DC, L: D.getIdentifierLoc(), Name,
8131 Params: TemplateParams, Decl: NewVD);
8132 NewVD->setDescribedVarTemplate(NewTemplate);
8133 }
8134
8135 // If this decl has an auto type in need of deduction, make a note of the
8136 // Decl so we can diagnose uses of it in its own initializer.
8137 if (R->getContainedDeducedType())
8138 ParsingInitForAutoVars.insert(Ptr: NewVD);
8139
8140 if (D.isInvalidType() || Invalid) {
8141 NewVD->setInvalidDecl();
8142 if (NewTemplate)
8143 NewTemplate->setInvalidDecl();
8144 }
8145
8146 SetNestedNameSpecifier(S&: *this, DD: NewVD, D);
8147
8148 // If we have any template parameter lists that don't directly belong to
8149 // the variable (matching the scope specifier), store them.
8150 // An explicit variable template specialization does not own any template
8151 // parameter lists.
8152 unsigned VDTemplateParamLists =
8153 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8154 if (TemplateParamLists.size() > VDTemplateParamLists)
8155 NewVD->setTemplateParameterListsInfo(
8156 Context, TPLists: TemplateParamLists.drop_back(N: VDTemplateParamLists));
8157 }
8158
8159 if (D.getDeclSpec().isInlineSpecified()) {
8160 if (!getLangOpts().CPlusPlus) {
8161 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
8162 << 0;
8163 } else if (CurContext->isFunctionOrMethod()) {
8164 // 'inline' is not allowed on block scope variable declaration.
8165 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8166 DiagID: diag::err_inline_declaration_block_scope) << Name
8167 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
8168 } else {
8169 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8170 DiagID: getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8171 : diag::compat_pre_cxx17_inline_variable);
8172 NewVD->setInlineSpecified();
8173 }
8174 }
8175
8176 // Set the lexical context. If the declarator has a C++ scope specifier, the
8177 // lexical context will be different from the semantic context.
8178 NewVD->setLexicalDeclContext(CurContext);
8179 if (NewTemplate)
8180 NewTemplate->setLexicalDeclContext(CurContext);
8181
8182 if (IsLocalExternDecl) {
8183 if (D.isDecompositionDeclarator())
8184 for (auto *B : Bindings)
8185 B->setLocalExternDecl();
8186 else
8187 NewVD->setLocalExternDecl();
8188 }
8189
8190 bool EmitTLSUnsupportedError = false;
8191 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
8192 // C++11 [dcl.stc]p4:
8193 // When thread_local is applied to a variable of block scope the
8194 // storage-class-specifier static is implied if it does not appear
8195 // explicitly.
8196 // Core issue: 'static' is not implied if the variable is declared
8197 // 'extern'.
8198 if (NewVD->hasLocalStorage() &&
8199 (SCSpec != DeclSpec::SCS_unspecified ||
8200 TSCS != DeclSpec::TSCS_thread_local ||
8201 !DC->isFunctionOrMethod()))
8202 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8203 DiagID: diag::err_thread_non_global)
8204 << DeclSpec::getSpecifierName(S: TSCS);
8205 else if (!Context.getTargetInfo().isTLSSupported()) {
8206 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8207 // Postpone error emission until we've collected attributes required to
8208 // figure out whether it's a host or device variable and whether the
8209 // error should be ignored.
8210 EmitTLSUnsupportedError = true;
8211 // We still need to mark the variable as TLS so it shows up in AST with
8212 // proper storage class for other tools to use even if we're not going
8213 // to emit any code for it.
8214 NewVD->setTSCSpec(TSCS);
8215 } else
8216 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8217 DiagID: diag::err_thread_unsupported);
8218 } else
8219 NewVD->setTSCSpec(TSCS);
8220 }
8221
8222 switch (D.getDeclSpec().getConstexprSpecifier()) {
8223 case ConstexprSpecKind::Unspecified:
8224 break;
8225
8226 case ConstexprSpecKind::Consteval:
8227 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8228 DiagID: diag::err_constexpr_wrong_decl_kind)
8229 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8230 [[fallthrough]];
8231
8232 case ConstexprSpecKind::Constexpr:
8233 NewVD->setConstexpr(true);
8234 // C++1z [dcl.spec.constexpr]p1:
8235 // A static data member declared with the constexpr specifier is
8236 // implicitly an inline variable.
8237 if (NewVD->isStaticDataMember() &&
8238 (getLangOpts().CPlusPlus17 ||
8239 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8240 NewVD->setImplicitlyInline();
8241 break;
8242
8243 case ConstexprSpecKind::Constinit:
8244 if (!NewVD->hasGlobalStorage())
8245 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8246 DiagID: diag::err_constinit_local_variable);
8247 else
8248 NewVD->addAttr(
8249 A: ConstInitAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getConstexprSpecLoc(),
8250 S: ConstInitAttr::Keyword_constinit));
8251 break;
8252 }
8253
8254 // C99 6.7.4p3
8255 // An inline definition of a function with external linkage shall
8256 // not contain a definition of a modifiable object with static or
8257 // thread storage duration...
8258 // We only apply this when the function is required to be defined
8259 // elsewhere, i.e. when the function is not 'extern inline'. Note
8260 // that a local variable with thread storage duration still has to
8261 // be marked 'static'. Also note that it's possible to get these
8262 // semantics in C++ using __attribute__((gnu_inline)).
8263 if (SC == SC_Static && S->getFnParent() != nullptr &&
8264 !NewVD->getType().isConstQualified()) {
8265 FunctionDecl *CurFD = getCurFunctionDecl();
8266 if (CurFD && isFunctionDefinitionDiscarded(S&: *this, FD: CurFD)) {
8267 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8268 DiagID: diag::warn_static_local_in_extern_inline);
8269 MaybeSuggestAddingStaticToDecl(D: CurFD);
8270 }
8271 }
8272
8273 if (D.getDeclSpec().isModulePrivateSpecified()) {
8274 if (IsVariableTemplateSpecialization)
8275 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8276 << (IsPartialSpecialization ? 1 : 0)
8277 << FixItHint::CreateRemoval(
8278 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8279 else if (IsMemberSpecialization)
8280 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8281 << 2
8282 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8283 else if (NewVD->hasLocalStorage())
8284 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_local)
8285 << 0 << NewVD
8286 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8287 << FixItHint::CreateRemoval(
8288 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8289 else {
8290 NewVD->setModulePrivate();
8291 if (NewTemplate)
8292 NewTemplate->setModulePrivate();
8293 for (auto *B : Bindings)
8294 B->setModulePrivate();
8295 }
8296 }
8297
8298 if (getLangOpts().OpenCL) {
8299 deduceOpenCLAddressSpace(Var: NewVD);
8300
8301 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
8302 if (TSC != TSCS_unspecified) {
8303 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8304 DiagID: diag::err_opencl_unknown_type_specifier)
8305 << getLangOpts().getOpenCLVersionString()
8306 << DeclSpec::getSpecifierName(S: TSC) << 1;
8307 NewVD->setInvalidDecl();
8308 }
8309 }
8310
8311 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8312 // address space if the table has local storage (semantic checks elsewhere
8313 // will produce an error anyway).
8314 if (const auto *ATy = dyn_cast<ArrayType>(Val: NewVD->getType())) {
8315 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8316 !NewVD->hasLocalStorage()) {
8317 QualType Type = Context.getAddrSpaceQualType(
8318 T: NewVD->getType(), AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: 1));
8319 NewVD->setType(Type);
8320 }
8321 }
8322
8323 LoadExternalExtnameUndeclaredIdentifiers();
8324
8325 if (Expr *E = D.getAsmLabel()) {
8326 // The parser guarantees this is a string.
8327 StringLiteral *SE = cast<StringLiteral>(Val: E);
8328 StringRef Label = SE->getString();
8329
8330 // Insert the asm attribute.
8331 NewVD->addAttr(A: AsmLabelAttr::Create(Ctx&: Context, Label, Range: SE->getStrTokenLoc(TokNum: 0)));
8332 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8333 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8334 ExtnameUndeclaredIdentifiers.find(Key: NewVD->getIdentifier());
8335 if (I != ExtnameUndeclaredIdentifiers.end()) {
8336 if (isDeclExternC(D: NewVD)) {
8337 NewVD->addAttr(A: I->second);
8338 ExtnameUndeclaredIdentifiers.erase(Iterator: I);
8339 } else if (NewVD->getDeclContext()
8340 ->getRedeclContext()
8341 ->isTranslationUnit())
8342 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
8343 << /*Variable*/ 1 << NewVD;
8344 }
8345 }
8346
8347 // Handle attributes prior to checking for duplicates in MergeVarDecl
8348 ProcessDeclAttributes(S, D: NewVD, PD: D);
8349
8350 if (getLangOpts().HLSL)
8351 HLSL().ActOnVariableDeclarator(VD: NewVD);
8352
8353 if (getLangOpts().OpenACC)
8354 OpenACC().ActOnVariableDeclarator(VD: NewVD);
8355
8356 // FIXME: This is probably the wrong location to be doing this and we should
8357 // probably be doing this for more attributes (especially for function
8358 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8359 // the code to copy attributes would be generated by TableGen.
8360 if (R->isFunctionPointerType())
8361 if (const auto *TT = R->getAs<TypedefType>())
8362 copyAttrFromTypedefToDecl<AllocSizeAttr>(S&: *this, D: NewVD, TT);
8363
8364 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8365 if (EmitTLSUnsupportedError &&
8366 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) ||
8367 (getLangOpts().OpenMPIsTargetDevice &&
8368 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD: NewVD))))
8369 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8370 DiagID: diag::err_thread_unsupported);
8371
8372 if (EmitTLSUnsupportedError &&
8373 (LangOpts.SYCLIsDevice ||
8374 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8375 targetDiag(Loc: D.getIdentifierLoc(), DiagID: diag::err_thread_unsupported);
8376 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8377 // storage [duration]."
8378 if (SC == SC_None && S->getFnParent() != nullptr &&
8379 (NewVD->hasAttr<CUDASharedAttr>() ||
8380 NewVD->hasAttr<CUDAConstantAttr>())) {
8381 NewVD->setStorageClass(SC_Static);
8382 }
8383 }
8384
8385 // Ensure that dllimport globals without explicit storage class are treated as
8386 // extern. The storage class is set above using parsed attributes. Now we can
8387 // check the VarDecl itself.
8388 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8389 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8390 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8391
8392 // In auto-retain/release, infer strong retension for variables of
8393 // retainable type.
8394 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewVD))
8395 NewVD->setInvalidDecl();
8396
8397 // Check the ASM label here, as we need to know all other attributes of the
8398 // Decl first. Otherwise, we can't know if the asm label refers to the
8399 // host or device in a CUDA context. The device has other registers than
8400 // host and we must know where the function will be placed.
8401 CheckAsmLabel(S, E: D.getAsmLabel(), SC, TInfo, NewVD);
8402
8403 // Find the shadowed declaration before filtering for scope.
8404 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8405 ? getShadowedDeclaration(D: NewVD, R: Previous)
8406 : nullptr;
8407
8408 // Don't consider existing declarations that are in a different
8409 // scope and are out-of-semantic-context declarations (if the new
8410 // declaration has linkage).
8411 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(VD: NewVD),
8412 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
8413 IsMemberSpecialization ||
8414 IsVariableTemplateSpecialization);
8415
8416 // Check whether the previous declaration is in the same block scope. This
8417 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8418 if (getLangOpts().CPlusPlus &&
8419 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8420 NewVD->setPreviousDeclInSameBlockScope(
8421 Previous.isSingleResult() && !Previous.isShadowed() &&
8422 isDeclInScope(D: Previous.getFoundDecl(), Ctx: OriginalDC, S, AllowInlineNamespace: false));
8423
8424 if (!getLangOpts().CPlusPlus) {
8425 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8426 } else {
8427 // If this is an explicit specialization of a static data member, check it.
8428 if (IsMemberSpecialization && !IsVariableTemplate &&
8429 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8430 CheckMemberSpecialization(Member: NewVD, Previous))
8431 NewVD->setInvalidDecl();
8432
8433 // Merge the decl with the existing one if appropriate.
8434 if (!Previous.empty()) {
8435 if (Previous.isSingleResult() &&
8436 isa<FieldDecl>(Val: Previous.getFoundDecl()) &&
8437 D.getCXXScopeSpec().isSet()) {
8438 // The user tried to define a non-static data member
8439 // out-of-line (C++ [dcl.meaning]p1).
8440 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_nonstatic_member_out_of_line)
8441 << D.getCXXScopeSpec().getRange();
8442 Previous.clear();
8443 NewVD->setInvalidDecl();
8444 }
8445 } else if (D.getCXXScopeSpec().isSet() &&
8446 !IsVariableTemplateSpecialization) {
8447 // No previous declaration in the qualifying scope.
8448 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_no_member)
8449 << Name << computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext: true)
8450 << D.getCXXScopeSpec().getRange();
8451 NewVD->setInvalidDecl();
8452
8453 // if this is a member specialization, we don't have any primary template
8454 // to be instantiated from. We set ourselves to a 'fake' clone of this so
8455 // that anything that attempts to refer to this invalid declaration can
8456 // act as if there IS a primary instantiation.
8457 if (NewTemplate && IsMemberSpecialization) {
8458 VarDecl *FakeVD =
8459 VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
8460 Id: II, T: R, TInfo, S: SC);
8461 FakeVD->setInvalidDecl();
8462 VarTemplateDecl *FakeInstantiatedFrom = VarTemplateDecl::Create(
8463 C&: Context, DC, L: D.getIdentifierLoc(), Name, Params: TemplateParams, Decl: FakeVD);
8464 FakeInstantiatedFrom->setInvalidDecl();
8465 NewTemplate->setInstantiatedFromMemberTemplate(FakeInstantiatedFrom);
8466 }
8467 }
8468
8469 if (!IsPlaceholderVariable)
8470 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8471
8472 // CheckVariableDeclaration will set NewVD as invalid if something is in
8473 // error like WebAssembly tables being declared as arrays with a non-zero
8474 // size, but then parsing continues and emits further errors on that line.
8475 // To avoid that we check here if it happened and return nullptr.
8476 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8477 return nullptr;
8478
8479 if (NewTemplate) {
8480 VarTemplateDecl *PrevVarTemplate =
8481 NewVD->getPreviousDecl()
8482 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8483 : nullptr;
8484
8485 // Check the template parameter list of this declaration, possibly
8486 // merging in the template parameter list from the previous variable
8487 // template declaration.
8488 if (CheckTemplateParameterList(
8489 NewParams: TemplateParams,
8490 OldParams: PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8491 : nullptr,
8492 TPC: (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8493 DC->isDependentContext())
8494 ? TPC_ClassTemplateMember
8495 : TPC_Other))
8496 NewVD->setInvalidDecl();
8497 }
8498 }
8499
8500 if (IsMemberSpecialization) {
8501 if (NewTemplate && NewVD->getPreviousDecl()) {
8502 NewTemplate->setMemberSpecialization();
8503 } else if (IsPartialSpecialization) {
8504 cast<VarTemplatePartialSpecializationDecl>(Val: NewVD)
8505 ->setMemberSpecialization();
8506 }
8507 }
8508
8509 // Diagnose shadowed variables iff this isn't a redeclaration.
8510 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8511 CheckShadow(D: NewVD, ShadowedDecl, R: Previous);
8512
8513 ProcessPragmaWeak(S, D: NewVD);
8514 ProcessPragmaExport(NewD: NewVD);
8515
8516 // If this is the first declaration of an extern C variable, update
8517 // the map of such variables.
8518 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8519 isIncompleteDeclExternC(S&: *this, D: NewVD))
8520 RegisterLocallyScopedExternCDecl(ND: NewVD, S);
8521
8522 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8523 MangleNumberingContext *MCtx;
8524 Decl *ManglingContextDecl;
8525 std::tie(args&: MCtx, args&: ManglingContextDecl) =
8526 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
8527 if (MCtx) {
8528 Context.setManglingNumber(
8529 ND: NewVD, Number: MCtx->getManglingNumber(
8530 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
8531 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
8532 }
8533 }
8534
8535 // Special handling of variable named 'main'.
8536 if (!getLangOpts().Freestanding && isMainVar(Name, VD: NewVD)) {
8537 // C++ [basic.start.main]p3:
8538 // A program that declares
8539 // - a variable main at global scope, or
8540 // - an entity named main with C language linkage (in any namespace)
8541 // is ill-formed
8542 if (getLangOpts().CPlusPlus)
8543 Diag(Loc: D.getBeginLoc(), DiagID: diag::err_main_global_variable)
8544 << NewVD->isExternC();
8545
8546 // In C, and external-linkage variable named main results in undefined
8547 // behavior.
8548 else if (NewVD->hasExternalFormalLinkage())
8549 Diag(Loc: D.getBeginLoc(), DiagID: diag::warn_main_redefined);
8550 }
8551
8552 if (D.isRedeclaration() && !Previous.empty()) {
8553 NamedDecl *Prev = Previous.getRepresentativeDecl();
8554 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewVD, IsSpecialization: IsMemberSpecialization,
8555 IsDefinition: D.isFunctionDefinition());
8556 }
8557
8558 if (NewTemplate) {
8559 if (NewVD->isInvalidDecl())
8560 NewTemplate->setInvalidDecl();
8561 ActOnDocumentableDecl(D: NewTemplate);
8562 return NewTemplate;
8563 }
8564
8565 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8566 CompleteMemberSpecialization(Member: NewVD, Previous);
8567
8568 emitReadOnlyPlacementAttrWarning(S&: *this, VD: NewVD);
8569
8570 return NewVD;
8571}
8572
8573/// Enum describing the %select options in diag::warn_decl_shadow.
8574enum ShadowedDeclKind {
8575 SDK_Local,
8576 SDK_Global,
8577 SDK_StaticMember,
8578 SDK_Field,
8579 SDK_Typedef,
8580 SDK_Using,
8581 SDK_StructuredBinding
8582};
8583
8584/// Determine what kind of declaration we're shadowing.
8585static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8586 const DeclContext *OldDC) {
8587 if (isa<TypeAliasDecl>(Val: ShadowedDecl))
8588 return SDK_Using;
8589 else if (isa<TypedefDecl>(Val: ShadowedDecl))
8590 return SDK_Typedef;
8591 else if (isa<BindingDecl>(Val: ShadowedDecl))
8592 return SDK_StructuredBinding;
8593 else if (isa<RecordDecl>(Val: OldDC))
8594 return isa<FieldDecl>(Val: ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8595
8596 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8597}
8598
8599/// Return the location of the capture if the given lambda captures the given
8600/// variable \p VD, or an invalid source location otherwise.
8601static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8602 const ValueDecl *VD) {
8603 for (const Capture &Capture : LSI->Captures) {
8604 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8605 return Capture.getLocation();
8606 }
8607 return SourceLocation();
8608}
8609
8610static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8611 const LookupResult &R) {
8612 // Only diagnose if we're shadowing an unambiguous field or variable.
8613 if (R.getResultKind() != LookupResultKind::Found)
8614 return false;
8615
8616 // Return false if warning is ignored.
8617 return !Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: R.getNameLoc());
8618}
8619
8620NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8621 const LookupResult &R) {
8622 if (!shouldWarnIfShadowedDecl(Diags, R))
8623 return nullptr;
8624
8625 // Don't diagnose declarations at file scope.
8626 if (D->hasGlobalStorage() && !D->isStaticLocal())
8627 return nullptr;
8628
8629 NamedDecl *ShadowedDecl = R.getFoundDecl();
8630 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8631 : nullptr;
8632}
8633
8634NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8635 const LookupResult &R) {
8636 // Don't warn if typedef declaration is part of a class
8637 if (D->getDeclContext()->isRecord())
8638 return nullptr;
8639
8640 if (!shouldWarnIfShadowedDecl(Diags, R))
8641 return nullptr;
8642
8643 NamedDecl *ShadowedDecl = R.getFoundDecl();
8644 return isa<TypedefNameDecl>(Val: ShadowedDecl) ? ShadowedDecl : nullptr;
8645}
8646
8647NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8648 const LookupResult &R) {
8649 if (!shouldWarnIfShadowedDecl(Diags, R))
8650 return nullptr;
8651
8652 NamedDecl *ShadowedDecl = R.getFoundDecl();
8653 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8654 : nullptr;
8655}
8656
8657void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8658 const LookupResult &R) {
8659 DeclContext *NewDC = D->getDeclContext();
8660
8661 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ShadowedDecl)) {
8662 DeclContext *FnDC = getFunctionLevelDeclContext();
8663 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDC)) {
8664 // Fields aren't shadowed in C++ static members or in member functions
8665 // with an explicit object parameter.
8666 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8667 return;
8668 } else if (isa<FunctionDecl>(Val: FnDC)) {
8669 // A FunctionDecl here (not a CXXMethodDecl) can only be an
8670 // inline-defined friend function, since that's the only way to
8671 // introduce a non-member function inside a class body. Friends have
8672 // no implicit `this`, so nothing here can shadow a field.
8673 return;
8674 }
8675 // Fields shadowed by constructor parameters are a special case. Usually
8676 // the constructor initializes the field with the parameter.
8677 if (isa<CXXConstructorDecl>(Val: NewDC))
8678 if (const auto PVD = dyn_cast<ParmVarDecl>(Val: D)) {
8679 // Remember that this was shadowed so we can either warn about its
8680 // modification or its existence depending on warning settings.
8681 ShadowingDecls.insert(KV: {PVD->getCanonicalDecl(), FD});
8682 return;
8683 }
8684 }
8685
8686 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(Val: ShadowedDecl))
8687 if (shadowedVar->isExternC()) {
8688 // For shadowing external vars, make sure that we point to the global
8689 // declaration, not a locally scoped extern declaration.
8690 for (auto *I : shadowedVar->redecls())
8691 if (I->isFileVarDecl()) {
8692 ShadowedDecl = I;
8693 break;
8694 }
8695 }
8696
8697 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8698
8699 unsigned WarningDiag = diag::warn_decl_shadow;
8700 SourceLocation CaptureLoc;
8701 if (isa<VarDecl>(Val: D) && NewDC && isa<CXXMethodDecl>(Val: NewDC)) {
8702 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: NewDC->getParent())) {
8703 if (RD->isLambda() && OldDC->Encloses(DC: NewDC->getLexicalParent())) {
8704 // Handle both VarDecl and BindingDecl in lambda contexts
8705 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8706 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8707 const auto *LSI = cast<LambdaScopeInfo>(Val: getCurFunction());
8708 if (RD->getLambdaCaptureDefault() == LCD_None) {
8709 // Try to avoid warnings for lambdas with an explicit capture
8710 // list. Warn only when the lambda captures the shadowed decl
8711 // explicitly.
8712 CaptureLoc = getCaptureLocation(LSI, VD);
8713 if (CaptureLoc.isInvalid())
8714 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8715 } else {
8716 // Remember that this was shadowed so we can avoid the warning if
8717 // the shadowed decl isn't captured and the warning settings allow
8718 // it.
8719 cast<LambdaScopeInfo>(Val: getCurFunction())
8720 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: VD});
8721 return;
8722 }
8723 }
8724 if (isa<FieldDecl>(Val: ShadowedDecl)) {
8725 // If lambda can capture this, then emit default shadowing warning,
8726 // Otherwise it is not really a shadowing case since field is not
8727 // available in lambda's body.
8728 // At this point we don't know that lambda can capture this, so
8729 // remember that this was shadowed and delay until we know.
8730 cast<LambdaScopeInfo>(Val: getCurFunction())
8731 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: ShadowedDecl});
8732 return;
8733 }
8734 }
8735 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8736 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8737 bool HasLocalStorage = false;
8738 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl))
8739 HasLocalStorage = VD->hasLocalStorage();
8740 else if (const auto *BD = dyn_cast<BindingDecl>(Val: ShadowedDecl))
8741 HasLocalStorage =
8742 cast<VarDecl>(Val: BD->getDecomposedDecl())->hasLocalStorage();
8743
8744 if (HasLocalStorage) {
8745 // A variable can't shadow a local variable or binding in an enclosing
8746 // scope, if they are separated by a non-capturing declaration
8747 // context.
8748 for (DeclContext *ParentDC = NewDC;
8749 ParentDC && !ParentDC->Equals(DC: OldDC);
8750 ParentDC = getLambdaAwareParentOfDeclContext(DC: ParentDC)) {
8751 // Only block literals, captured statements, and lambda expressions
8752 // can capture; other scopes don't.
8753 if (!isa<BlockDecl>(Val: ParentDC) && !isa<CapturedDecl>(Val: ParentDC) &&
8754 !isLambdaCallOperator(DC: ParentDC))
8755 return;
8756 }
8757 }
8758 }
8759 }
8760 }
8761
8762 // Never warn about shadowing a placeholder variable.
8763 if (ShadowedDecl->isPlaceholderVar(LangOpts: getLangOpts()))
8764 return;
8765
8766 // Only warn about certain kinds of shadowing for class members.
8767 if (NewDC) {
8768 // In particular, don't warn about shadowing non-class members.
8769 if (NewDC->isRecord() && !OldDC->isRecord())
8770 return;
8771
8772 // Skip shadowing check if we're in a class scope, dealing with an enum
8773 // constant in a different context.
8774 DeclContext *ReDC = NewDC->getRedeclContext();
8775 if (ReDC->isRecord() && isa<EnumConstantDecl>(Val: D) && !OldDC->Equals(DC: ReDC))
8776 return;
8777
8778 // TODO: should we warn about static data members shadowing
8779 // static data members from base classes?
8780
8781 // TODO: don't diagnose for inaccessible shadowed members.
8782 // This is hard to do perfectly because we might friend the
8783 // shadowing context, but that's just a false negative.
8784 }
8785
8786 DeclarationName Name = R.getLookupName();
8787
8788 // Emit warning and note.
8789 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8790 Diag(Loc: R.getNameLoc(), DiagID: WarningDiag) << Name << Kind << OldDC;
8791 if (!CaptureLoc.isInvalid())
8792 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8793 << Name << /*explicitly*/ 1;
8794 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8795}
8796
8797void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8798 for (const auto &Shadow : LSI->ShadowingDecls) {
8799 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8800 // Try to avoid the warning when the shadowed decl isn't captured.
8801 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8802 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8803 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8804 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8805 Diag(Loc: Shadow.VD->getLocation(),
8806 DiagID: CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8807 : diag::warn_decl_shadow)
8808 << Shadow.VD->getDeclName()
8809 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8810 if (CaptureLoc.isValid())
8811 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8812 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8813 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8814 } else if (isa<FieldDecl>(Val: ShadowedDecl)) {
8815 Diag(Loc: Shadow.VD->getLocation(),
8816 DiagID: LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8817 : diag::warn_decl_shadow_uncaptured_local)
8818 << Shadow.VD->getDeclName()
8819 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8820 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8821 }
8822 }
8823}
8824
8825void Sema::CheckShadow(Scope *S, VarDecl *D) {
8826 if (Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: D->getLocation()))
8827 return;
8828
8829 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8830 Sema::LookupOrdinaryName,
8831 RedeclarationKind::ForVisibleRedeclaration);
8832 LookupName(R, S);
8833 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8834 CheckShadow(D, ShadowedDecl, R);
8835}
8836
8837/// Check if 'E', which is an expression that is about to be modified, refers
8838/// to a constructor parameter that shadows a field.
8839void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8840 // Quickly ignore expressions that can't be shadowing ctor parameters.
8841 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8842 return;
8843 E = E->IgnoreParenImpCasts();
8844 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
8845 if (!DRE)
8846 return;
8847 const NamedDecl *D = cast<NamedDecl>(Val: DRE->getDecl()->getCanonicalDecl());
8848 auto I = ShadowingDecls.find(Val: D);
8849 if (I == ShadowingDecls.end())
8850 return;
8851 const NamedDecl *ShadowedDecl = I->second;
8852 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8853 Diag(Loc, DiagID: diag::warn_modifying_shadowing_decl) << D << OldDC;
8854 Diag(Loc: D->getLocation(), DiagID: diag::note_var_declared_here) << D;
8855 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8856
8857 // Avoid issuing multiple warnings about the same decl.
8858 ShadowingDecls.erase(I);
8859}
8860
8861/// Check for conflict between this global or extern "C" declaration and
8862/// previous global or extern "C" declarations. This is only used in C++.
8863template<typename T>
8864static bool checkGlobalOrExternCConflict(
8865 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8866 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8867 NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName());
8868
8869 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8870 // The common case: this global doesn't conflict with any extern "C"
8871 // declaration.
8872 return false;
8873 }
8874
8875 if (Prev) {
8876 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8877 // Both the old and new declarations have C language linkage. This is a
8878 // redeclaration.
8879 Previous.clear();
8880 Previous.addDecl(D: Prev);
8881 return true;
8882 }
8883
8884 // This is a global, non-extern "C" declaration, and there is a previous
8885 // non-global extern "C" declaration. Diagnose if this is a variable
8886 // declaration.
8887 if (!isa<VarDecl>(ND))
8888 return false;
8889 } else {
8890 // The declaration is extern "C". Check for any declaration in the
8891 // translation unit which might conflict.
8892 if (IsGlobal) {
8893 // We have already performed the lookup into the translation unit.
8894 IsGlobal = false;
8895 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8896 I != E; ++I) {
8897 if (isa<VarDecl>(Val: *I)) {
8898 Prev = *I;
8899 break;
8900 }
8901 }
8902 } else {
8903 DeclContext::lookup_result R =
8904 S.Context.getTranslationUnitDecl()->lookup(Name: ND->getDeclName());
8905 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8906 I != E; ++I) {
8907 if (isa<VarDecl>(Val: *I)) {
8908 Prev = *I;
8909 break;
8910 }
8911 // FIXME: If we have any other entity with this name in global scope,
8912 // the declaration is ill-formed, but that is a defect: it breaks the
8913 // 'stat' hack, for instance. Only variables can have mangled name
8914 // clashes with extern "C" declarations, so only they deserve a
8915 // diagnostic.
8916 }
8917 }
8918
8919 if (!Prev)
8920 return false;
8921 }
8922
8923 // Use the first declaration's location to ensure we point at something which
8924 // is lexically inside an extern "C" linkage-spec.
8925 assert(Prev && "should have found a previous declaration to diagnose");
8926 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: Prev))
8927 Prev = FD->getFirstDecl();
8928 else
8929 Prev = cast<VarDecl>(Val: Prev)->getFirstDecl();
8930
8931 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8932 << IsGlobal << ND;
8933 S.Diag(Loc: Prev->getLocation(), DiagID: diag::note_extern_c_global_conflict)
8934 << IsGlobal;
8935 return false;
8936}
8937
8938/// Apply special rules for handling extern "C" declarations. Returns \c true
8939/// if we have found that this is a redeclaration of some prior entity.
8940///
8941/// Per C++ [dcl.link]p6:
8942/// Two declarations [for a function or variable] with C language linkage
8943/// with the same name that appear in different scopes refer to the same
8944/// [entity]. An entity with C language linkage shall not be declared with
8945/// the same name as an entity in global scope.
8946template<typename T>
8947static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8948 LookupResult &Previous) {
8949 if (!S.getLangOpts().CPlusPlus) {
8950 // In C, when declaring a global variable, look for a corresponding 'extern'
8951 // variable declared in function scope. We don't need this in C++, because
8952 // we find local extern decls in the surrounding file-scope DeclContext.
8953 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8954 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName())) {
8955 Previous.clear();
8956 Previous.addDecl(D: Prev);
8957 return true;
8958 }
8959 }
8960 return false;
8961 }
8962
8963 // A declaration in the translation unit can conflict with an extern "C"
8964 // declaration.
8965 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8966 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8967
8968 // An extern "C" declaration can conflict with a declaration in the
8969 // translation unit or can be a redeclaration of an extern "C" declaration
8970 // in another scope.
8971 if (isIncompleteDeclExternC(S,ND))
8972 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8973
8974 // Neither global nor extern "C": nothing to do.
8975 return false;
8976}
8977
8978static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8979 QualType T) {
8980 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8981 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8982 // any of its members, even recursively, shall not have an atomic type, or a
8983 // variably modified type, or a type that is volatile or restrict qualified.
8984 if (CanonT->isVariablyModifiedType()) {
8985 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8986 return true;
8987 }
8988
8989 // Arrays are qualified by their element type, so get the base type (this
8990 // works on non-arrays as well).
8991 CanonT = SemaRef.Context.getBaseElementType(QT: CanonT);
8992
8993 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8994 CanonT.isRestrictQualified()) {
8995 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8996 return true;
8997 }
8998
8999 if (CanonT->isRecordType()) {
9000 const RecordDecl *RD = CanonT->getAsRecordDecl();
9001 if (!RD->isInvalidDecl() &&
9002 llvm::any_of(Range: RD->fields(), P: [&SemaRef, VarLoc](const FieldDecl *F) {
9003 return CheckC23ConstexprVarType(SemaRef, VarLoc, T: F->getType());
9004 }))
9005 return true;
9006 }
9007
9008 return false;
9009}
9010
9011static bool isSYCLAddressSpace(LangAS AS) {
9012 return AS >= LangAS::sycl_global && AS <= LangAS::sycl_constant;
9013}
9014
9015void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
9016 // If the decl is already known invalid, don't check it.
9017 if (NewVD->isInvalidDecl())
9018 return;
9019
9020 QualType T = NewVD->getType();
9021
9022 // Defer checking an 'auto' type until its initializer is attached.
9023 if (T->isUndeducedType())
9024 return;
9025
9026 if (NewVD->hasAttrs())
9027 CheckAlignasUnderalignment(D: NewVD);
9028
9029 if (T->isObjCObjectType()) {
9030 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_statically_allocated_object)
9031 << FixItHint::CreateInsertion(InsertionLoc: NewVD->getLocation(), Code: "*");
9032 T = Context.getObjCObjectPointerType(OIT: T);
9033 NewVD->setType(T);
9034 }
9035
9036 // The top-level type of a variable declaration cannot have a SYCL address
9037 // space qualifier.
9038 if (getLangOpts().isSYCL()) {
9039 LangAS AS = Context.getBaseElementType(QT: T).getAddressSpace();
9040 if (isSYCLAddressSpace(AS)) {
9041 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sycl_address_space_qualified_object)
9042 << Qualifiers::getAddrSpaceAsString(AS);
9043 NewVD->setInvalidDecl();
9044 return;
9045 }
9046 }
9047
9048 // Emit an error if an address space was applied to decl with local storage.
9049 // This includes arrays of objects with address space qualifiers, but not
9050 // automatic variables that point to other address spaces.
9051 // ISO/IEC TR 18037 S5.1.2
9052 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
9053 T.getAddressSpace() != LangAS::Default) {
9054 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 0;
9055 NewVD->setInvalidDecl();
9056 return;
9057 }
9058
9059 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
9060 // scope.
9061 if (getLangOpts().OpenCLVersion == 120 &&
9062 !getOpenCLOptions().isAvailableOption(Ext: "cl_clang_storage_class_specifiers",
9063 LO: getLangOpts()) &&
9064 NewVD->isStaticLocal()) {
9065 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_static_function_scope);
9066 NewVD->setInvalidDecl();
9067 return;
9068 }
9069
9070 if (getLangOpts().OpenCL) {
9071 if (!diagnoseOpenCLTypes(Se&: *this, NewVD))
9072 return;
9073
9074 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
9075 if (NewVD->hasAttr<BlocksAttr>()) {
9076 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_block_storage_type);
9077 return;
9078 }
9079
9080 if (T->isBlockPointerType()) {
9081 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
9082 // can't use 'extern' storage class.
9083 if (!T.isConstQualified()) {
9084 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
9085 << 0 /*const*/;
9086 NewVD->setInvalidDecl();
9087 return;
9088 }
9089 if (NewVD->hasExternalStorage()) {
9090 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_extern_block_declaration);
9091 NewVD->setInvalidDecl();
9092 return;
9093 }
9094 }
9095
9096 // FIXME: Adding local AS in C++ for OpenCL might make sense.
9097 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
9098 NewVD->hasExternalStorage()) {
9099 if (!T->isSamplerT() && !T->isDependentType() &&
9100 !(T.getAddressSpace() == LangAS::opencl_constant ||
9101 (T.getAddressSpace() == LangAS::opencl_global &&
9102 getOpenCLOptions().areProgramScopeVariablesSupported(
9103 Opts: getLangOpts())))) {
9104 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
9105 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()))
9106 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
9107 << Scope << "global or constant";
9108 else
9109 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
9110 << Scope << "constant";
9111 NewVD->setInvalidDecl();
9112 return;
9113 }
9114 } else {
9115 if (T.getAddressSpace() == LangAS::opencl_global) {
9116 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9117 << 1 /*is any function*/ << "global";
9118 NewVD->setInvalidDecl();
9119 return;
9120 }
9121 // When this extension is enabled, 'local' variables are permitted in
9122 // non-kernel functions and within nested scopes of kernel functions,
9123 // bypassing standard OpenCL address space restrictions.
9124 bool AllowFunctionScopeLocalVariables =
9125 T.getAddressSpace() == LangAS::opencl_local &&
9126 getOpenCLOptions().isAvailableOption(
9127 Ext: "__cl_clang_function_scope_local_variables", LO: getLangOpts());
9128 if (AllowFunctionScopeLocalVariables) {
9129 // Direct pass: No further diagnostics needed for this specific case.
9130 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
9131 T.getAddressSpace() == LangAS::opencl_local) {
9132 FunctionDecl *FD = getCurFunctionDecl();
9133 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
9134 // in functions.
9135 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
9136 if (T.getAddressSpace() == LangAS::opencl_constant)
9137 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9138 << 0 /*non-kernel only*/ << "constant";
9139 else
9140 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9141 << 0 /*non-kernel only*/ << "local";
9142 NewVD->setInvalidDecl();
9143 return;
9144 }
9145 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9146 // in the outermost scope of a kernel function.
9147 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9148 if (!getCurScope()->isFunctionScope()) {
9149 if (T.getAddressSpace() == LangAS::opencl_constant)
9150 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9151 << "constant";
9152 else
9153 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9154 << "local";
9155 NewVD->setInvalidDecl();
9156 return;
9157 }
9158 }
9159 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9160 // If we are parsing a template we didn't deduce an addr
9161 // space yet.
9162 T.getAddressSpace() != LangAS::Default) {
9163 // Do not allow other address spaces on automatic variable.
9164 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 1;
9165 NewVD->setInvalidDecl();
9166 return;
9167 }
9168 }
9169 }
9170
9171 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9172 && !NewVD->hasAttr<BlocksAttr>()) {
9173 if (getLangOpts().getGC() != LangOptions::NonGC)
9174 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_gc_attribute_weak_on_local);
9175 else {
9176 assert(!getLangOpts().ObjCAutoRefCount);
9177 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_attribute_weak_on_local);
9178 }
9179 }
9180
9181 // WebAssembly tables must be static with a zero length and can't be
9182 // declared within functions.
9183 if (T->isWebAssemblyTableType()) {
9184 if (getCurScope()->getParent()) { // Parent is null at top-level
9185 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_in_function);
9186 NewVD->setInvalidDecl();
9187 return;
9188 }
9189 if (NewVD->getStorageClass() != SC_Static) {
9190 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_must_be_static);
9191 NewVD->setInvalidDecl();
9192 return;
9193 }
9194 const auto *ATy = dyn_cast<ConstantArrayType>(Val: T.getTypePtr());
9195 if (!ATy || ATy->getZExtSize() != 0) {
9196 Diag(Loc: NewVD->getLocation(),
9197 DiagID: diag::err_typecheck_wasm_table_must_have_zero_length);
9198 NewVD->setInvalidDecl();
9199 return;
9200 }
9201 }
9202
9203 // zero sized static arrays are not allowed in HIP device functions
9204 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9205 if (FunctionDecl *FD = getCurFunctionDecl();
9206 FD &&
9207 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9208 if (const ConstantArrayType *ArrayT =
9209 getASTContext().getAsConstantArrayType(T);
9210 ArrayT && ArrayT->isZeroSize()) {
9211 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_zero_array_size) << 2;
9212 }
9213 }
9214 }
9215
9216 bool isVM = T->isVariablyModifiedType();
9217 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9218 NewVD->hasAttr<BlocksAttr>())
9219 setFunctionHasBranchProtectedScope();
9220
9221 if ((isVM && NewVD->hasLinkage()) ||
9222 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9223 bool SizeIsNegative;
9224 llvm::APSInt Oversized;
9225 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
9226 TInfo: NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9227 QualType FixedT;
9228 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9229 FixedT = FixedTInfo->getType();
9230 else if (FixedTInfo) {
9231 // Type and type-as-written are canonically different. We need to fix up
9232 // both types separately.
9233 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9234 Oversized);
9235 }
9236 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9237 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9238 // FIXME: This won't give the correct result for
9239 // int a[10][n];
9240 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9241
9242 if (NewVD->isFileVarDecl())
9243 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope)
9244 << SizeRange;
9245 else if (NewVD->isStaticLocal())
9246 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_static_storage)
9247 << SizeRange;
9248 else
9249 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_extern_linkage)
9250 << SizeRange;
9251 NewVD->setInvalidDecl();
9252 return;
9253 }
9254
9255 if (!FixedTInfo) {
9256 if (NewVD->isFileVarDecl())
9257 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
9258 else
9259 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_has_extern_linkage);
9260 NewVD->setInvalidDecl();
9261 return;
9262 }
9263
9264 Diag(Loc: NewVD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
9265 NewVD->setType(FixedT);
9266 NewVD->setTypeSourceInfo(FixedTInfo);
9267 }
9268
9269 if (T->isVoidType()) {
9270 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9271 // of objects and functions.
9272 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
9273 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
9274 << T;
9275 NewVD->setInvalidDecl();
9276 return;
9277 }
9278 }
9279
9280 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9281 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9282 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sizeless_nonlocal) << T;
9283 NewVD->setInvalidDecl();
9284 return;
9285 }
9286
9287 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9288 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_not_allowed_on)
9289 << diag::NotAllowedBlockVarReason::VariablyModifiedType;
9290 NewVD->setInvalidDecl();
9291 return;
9292 }
9293
9294 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9295 CheckC23ConstexprVarType(SemaRef&: *this, VarLoc: NewVD->getLocation(), T)) {
9296 NewVD->setInvalidDecl();
9297 return;
9298 }
9299
9300 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9301 !T->isDependentType() &&
9302 RequireLiteralType(Loc: NewVD->getLocation(), T,
9303 DiagID: diag::err_constexpr_var_non_literal)) {
9304 NewVD->setInvalidDecl();
9305 return;
9306 }
9307
9308 // PPC MMA non-pointer types are not allowed as non-local variable types.
9309 if (Context.getTargetInfo().getTriple().isPPC64() &&
9310 !NewVD->isLocalVarDecl() &&
9311 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewVD->getLocation())) {
9312 NewVD->setInvalidDecl();
9313 return;
9314 }
9315
9316 // Check that SVE types are only used in functions with SVE available.
9317 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9318 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9319 llvm::StringMap<bool> CallerFeatureMap;
9320 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9321 if (ARM().checkSVETypeSupport(Ty: T, Loc: NewVD->getLocation(), FD,
9322 FeatureMap: CallerFeatureMap)) {
9323 NewVD->setInvalidDecl();
9324 return;
9325 }
9326 }
9327
9328 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9329 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9330 llvm::StringMap<bool> CallerFeatureMap;
9331 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9332 RISCV().checkRVVTypeSupport(Ty: T, Loc: NewVD->getLocation(), D: cast<Decl>(Val: CurContext),
9333 FeatureMap: CallerFeatureMap);
9334 }
9335
9336 if (Context.getTargetInfo().hasAMDGPUTypes()) {
9337 if (!AMDGPU().checkAMDGPUTypeSupport(Ty: T, Loc: NewVD->getLocation())) {
9338 NewVD->setInvalidDecl();
9339 return;
9340 }
9341 }
9342
9343 if (T.hasAddressSpace() &&
9344 !CheckVarDeclSizeAddressSpace(VD: NewVD, AS: T.getAddressSpace())) {
9345 NewVD->setInvalidDecl();
9346 return;
9347 }
9348}
9349
9350bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
9351 CheckVariableDeclarationType(NewVD);
9352
9353 // If the decl is already known invalid, don't check it.
9354 if (NewVD->isInvalidDecl())
9355 return false;
9356
9357 // If we did not find anything by this name, look for a non-visible
9358 // extern "C" declaration with the same name.
9359 if (Previous.empty() &&
9360 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewVD, Previous))
9361 Previous.setShadowed();
9362
9363 if (!Previous.empty()) {
9364 MergeVarDecl(New: NewVD, Previous);
9365 return true;
9366 }
9367 return false;
9368}
9369
9370bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
9371 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
9372
9373 // Look for methods in base classes that this method might override.
9374 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9375 /*DetectVirtual=*/false);
9376 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9377 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9378 DeclarationName Name = MD->getDeclName();
9379
9380 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9381 // We really want to find the base class destructor here.
9382 Name = Context.DeclarationNames.getCXXDestructorName(
9383 Ty: Context.getCanonicalTagType(TD: BaseRecord));
9384 }
9385
9386 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9387 CXXMethodDecl *BaseMD =
9388 dyn_cast<CXXMethodDecl>(Val: BaseND->getCanonicalDecl());
9389 if (!BaseMD || !BaseMD->isVirtual() ||
9390 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9391 /*ConsiderCudaAttrs=*/true))
9392 continue;
9393 if (!CheckExplicitObjectOverride(New: MD, Old: BaseMD))
9394 continue;
9395 if (Overridden.insert(Ptr: BaseMD).second) {
9396 MD->addOverriddenMethod(MD: BaseMD);
9397 CheckOverridingFunctionReturnType(New: MD, Old: BaseMD);
9398 CheckOverridingFunctionAttributes(New: MD, Old: BaseMD);
9399 CheckOverridingFunctionExceptionSpec(New: MD, Old: BaseMD);
9400 CheckIfOverriddenFunctionIsMarkedFinal(New: MD, Old: BaseMD);
9401 }
9402
9403 // A method can only override one function from each base class. We
9404 // don't track indirectly overridden methods from bases of bases.
9405 return true;
9406 }
9407
9408 return false;
9409 };
9410
9411 DC->lookupInBases(BaseMatches: VisitBase, Paths);
9412 return !Overridden.empty();
9413}
9414
9415namespace {
9416 // Struct for holding all of the extra arguments needed by
9417 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9418 struct ActOnFDArgs {
9419 Scope *S;
9420 Declarator &D;
9421 MultiTemplateParamsArg TemplateParamLists;
9422 bool AddToScope;
9423 };
9424} // end anonymous namespace
9425
9426namespace {
9427
9428// Callback to only accept typo corrections that have a non-zero edit distance.
9429// Also only accept corrections that have the same parent decl.
9430class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9431 public:
9432 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9433 CXXRecordDecl *Parent)
9434 : Context(Context), OriginalFD(TypoFD),
9435 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9436
9437 bool ValidateCandidate(const TypoCorrection &candidate) override {
9438 if (candidate.getEditDistance() == 0)
9439 return false;
9440
9441 SmallVector<unsigned, 1> MismatchedParams;
9442 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9443 CDeclEnd = candidate.end();
9444 CDecl != CDeclEnd; ++CDecl) {
9445 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9446
9447 if (FD && !FD->hasBody() &&
9448 hasSimilarParameters(Context, Declaration: FD, Definition: OriginalFD, Params&: MismatchedParams)) {
9449 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
9450 CXXRecordDecl *Parent = MD->getParent();
9451 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9452 return true;
9453 } else if (!ExpectedParent) {
9454 return true;
9455 }
9456 }
9457 }
9458
9459 return false;
9460 }
9461
9462 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9463 return std::make_unique<DifferentNameValidatorCCC>(args&: *this);
9464 }
9465
9466 private:
9467 ASTContext &Context;
9468 FunctionDecl *OriginalFD;
9469 CXXRecordDecl *ExpectedParent;
9470};
9471
9472} // end anonymous namespace
9473
9474void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9475 TypoCorrectedFunctionDefinitions.insert(Ptr: F);
9476}
9477
9478/// Generate diagnostics for an invalid function redeclaration.
9479///
9480/// This routine handles generating the diagnostic messages for an invalid
9481/// function redeclaration, including finding possible similar declarations
9482/// or performing typo correction if there are no previous declarations with
9483/// the same name.
9484///
9485/// Returns a NamedDecl iff typo correction was performed and substituting in
9486/// the new declaration name does not cause new errors.
9487static NamedDecl *DiagnoseInvalidRedeclaration(
9488 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9489 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9490 DeclarationName Name = NewFD->getDeclName();
9491 DeclContext *NewDC = NewFD->getDeclContext();
9492 SmallVector<unsigned, 1> MismatchedParams;
9493 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9494 TypoCorrection Correction;
9495 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9496 unsigned DiagMsg =
9497 IsLocalFriend ? diag::err_no_matching_local_friend :
9498 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9499 diag::err_member_decl_does_not_match;
9500 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9501 IsLocalFriend ? Sema::LookupLocalFriendName
9502 : Sema::LookupOrdinaryName,
9503 RedeclarationKind::ForVisibleRedeclaration);
9504
9505 NewFD->setInvalidDecl();
9506 if (IsLocalFriend)
9507 SemaRef.LookupName(R&: Prev, S);
9508 else
9509 SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: NewDC);
9510 assert(!Prev.isAmbiguous() &&
9511 "Cannot have an ambiguity in previous-declaration lookup");
9512 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9513 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9514 MD ? MD->getParent() : nullptr);
9515 if (!Prev.empty()) {
9516 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9517 Func != FuncEnd; ++Func) {
9518 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *Func);
9519 if (FD &&
9520 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9521 // Add 1 to the index so that 0 can mean the mismatch didn't
9522 // involve a parameter
9523 unsigned ParamNum =
9524 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9525 NearMatches.push_back(Elt: std::make_pair(x&: FD, y&: ParamNum));
9526 }
9527 }
9528 // If the qualified name lookup yielded nothing, try typo correction
9529 } else if ((Correction = SemaRef.CorrectTypo(
9530 Typo: Prev.getLookupNameInfo(), LookupKind: Prev.getLookupKind(), S,
9531 SS: &ExtraArgs.D.getCXXScopeSpec(), CCC,
9532 Mode: CorrectTypoKind::ErrorRecovery,
9533 MemberContext: IsLocalFriend ? nullptr : NewDC))) {
9534 // Set up everything for the call to ActOnFunctionDeclarator
9535 ExtraArgs.D.SetIdentifier(Id: Correction.getCorrectionAsIdentifierInfo(),
9536 IdLoc: ExtraArgs.D.getIdentifierLoc());
9537 Previous.clear();
9538 Previous.setLookupName(Correction.getCorrection());
9539 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9540 CDeclEnd = Correction.end();
9541 CDecl != CDeclEnd; ++CDecl) {
9542 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9543 if (FD && !FD->hasBody() &&
9544 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9545 Previous.addDecl(D: FD);
9546 }
9547 }
9548 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9549
9550 NamedDecl *Result;
9551 // Retry building the function declaration with the new previous
9552 // declarations, and with errors suppressed.
9553 {
9554 // Trap errors.
9555 Sema::SFINAETrap Trap(SemaRef);
9556
9557 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9558 // pieces need to verify the typo-corrected C++ declaration and hopefully
9559 // eliminate the need for the parameter pack ExtraArgs.
9560 Result = SemaRef.ActOnFunctionDeclarator(
9561 S: ExtraArgs.S, D&: ExtraArgs.D,
9562 DC: Correction.getCorrectionDecl()->getDeclContext(),
9563 TInfo: NewFD->getTypeSourceInfo(), Previous, TemplateParamLists: ExtraArgs.TemplateParamLists,
9564 AddToScope&: ExtraArgs.AddToScope);
9565
9566 if (Trap.hasErrorOccurred())
9567 Result = nullptr;
9568 }
9569
9570 if (Result) {
9571 // Determine which correction we picked.
9572 Decl *Canonical = Result->getCanonicalDecl();
9573 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9574 I != E; ++I)
9575 if ((*I)->getCanonicalDecl() == Canonical)
9576 Correction.setCorrectionDecl(*I);
9577
9578 // Let Sema know about the correction.
9579 SemaRef.MarkTypoCorrectedFunctionDefinition(F: Result);
9580 SemaRef.diagnoseTypo(
9581 Correction,
9582 TypoDiag: SemaRef.PDiag(DiagID: IsLocalFriend
9583 ? diag::err_no_matching_local_friend_suggest
9584 : diag::err_member_decl_does_not_match_suggest)
9585 << Name << NewDC << IsDefinition);
9586 return Result;
9587 }
9588
9589 // Pretend the typo correction never occurred
9590 ExtraArgs.D.SetIdentifier(Id: Name.getAsIdentifierInfo(),
9591 IdLoc: ExtraArgs.D.getIdentifierLoc());
9592 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9593 Previous.clear();
9594 Previous.setLookupName(Name);
9595 }
9596
9597 SemaRef.Diag(Loc: NewFD->getLocation(), DiagID: DiagMsg)
9598 << Name << NewDC << IsDefinition << NewFD->getLocation();
9599
9600 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9601 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9602 CXXRecordDecl *RD = NewMD->getParent();
9603 SemaRef.Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here)
9604 << RD->getName() << RD->getLocation();
9605 }
9606
9607 bool NewFDisConst = NewMD && NewMD->isConst();
9608
9609 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9610 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9611 NearMatch != NearMatchEnd; ++NearMatch) {
9612 FunctionDecl *FD = NearMatch->first;
9613 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
9614 bool FDisConst = MD && MD->isConst();
9615 bool IsMember = MD || !IsLocalFriend;
9616
9617 // FIXME: These notes are poorly worded for the local friend case.
9618 if (unsigned Idx = NearMatch->second) {
9619 ParmVarDecl *FDParam = FD->getParamDecl(i: Idx-1);
9620 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9621 if (Loc.isInvalid()) Loc = FD->getLocation();
9622 SemaRef.Diag(Loc, DiagID: IsMember ? diag::note_member_def_close_param_match
9623 : diag::note_local_decl_close_param_match)
9624 << Idx << FDParam->getType()
9625 << NewFD->getParamDecl(i: Idx - 1)->getType();
9626 } else if (FDisConst != NewFDisConst) {
9627 auto DB = SemaRef.Diag(Loc: FD->getLocation(),
9628 DiagID: diag::note_member_def_close_const_match)
9629 << NewFDisConst << FD->getSourceRange().getEnd();
9630 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9631 DB << FixItHint::CreateInsertion(InsertionLoc: FTI.getRParenLoc().getLocWithOffset(Offset: 1),
9632 Code: " const");
9633 else if (FTI.hasMethodTypeQualifiers() &&
9634 FTI.getConstQualifierLoc().isValid())
9635 DB << FixItHint::CreateRemoval(RemoveRange: FTI.getConstQualifierLoc());
9636 } else {
9637 SemaRef.Diag(Loc: FD->getLocation(),
9638 DiagID: IsMember ? diag::note_member_def_close_match
9639 : diag::note_local_decl_close_match);
9640 }
9641 }
9642 return nullptr;
9643}
9644
9645static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9646 switch (D.getDeclSpec().getStorageClassSpec()) {
9647 default: llvm_unreachable("Unknown storage class!");
9648 case DeclSpec::SCS_auto:
9649 case DeclSpec::SCS_register:
9650 case DeclSpec::SCS_mutable:
9651 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9652 DiagID: diag::err_typecheck_sclass_func);
9653 D.getMutableDeclSpec().ClearStorageClassSpecs();
9654 D.setInvalidType();
9655 break;
9656 case DeclSpec::SCS_unspecified: break;
9657 case DeclSpec::SCS_extern:
9658 if (D.getDeclSpec().isExternInLinkageSpec())
9659 return SC_None;
9660 return SC_Extern;
9661 case DeclSpec::SCS_static: {
9662 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9663 // C99 6.7.1p5:
9664 // The declaration of an identifier for a function that has
9665 // block scope shall have no explicit storage-class specifier
9666 // other than extern
9667 // See also (C++ [dcl.stc]p4).
9668 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9669 DiagID: diag::err_static_block_func);
9670 break;
9671 } else
9672 return SC_Static;
9673 }
9674 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9675 }
9676
9677 // No explicit storage class has already been returned
9678 return SC_None;
9679}
9680
9681static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9682 DeclContext *DC, QualType &R,
9683 TypeSourceInfo *TInfo,
9684 StorageClass SC,
9685 bool &IsVirtualOkay) {
9686 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9687 DeclarationName Name = NameInfo.getName();
9688
9689 FunctionDecl *NewFD = nullptr;
9690 bool isInline = D.getDeclSpec().isInlineSpecified();
9691
9692 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9693 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9694 (SemaRef.getLangOpts().C23 &&
9695 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9696
9697 if (SemaRef.getLangOpts().C23)
9698 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9699 DiagID: diag::err_c23_constexpr_not_variable);
9700 else
9701 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9702 DiagID: diag::err_constexpr_wrong_decl_kind)
9703 << static_cast<int>(ConstexprKind);
9704 ConstexprKind = ConstexprSpecKind::Unspecified;
9705 D.getMutableDeclSpec().ClearConstexprSpec();
9706 }
9707
9708 if (!SemaRef.getLangOpts().CPlusPlus) {
9709 // Determine whether the function was written with a prototype. This is
9710 // true when:
9711 // - there is a prototype in the declarator, or
9712 // - the type R of the function is some kind of typedef or other non-
9713 // attributed reference to a type name (which eventually refers to a
9714 // function type). Note, we can't always look at the adjusted type to
9715 // check this case because attributes may cause a non-function
9716 // declarator to still have a function type. e.g.,
9717 // typedef void func(int a);
9718 // __attribute__((noreturn)) func other_func; // This has a prototype
9719 bool HasPrototype =
9720 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9721 (D.getDeclSpec().isTypeRep() &&
9722 SemaRef.GetTypeFromParser(Ty: D.getDeclSpec().getRepAsType(), TInfo: nullptr)
9723 ->isFunctionProtoType()) ||
9724 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9725 assert(
9726 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9727 "Strict prototypes are required");
9728
9729 NewFD = FunctionDecl::Create(
9730 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9731 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline, hasWrittenPrototype: HasPrototype,
9732 ConstexprKind: ConstexprSpecKind::Unspecified,
9733 /*TrailingRequiresClause=*/{});
9734 if (D.isInvalidType())
9735 NewFD->setInvalidDecl();
9736
9737 return NewFD;
9738 }
9739
9740 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9741 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9742
9743 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9744
9745 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9746 // This is a C++ constructor declaration.
9747 assert(DC->isRecord() &&
9748 "Constructors can only be declared in a member context");
9749
9750 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9751 return CXXConstructorDecl::Create(
9752 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9753 TInfo, ES: ExplicitSpecifier, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(),
9754 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9755 Inherited: InheritedConstructor(), TrailingRequiresClause);
9756
9757 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9758 // This is a C++ destructor declaration.
9759 if (DC->isRecord()) {
9760 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9761 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC);
9762 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9763 C&: SemaRef.Context, RD: Record, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo,
9764 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9765 /*isImplicitlyDeclared=*/false, ConstexprKind,
9766 TrailingRequiresClause);
9767 // User defined destructors start as not selected if the class definition is still
9768 // not done.
9769 if (Record->isBeingDefined())
9770 NewDD->setIneligibleOrNotSelected(true);
9771
9772 // If the destructor needs an implicit exception specification, set it
9773 // now. FIXME: It'd be nice to be able to create the right type to start
9774 // with, but the type needs to reference the destructor declaration.
9775 if (SemaRef.getLangOpts().CPlusPlus11)
9776 SemaRef.AdjustDestructorExceptionSpec(Destructor: NewDD);
9777
9778 IsVirtualOkay = true;
9779 return NewDD;
9780
9781 } else {
9782 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_not_member);
9783 D.setInvalidType();
9784
9785 // Create a FunctionDecl to satisfy the function definition parsing
9786 // code path.
9787 return FunctionDecl::Create(
9788 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NLoc: D.getIdentifierLoc(), N: Name, T: R,
9789 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9790 /*hasPrototype=*/hasWrittenPrototype: true, ConstexprKind, TrailingRequiresClause);
9791 }
9792
9793 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9794 if (!DC->isRecord()) {
9795 SemaRef.Diag(Loc: D.getIdentifierLoc(),
9796 DiagID: diag::err_conv_function_not_member);
9797 return nullptr;
9798 }
9799
9800 SemaRef.CheckConversionDeclarator(D, R, SC);
9801 if (D.isInvalidType())
9802 return nullptr;
9803
9804 IsVirtualOkay = true;
9805 return CXXConversionDecl::Create(
9806 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9807 TInfo, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9808 ES: ExplicitSpecifier, ConstexprKind, EndLocation: SourceLocation(),
9809 TrailingRequiresClause);
9810
9811 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9812 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9813 return nullptr;
9814 return CXXDeductionGuideDecl::Create(
9815 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), ES: ExplicitSpecifier, NameInfo, T: R,
9816 TInfo, EndLocation: D.getEndLoc(), /*Ctor=*/nullptr,
9817 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9818 } else if (DC->isRecord()) {
9819 // If the name of the function is the same as the name of the record,
9820 // then this must be an invalid constructor that has a return type.
9821 // (The parser checks for a return type and makes the declarator a
9822 // constructor if it has no return type).
9823 if (Name.getAsIdentifierInfo() &&
9824 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(Val: DC)->getIdentifier()){
9825 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_return_type)
9826 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9827 << SourceRange(D.getIdentifierLoc());
9828 return nullptr;
9829 }
9830
9831 // This is a C++ method declaration.
9832 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9833 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9834 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9835 ConstexprKind, EndLocation: SourceLocation(), TrailingRequiresClause);
9836 IsVirtualOkay = !Ret->isStatic();
9837 return Ret;
9838 } else {
9839 bool isFriend =
9840 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9841 if (!isFriend && SemaRef.CurContext->isRecord())
9842 return nullptr;
9843
9844 // Determine whether the function was written with a
9845 // prototype. This true when:
9846 // - we're in C++ (where every function has a prototype),
9847 return FunctionDecl::Create(
9848 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9849 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9850 hasWrittenPrototype: true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9851 }
9852}
9853
9854enum OpenCLParamType {
9855 ValidKernelParam,
9856 PtrPtrKernelParam,
9857 PtrKernelParam,
9858 InvalidAddrSpacePtrKernelParam,
9859 InvalidKernelParam,
9860 RecordKernelParam
9861};
9862
9863static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9864 // Size dependent types are just typedefs to normal integer types
9865 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9866 // integers other than by their names.
9867 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9868
9869 // Remove typedefs one by one until we reach a typedef
9870 // for a size dependent type.
9871 QualType DesugaredTy = Ty;
9872 do {
9873 ArrayRef<StringRef> Names(SizeTypeNames);
9874 auto Match = llvm::find(Range&: Names, Val: DesugaredTy.getUnqualifiedType().getAsString());
9875 if (Names.end() != Match)
9876 return true;
9877
9878 Ty = DesugaredTy;
9879 DesugaredTy = Ty.getSingleStepDesugaredType(Context: C);
9880 } while (DesugaredTy != Ty);
9881
9882 return false;
9883}
9884
9885static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9886 if (PT->isDependentType())
9887 return InvalidKernelParam;
9888
9889 if (PT->isPointerOrReferenceType()) {
9890 QualType PointeeType = PT->getPointeeType();
9891 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9892 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9893 PointeeType.getAddressSpace() == LangAS::Default)
9894 return InvalidAddrSpacePtrKernelParam;
9895
9896 if (PointeeType->isPointerType()) {
9897 // This is a pointer to pointer parameter.
9898 // Recursively check inner type.
9899 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PT: PointeeType);
9900 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9901 ParamKind == InvalidKernelParam)
9902 return ParamKind;
9903
9904 // OpenCL v3.0 s6.11.a:
9905 // A restriction to pass pointers to pointers only applies to OpenCL C
9906 // v1.2 or below.
9907 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9908 return ValidKernelParam;
9909
9910 return PtrPtrKernelParam;
9911 }
9912
9913 // C++ for OpenCL v1.0 s2.4:
9914 // Moreover the types used in parameters of the kernel functions must be:
9915 // Standard layout types for pointer parameters. The same applies to
9916 // reference if an implementation supports them in kernel parameters.
9917 if (S.getLangOpts().OpenCLCPlusPlus &&
9918 !S.getOpenCLOptions().isAvailableOption(
9919 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts())) {
9920 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9921 bool IsStandardLayoutType = true;
9922 if (CXXRec) {
9923 // If template type is not ODR-used its definition is only available
9924 // in the template definition not its instantiation.
9925 // FIXME: This logic doesn't work for types that depend on template
9926 // parameter (PR58590).
9927 if (!CXXRec->hasDefinition())
9928 CXXRec = CXXRec->getTemplateInstantiationPattern();
9929 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9930 IsStandardLayoutType = false;
9931 }
9932 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9933 !IsStandardLayoutType)
9934 return InvalidKernelParam;
9935 }
9936
9937 // OpenCL v1.2 s6.9.p:
9938 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9939 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9940 return ValidKernelParam;
9941
9942 return PtrKernelParam;
9943 }
9944
9945 // OpenCL v1.2 s6.9.k:
9946 // Arguments to kernel functions in a program cannot be declared with the
9947 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9948 // uintptr_t or a struct and/or union that contain fields declared to be one
9949 // of these built-in scalar types.
9950 if (isOpenCLSizeDependentType(C&: S.getASTContext(), Ty: PT))
9951 return InvalidKernelParam;
9952
9953 if (PT->isImageType())
9954 return PtrKernelParam;
9955
9956 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9957 return InvalidKernelParam;
9958
9959 // OpenCL extension spec v1.2 s9.5:
9960 // This extension adds support for half scalar and vector types as built-in
9961 // types that can be used for arithmetic operations, conversions etc.
9962 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: S.getLangOpts()) &&
9963 PT->isHalfType())
9964 return InvalidKernelParam;
9965
9966 // Look into an array argument to check if it has a forbidden type.
9967 if (PT->isArrayType()) {
9968 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9969 // Call ourself to check an underlying type of an array. Since the
9970 // getPointeeOrArrayElementType returns an innermost type which is not an
9971 // array, this recursive call only happens once.
9972 return getOpenCLKernelParameterType(S, PT: QualType(UnderlyingTy, 0));
9973 }
9974
9975 // C++ for OpenCL v1.0 s2.4:
9976 // Moreover the types used in parameters of the kernel functions must be:
9977 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9978 // types) for parameters passed by value;
9979 if (S.getLangOpts().OpenCLCPlusPlus &&
9980 !S.getOpenCLOptions().isAvailableOption(
9981 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts()) &&
9982 !PT->isOpenCLSpecificType() && !PT.isPODType(Context: S.Context))
9983 return InvalidKernelParam;
9984
9985 if (PT->isRecordType())
9986 return RecordKernelParam;
9987
9988 return ValidKernelParam;
9989}
9990
9991static void checkIsValidOpenCLKernelParameter(
9992 Sema &S,
9993 Declarator &D,
9994 ParmVarDecl *Param,
9995 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9996 QualType PT = Param->getType();
9997
9998 // Cache the valid types we encounter to avoid rechecking structs that are
9999 // used again
10000 if (ValidTypes.count(Ptr: PT.getTypePtr()))
10001 return;
10002
10003 switch (getOpenCLKernelParameterType(S, PT)) {
10004 case PtrPtrKernelParam:
10005 // OpenCL v3.0 s6.11.a:
10006 // A kernel function argument cannot be declared as a pointer to a pointer
10007 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
10008 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_opencl_ptrptr_kernel_param);
10009 D.setInvalidType();
10010 return;
10011
10012 case InvalidAddrSpacePtrKernelParam:
10013 // OpenCL v1.0 s6.5:
10014 // __kernel function arguments declared to be a pointer of a type can point
10015 // to one of the following address spaces only : __global, __local or
10016 // __constant.
10017 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_kernel_arg_address_space);
10018 D.setInvalidType();
10019 return;
10020
10021 // OpenCL v1.2 s6.9.k:
10022 // Arguments to kernel functions in a program cannot be declared with the
10023 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
10024 // uintptr_t or a struct and/or union that contain fields declared to be
10025 // one of these built-in scalar types.
10026
10027 case InvalidKernelParam:
10028 // OpenCL v1.2 s6.8 n:
10029 // A kernel function argument cannot be declared
10030 // of event_t type.
10031 // Do not diagnose half type since it is diagnosed as invalid argument
10032 // type for any function elsewhere.
10033 if (!PT->isHalfType()) {
10034 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
10035
10036 // Explain what typedefs are involved.
10037 const TypedefType *Typedef = nullptr;
10038 while ((Typedef = PT->getAs<TypedefType>())) {
10039 SourceLocation Loc = Typedef->getDecl()->getLocation();
10040 // SourceLocation may be invalid for a built-in type.
10041 if (Loc.isValid())
10042 S.Diag(Loc, DiagID: diag::note_entity_declared_at) << PT;
10043 PT = Typedef->desugar();
10044 }
10045 }
10046
10047 D.setInvalidType();
10048 return;
10049
10050 case PtrKernelParam:
10051 case ValidKernelParam:
10052 ValidTypes.insert(Ptr: PT.getTypePtr());
10053 return;
10054
10055 case RecordKernelParam:
10056 break;
10057 }
10058
10059 // Track nested structs we will inspect
10060 SmallVector<const Decl *, 4> VisitStack;
10061
10062 // Track where we are in the nested structs. Items will migrate from
10063 // VisitStack to HistoryStack as we do the DFS for bad field.
10064 SmallVector<const FieldDecl *, 4> HistoryStack;
10065 HistoryStack.push_back(Elt: nullptr);
10066
10067 // At this point we already handled everything except of a RecordType.
10068 assert(PT->isRecordType() && "Unexpected type.");
10069 const auto *PD = PT->castAsRecordDecl();
10070 VisitStack.push_back(Elt: PD);
10071 assert(VisitStack.back() && "First decl null?");
10072
10073 do {
10074 const Decl *Next = VisitStack.pop_back_val();
10075 if (!Next) {
10076 assert(!HistoryStack.empty());
10077 // Found a marker, we have gone up a level
10078 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
10079 ValidTypes.insert(Ptr: Hist->getType().getTypePtr());
10080
10081 continue;
10082 }
10083
10084 // Adds everything except the original parameter declaration (which is not a
10085 // field itself) to the history stack.
10086 const RecordDecl *RD;
10087 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: Next)) {
10088 HistoryStack.push_back(Elt: Field);
10089
10090 QualType FieldTy = Field->getType();
10091 // Other field types (known to be valid or invalid) are handled while we
10092 // walk around RecordDecl::fields().
10093 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
10094 "Unexpected type.");
10095 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
10096
10097 RD = FieldRecTy->castAsRecordDecl();
10098 } else {
10099 RD = cast<RecordDecl>(Val: Next);
10100 }
10101
10102 // Add a null marker so we know when we've gone back up a level
10103 VisitStack.push_back(Elt: nullptr);
10104
10105 for (const auto *FD : RD->fields()) {
10106 QualType QT = FD->getType();
10107
10108 if (ValidTypes.count(Ptr: QT.getTypePtr()))
10109 continue;
10110
10111 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, PT: QT);
10112 if (ParamType == ValidKernelParam)
10113 continue;
10114
10115 if (ParamType == RecordKernelParam) {
10116 VisitStack.push_back(Elt: FD);
10117 continue;
10118 }
10119
10120 // OpenCL v1.2 s6.9.p:
10121 // Arguments to kernel functions that are declared to be a struct or union
10122 // do not allow OpenCL objects to be passed as elements of the struct or
10123 // union. This restriction was lifted in OpenCL v2.0 with the introduction
10124 // of SVM.
10125 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
10126 ParamType == InvalidAddrSpacePtrKernelParam) {
10127 S.Diag(Loc: Param->getLocation(),
10128 DiagID: diag::err_record_with_pointers_kernel_param)
10129 << PT->isUnionType()
10130 << PT;
10131 } else {
10132 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
10133 }
10134
10135 S.Diag(Loc: PD->getLocation(), DiagID: diag::note_within_field_of_type)
10136 << PD->getDeclName();
10137
10138 // We have an error, now let's go back up through history and show where
10139 // the offending field came from
10140 for (ArrayRef<const FieldDecl *>::const_iterator
10141 I = HistoryStack.begin() + 1,
10142 E = HistoryStack.end();
10143 I != E; ++I) {
10144 const FieldDecl *OuterField = *I;
10145 S.Diag(Loc: OuterField->getLocation(), DiagID: diag::note_within_field_of_type)
10146 << OuterField->getType();
10147 }
10148
10149 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_illegal_field_declared_here)
10150 << QT->isPointerType()
10151 << QT;
10152 D.setInvalidType();
10153 return;
10154 }
10155 } while (!VisitStack.empty());
10156}
10157
10158/// Find the DeclContext in which a tag is implicitly declared if we see an
10159/// elaborated type specifier in the specified context, and lookup finds
10160/// nothing.
10161static DeclContext *getTagInjectionContext(DeclContext *DC) {
10162 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10163 DC = DC->getParent();
10164 return DC;
10165}
10166
10167/// Find the Scope in which a tag is implicitly declared if we see an
10168/// elaborated type specifier in the specified context, and lookup finds
10169/// nothing.
10170static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10171 while (S->isClassScope() ||
10172 (LangOpts.CPlusPlus &&
10173 S->isFunctionPrototypeScope()) ||
10174 ((S->getFlags() & Scope::DeclScope) == 0) ||
10175 (S->getEntity() && S->getEntity()->isTransparentContext()))
10176 S = S->getParent();
10177 return S;
10178}
10179
10180/// Determine whether a declaration matches a known function in namespace std.
10181static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
10182 unsigned BuiltinID) {
10183 switch (BuiltinID) {
10184 case Builtin::BI__GetExceptionInfo:
10185 // No type checking whatsoever.
10186 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10187
10188 case Builtin::BIaddressof:
10189 case Builtin::BI__addressof:
10190 case Builtin::BIforward:
10191 case Builtin::BIforward_like:
10192 case Builtin::BImove:
10193 case Builtin::BImove_if_noexcept:
10194 case Builtin::BIas_const: {
10195 // Ensure that we don't treat the algorithm
10196 // OutputIt std::move(InputIt, InputIt, OutputIt)
10197 // as the builtin std::move.
10198 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10199 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10200 }
10201
10202 default:
10203 return false;
10204 }
10205}
10206
10207void Sema::addImplicitCallingConvAbiTag(FunctionDecl *FD) {
10208 const auto *FT = FD->getType()->getAs<FunctionType>();
10209 if (!FT)
10210 return;
10211
10212 StringRef Tag;
10213 switch (FT->getCallConv()) {
10214#define CC_VLS_CASE(ABI_VLEN) \
10215 case CC_RISCVVLSCall_##ABI_VLEN: \
10216 Tag = "riscv_vls_cc_" #ABI_VLEN; \
10217 break;
10218 CC_VLS_CASE(32)
10219 CC_VLS_CASE(64)
10220 CC_VLS_CASE(128)
10221 CC_VLS_CASE(256)
10222 CC_VLS_CASE(512)
10223 CC_VLS_CASE(1024)
10224 CC_VLS_CASE(2048)
10225 CC_VLS_CASE(4096)
10226 CC_VLS_CASE(8192)
10227 CC_VLS_CASE(16384)
10228 CC_VLS_CASE(32768)
10229 CC_VLS_CASE(65536)
10230#undef CC_VLS_CASE
10231 default:
10232 return;
10233 }
10234
10235 SmallVector<AbiTagAttr *, 2> Existing(FD->specific_attrs<AbiTagAttr>());
10236 AbiTagAttr *Old = Existing.empty() ? nullptr : Existing.front();
10237
10238 SmallVector<StringRef, 4> Tags;
10239 if (Old)
10240 llvm::append_range(C&: Tags, R: Old->tags());
10241 if (llvm::is_contained(Range&: Tags, Element: Tag))
10242 return;
10243 Tags.push_back(Elt: Tag);
10244
10245 AbiTagAttr *Merged =
10246 Old ? AbiTagAttr::Create(Ctx&: Context, Tags: Tags.data(), TagsSize: Tags.size(), CommonInfo: *Old)
10247 : AbiTagAttr::CreateImplicit(Ctx&: Context, Tags: Tags.data(), TagsSize: Tags.size(),
10248 Range: FD->getLocation());
10249 FD->dropAttr<AbiTagAttr>();
10250 FD->addAttr(A: Merged);
10251 for (size_t I = 1, E = Existing.size(); I < E; ++I)
10252 FD->addAttr(A: Existing[I]);
10253}
10254
10255NamedDecl*
10256Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
10257 TypeSourceInfo *TInfo, LookupResult &Previous,
10258 MultiTemplateParamsArg TemplateParamListsRef,
10259 bool &AddToScope) {
10260 QualType R = TInfo->getType();
10261
10262 assert(R->isFunctionType());
10263 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10264 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_decl_cmse_ns_call);
10265
10266 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10267 llvm::append_range(C&: TemplateParamLists, R&: TemplateParamListsRef);
10268 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
10269 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10270 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10271 TemplateParamLists.back() = Invented;
10272 else
10273 TemplateParamLists.push_back(Elt: Invented);
10274 }
10275
10276 // TODO: consider using NameInfo for diagnostic.
10277 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10278 DeclarationName Name = NameInfo.getName();
10279 StorageClass SC = getFunctionStorageClass(SemaRef&: *this, D);
10280
10281 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
10282 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
10283 DiagID: diag::err_invalid_thread)
10284 << DeclSpec::getSpecifierName(S: TSCS);
10285
10286 if (D.isFirstDeclarationOfMember())
10287 adjustMemberFunctionCC(
10288 T&: R, HasThisPointer: !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
10289 IsCtorOrDtor: D.isCtorOrDtor(), Loc: D.getIdentifierLoc());
10290
10291 bool isFriend = false;
10292 FunctionTemplateDecl *FunctionTemplate = nullptr;
10293 bool isMemberSpecialization = false;
10294 bool isFunctionTemplateSpecialization = false;
10295
10296 bool HasExplicitTemplateArgs = false;
10297 TemplateArgumentListInfo TemplateArgs;
10298
10299 bool isVirtualOkay = false;
10300
10301 DeclContext *OriginalDC = DC;
10302 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10303
10304 FunctionDecl *NewFD = CreateNewFunctionDecl(SemaRef&: *this, D, DC, R, TInfo, SC,
10305 IsVirtualOkay&: isVirtualOkay);
10306 if (!NewFD) return nullptr;
10307
10308 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10309 NewFD->setTopLevelDeclInObjCContainer();
10310
10311 // Set the lexical context. If this is a function-scope declaration, or has a
10312 // C++ scope specifier, or is the object of a friend declaration, the lexical
10313 // context will be different from the semantic context.
10314 NewFD->setLexicalDeclContext(CurContext);
10315
10316 if (IsLocalExternDecl)
10317 NewFD->setLocalExternDecl();
10318
10319 if (getLangOpts().CPlusPlus) {
10320 // The rules for implicit inlines changed in C++20 for methods and friends
10321 // with an in-class definition (when such a definition is not attached to
10322 // the global module). This does not affect declarations that are already
10323 // inline (whether explicitly or implicitly by being declared constexpr,
10324 // consteval, etc).
10325 // FIXME: We need a better way to separate C++ standard and clang modules.
10326 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10327 !NewFD->getOwningModule() ||
10328 NewFD->isFromGlobalModule() ||
10329 NewFD->getOwningModule()->isHeaderLikeModule();
10330 bool isInline = D.getDeclSpec().isInlineSpecified();
10331 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10332 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10333 isFriend = D.getDeclSpec().isFriendSpecified();
10334 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10335 // Pre-C++20 [class.friend]p5
10336 // A function can be defined in a friend declaration of a
10337 // class . . . . Such a function is implicitly inline.
10338 // Post C++20 [class.friend]p7
10339 // Such a function is implicitly an inline function if it is attached
10340 // to the global module.
10341 NewFD->setImplicitlyInline();
10342 }
10343
10344 // If this is a method defined in an __interface, and is not a constructor
10345 // or an overloaded operator, then set the pure flag (isVirtual will already
10346 // return true).
10347 if (const CXXRecordDecl *Parent =
10348 dyn_cast<CXXRecordDecl>(Val: NewFD->getDeclContext())) {
10349 if (Parent->isInterface() && cast<CXXMethodDecl>(Val: NewFD)->isUserProvided())
10350 NewFD->setIsPureVirtual(true);
10351
10352 // C++ [class.union]p2
10353 // A union can have member functions, but not virtual functions.
10354 if (isVirtual && Parent->isUnion()) {
10355 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_virtual_in_union);
10356 NewFD->setInvalidDecl();
10357 }
10358 if ((Parent->isClass() || Parent->isStruct()) &&
10359 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10360 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10361 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10362 if (auto *Def = Parent->getDefinition())
10363 Def->setInitMethod(true);
10364 }
10365 }
10366
10367 SetNestedNameSpecifier(S&: *this, DD: NewFD, D);
10368 isMemberSpecialization = false;
10369 isFunctionTemplateSpecialization = false;
10370 if (D.isInvalidType())
10371 NewFD->setInvalidDecl();
10372
10373 // Match up the template parameter lists with the scope specifier, then
10374 // determine whether we have a template or a template specialization.
10375 bool Invalid = false;
10376 TemplateIdAnnotation *TemplateId =
10377 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
10378 ? D.getName().TemplateId
10379 : nullptr;
10380 TemplateParameterList *TemplateParams =
10381 MatchTemplateParametersToScopeSpecifier(
10382 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
10383 SS: D.getCXXScopeSpec(), TemplateId, ParamLists: TemplateParamLists, IsFriend: isFriend,
10384 IsMemberSpecialization&: isMemberSpecialization, Invalid);
10385 if (TemplateParams) {
10386 // Check that we can declare a template here.
10387 if (CheckTemplateDeclScope(S, TemplateParams))
10388 NewFD->setInvalidDecl();
10389
10390 if (TemplateParams->size() > 0) {
10391 // This is a function template
10392
10393 // A destructor cannot be a template.
10394 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
10395 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_template);
10396 NewFD->setInvalidDecl();
10397 // Function template with explicit template arguments.
10398 } else if (TemplateId) {
10399 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_template_partial_spec)
10400 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10401 NewFD->setInvalidDecl();
10402 }
10403
10404 // If we're adding a template to a dependent context, we may need to
10405 // rebuilding some of the types used within the template parameter list,
10406 // now that we know what the current instantiation is.
10407 if (DC->isDependentContext()) {
10408 ContextRAII SavedContext(*this, DC);
10409 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
10410 Invalid = true;
10411 }
10412
10413 FunctionTemplate = FunctionTemplateDecl::Create(C&: Context, DC,
10414 L: NewFD->getLocation(),
10415 Name, Params: TemplateParams,
10416 Decl: NewFD);
10417 FunctionTemplate->setLexicalDeclContext(CurContext);
10418 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
10419
10420 // For source fidelity, store the other template param lists.
10421 if (TemplateParamLists.size() > 1) {
10422 NewFD->setTemplateParameterListsInfo(Context,
10423 TPLists: ArrayRef<TemplateParameterList *>(TemplateParamLists)
10424 .drop_back(N: 1));
10425 }
10426 } else {
10427 // This is a function template specialization.
10428 isFunctionTemplateSpecialization = true;
10429 // For source fidelity, store all the template param lists.
10430 if (TemplateParamLists.size() > 0)
10431 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10432
10433 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10434 if (isFriend) {
10435 // We want to remove the "template<>", found here.
10436 SourceRange RemoveRange = TemplateParams->getSourceRange();
10437
10438 // If we remove the template<> and the name is not a
10439 // template-id, we're actually silently creating a problem:
10440 // the friend declaration will refer to an untemplated decl,
10441 // and clearly the user wants a template specialization. So
10442 // we need to insert '<>' after the name.
10443 SourceLocation InsertLoc;
10444 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10445 InsertLoc = D.getName().getSourceRange().getEnd();
10446 InsertLoc = getLocForEndOfToken(Loc: InsertLoc);
10447 }
10448
10449 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_spec_decl_friend)
10450 << Name << RemoveRange
10451 << FixItHint::CreateRemoval(RemoveRange)
10452 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: "<>");
10453 Invalid = true;
10454
10455 // Recover by faking up an empty template argument list.
10456 HasExplicitTemplateArgs = true;
10457 TemplateArgs.setLAngleLoc(InsertLoc);
10458 TemplateArgs.setRAngleLoc(InsertLoc);
10459 }
10460 }
10461 } else {
10462 // Check that we can declare a template here.
10463 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10464 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
10465 NewFD->setInvalidDecl();
10466
10467 // All template param lists were matched against the scope specifier:
10468 // this is NOT (an explicit specialization of) a template.
10469 if (TemplateParamLists.size() > 0)
10470 // For source fidelity, store all the template param lists.
10471 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10472
10473 // "friend void foo<>(int);" is an implicit specialization decl.
10474 if (isFriend && TemplateId)
10475 isFunctionTemplateSpecialization = true;
10476 }
10477
10478 // If this is a function template specialization and the unqualified-id of
10479 // the declarator-id is a template-id, convert the template argument list
10480 // into our AST format and check for unexpanded packs.
10481 if (isFunctionTemplateSpecialization && TemplateId) {
10482 HasExplicitTemplateArgs = true;
10483
10484 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10485 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10486 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10487 TemplateId->NumArgs);
10488 translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgs);
10489
10490 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10491 // declaration of a function template partial specialization? Should we
10492 // consider the unexpanded pack context to be a partial specialization?
10493 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10494 if (DiagnoseUnexpandedParameterPack(
10495 Arg: ArgLoc, UPPC: isFriend ? UPPC_FriendDeclaration
10496 : UPPC_ExplicitSpecialization))
10497 NewFD->setInvalidDecl();
10498 }
10499 }
10500
10501 if (Invalid) {
10502 NewFD->setInvalidDecl();
10503 if (FunctionTemplate)
10504 FunctionTemplate->setInvalidDecl();
10505 }
10506
10507 // C++ [dcl.fct.spec]p5:
10508 // The virtual specifier shall only be used in declarations of
10509 // nonstatic class member functions that appear within a
10510 // member-specification of a class declaration; see 10.3.
10511 //
10512 if (isVirtual && !NewFD->isInvalidDecl()) {
10513 if (!isVirtualOkay) {
10514 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10515 DiagID: diag::err_virtual_non_function);
10516 } else if (!CurContext->isRecord()) {
10517 // 'virtual' was specified outside of the class.
10518 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10519 DiagID: diag::err_virtual_out_of_class)
10520 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10521 } else if (NewFD->getDescribedFunctionTemplate()) {
10522 // C++ [temp.mem]p3:
10523 // A member function template shall not be virtual.
10524 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10525 DiagID: diag::err_virtual_member_function_template)
10526 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10527 } else {
10528 // Okay: Add virtual to the method.
10529 NewFD->setVirtualAsWritten(true);
10530 }
10531
10532 if (getLangOpts().CPlusPlus14 &&
10533 NewFD->getReturnType()->isUndeducedType())
10534 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_auto_fn_virtual);
10535 }
10536
10537 // C++ [dcl.fct.spec]p3:
10538 // The inline specifier shall not appear on a block scope function
10539 // declaration.
10540 if (isInline && !NewFD->isInvalidDecl()) {
10541 if (CurContext->isFunctionOrMethod()) {
10542 // 'inline' is not allowed on block scope function declaration.
10543 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10544 DiagID: diag::err_inline_declaration_block_scope) << Name
10545 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10546 }
10547 }
10548
10549 // C++ [dcl.fct.spec]p6:
10550 // The explicit specifier shall be used only in the declaration of a
10551 // constructor or conversion function within its class definition;
10552 // see 12.3.1 and 12.3.2.
10553 if (hasExplicit && !NewFD->isInvalidDecl() &&
10554 !isa<CXXDeductionGuideDecl>(Val: NewFD)) {
10555 if (!CurContext->isRecord()) {
10556 // 'explicit' was specified outside of the class.
10557 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10558 DiagID: diag::err_explicit_out_of_class)
10559 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10560 } else if (!isa<CXXConstructorDecl>(Val: NewFD) &&
10561 !isa<CXXConversionDecl>(Val: NewFD)) {
10562 // 'explicit' was specified on a function that wasn't a constructor
10563 // or conversion function.
10564 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10565 DiagID: diag::err_explicit_non_ctor_or_conv_function)
10566 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10567 }
10568 }
10569
10570 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10571 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10572 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10573 // are implicitly inline.
10574 NewFD->setImplicitlyInline();
10575
10576 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10577 // be either constructors or to return a literal type. Therefore,
10578 // destructors cannot be declared constexpr.
10579 if (isa<CXXDestructorDecl>(Val: NewFD) &&
10580 (!getLangOpts().CPlusPlus20 ||
10581 ConstexprKind == ConstexprSpecKind::Consteval)) {
10582 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_constexpr_dtor)
10583 << static_cast<int>(ConstexprKind);
10584 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10585 ? ConstexprSpecKind::Unspecified
10586 : ConstexprSpecKind::Constexpr);
10587 }
10588 // C++20 [dcl.constexpr]p2: An allocation function, or a
10589 // deallocation function shall not be declared with the consteval
10590 // specifier.
10591 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10592 NewFD->getDeclName().isAnyOperatorNewOrDelete()) {
10593 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10594 DiagID: diag::err_invalid_consteval_decl_kind)
10595 << NewFD;
10596 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10597 }
10598 }
10599
10600 // If __module_private__ was specified, mark the function accordingly.
10601 if (D.getDeclSpec().isModulePrivateSpecified()) {
10602 if (isFunctionTemplateSpecialization) {
10603 SourceLocation ModulePrivateLoc
10604 = D.getDeclSpec().getModulePrivateSpecLoc();
10605 Diag(Loc: ModulePrivateLoc, DiagID: diag::err_module_private_specialization)
10606 << 0
10607 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
10608 } else {
10609 NewFD->setModulePrivate();
10610 if (FunctionTemplate)
10611 FunctionTemplate->setModulePrivate();
10612 }
10613 }
10614
10615 if (isFriend) {
10616 if (FunctionTemplate) {
10617 FunctionTemplate->setObjectOfFriendDecl();
10618 FunctionTemplate->setAccess(AS_public);
10619 }
10620 NewFD->setObjectOfFriendDecl();
10621 NewFD->setAccess(AS_public);
10622 }
10623
10624 // If a function is defined as defaulted or deleted, mark it as such now.
10625 // We'll do the relevant checks on defaulted / deleted functions later.
10626 switch (D.getFunctionDefinitionKind()) {
10627 case FunctionDefinitionKind::Declaration:
10628 case FunctionDefinitionKind::Definition:
10629 break;
10630
10631 case FunctionDefinitionKind::Defaulted:
10632 NewFD->setDefaulted();
10633 break;
10634
10635 case FunctionDefinitionKind::Deleted:
10636 NewFD->setDeletedAsWritten();
10637 break;
10638 }
10639
10640 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(Val: NewFD) && DC == CurContext &&
10641 D.isFunctionDefinition()) {
10642 // Pre C++20 [class.mfct]p2:
10643 // A member function may be defined (8.4) in its class definition, in
10644 // which case it is an inline member function (7.1.2)
10645 // Post C++20 [class.mfct]p1:
10646 // If a member function is attached to the global module and is defined
10647 // in its class definition, it is inline.
10648 NewFD->setImplicitlyInline();
10649 }
10650
10651 if (!isFriend && SC != SC_None) {
10652 // C++ [temp.expl.spec]p2:
10653 // The declaration in an explicit-specialization shall not be an
10654 // export-declaration. An explicit specialization shall not use a
10655 // storage-class-specifier other than thread_local.
10656 //
10657 // We diagnose friend declarations with storage-class-specifiers
10658 // elsewhere.
10659 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10660 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10661 DiagID: diag::ext_explicit_specialization_storage_class)
10662 << FixItHint::CreateRemoval(
10663 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10664 }
10665
10666 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10667 assert(isa<CXXMethodDecl>(NewFD) &&
10668 "Out-of-line member function should be a CXXMethodDecl");
10669 // C++ [class.static]p1:
10670 // A data or function member of a class may be declared static
10671 // in a class definition, in which case it is a static member of
10672 // the class.
10673
10674 // Complain about the 'static' specifier if it's on an out-of-line
10675 // member function definition.
10676
10677 // MSVC permits the use of a 'static' storage specifier on an
10678 // out-of-line member function template declaration and class member
10679 // template declaration (MSVC versions before 2015), warn about this.
10680 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10681 DiagID: ((!getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
10682 cast<CXXRecordDecl>(Val: DC)->getDescribedClassTemplate()) ||
10683 (getLangOpts().MSVCCompat &&
10684 NewFD->getDescribedFunctionTemplate()))
10685 ? diag::ext_static_out_of_line
10686 : diag::err_static_out_of_line)
10687 << FixItHint::CreateRemoval(
10688 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10689 }
10690 }
10691
10692 // C++11 [except.spec]p15:
10693 // A deallocation function with no exception-specification is treated
10694 // as if it were specified with noexcept(true).
10695 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10696 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10697 !FPT->hasExceptionSpec())
10698 NewFD->setType(Context.getFunctionType(
10699 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
10700 EPI: FPT->getExtProtoInfo().withExceptionSpec(ESI: EST_BasicNoexcept)));
10701
10702 // C++20 [dcl.inline]/7
10703 // If an inline function or variable that is attached to a named module
10704 // is declared in a definition domain, it shall be defined in that
10705 // domain.
10706 // So, if the current declaration does not have a definition, we must
10707 // check at the end of the TU (or when the PMF starts) to see that we
10708 // have a definition at that point.
10709 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10710 NewFD->isInNamedModule()) {
10711 PendingInlineFuncDecls.insert(Ptr: NewFD);
10712 }
10713 }
10714
10715 // Filter out previous declarations that don't match the scope.
10716 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(FD: NewFD),
10717 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
10718 isMemberSpecialization ||
10719 isFunctionTemplateSpecialization);
10720
10721 LoadExternalExtnameUndeclaredIdentifiers();
10722
10723 // Handle GNU asm-label extension (encoded as an attribute).
10724 if (Expr *E = D.getAsmLabel()) {
10725 // The parser guarantees this is a string.
10726 StringLiteral *SE = cast<StringLiteral>(Val: E);
10727 NewFD->addAttr(
10728 A: AsmLabelAttr::Create(Ctx&: Context, Label: SE->getString(), Range: SE->getStrTokenLoc(TokNum: 0)));
10729 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10730 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
10731 ExtnameUndeclaredIdentifiers.find(Key: NewFD->getIdentifier());
10732 if (I != ExtnameUndeclaredIdentifiers.end()) {
10733 if (isDeclExternC(D: NewFD)) {
10734 NewFD->addAttr(A: I->second);
10735 ExtnameUndeclaredIdentifiers.erase(Iterator: I);
10736 } else if (NewFD->getDeclContext()
10737 ->getRedeclContext()
10738 ->isTranslationUnit())
10739 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
10740 << /*Variable*/0 << NewFD;
10741 }
10742 }
10743
10744 // Copy the parameter declarations from the declarator D to the function
10745 // declaration NewFD, if they are available. First scavenge them into Params.
10746 SmallVector<ParmVarDecl*, 16> Params;
10747 unsigned FTIIdx;
10748 if (D.isFunctionDeclarator(idx&: FTIIdx)) {
10749 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(i: FTIIdx).Fun;
10750
10751 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10752 // function that takes no arguments, not a function that takes a
10753 // single void argument.
10754 // We let through "const void" here because Sema::GetTypeForDeclarator
10755 // already checks for that case.
10756 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10757 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10758 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
10759 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10760 Param->setDeclContext(NewFD);
10761 Params.push_back(Elt: Param);
10762
10763 if (Param->isInvalidDecl())
10764 NewFD->setInvalidDecl();
10765 }
10766 }
10767
10768 if (!getLangOpts().CPlusPlus) {
10769 // In C, find all the tag declarations from the prototype and move them
10770 // into the function DeclContext. Remove them from the surrounding tag
10771 // injection context of the function, which is typically but not always
10772 // the TU.
10773 DeclContext *PrototypeTagContext =
10774 getTagInjectionContext(DC: NewFD->getLexicalDeclContext());
10775 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10776 auto *TD = dyn_cast<TagDecl>(Val: NonParmDecl);
10777
10778 // We don't want to reparent enumerators. Look at their parent enum
10779 // instead.
10780 if (!TD) {
10781 if (auto *ECD = dyn_cast<EnumConstantDecl>(Val: NonParmDecl))
10782 TD = cast<EnumDecl>(Val: ECD->getDeclContext());
10783 }
10784 if (!TD)
10785 continue;
10786 DeclContext *TagDC = TD->getLexicalDeclContext();
10787 if (!TagDC->containsDecl(D: TD))
10788 continue;
10789 TagDC->removeDecl(D: TD);
10790 TD->setDeclContext(NewFD);
10791 NewFD->addDecl(D: TD);
10792
10793 // Preserve the lexical DeclContext if it is not the surrounding tag
10794 // injection context of the FD. In this example, the semantic context of
10795 // E will be f and the lexical context will be S, while both the
10796 // semantic and lexical contexts of S will be f:
10797 // void f(struct S { enum E { a } f; } s);
10798 if (TagDC != PrototypeTagContext)
10799 TD->setLexicalDeclContext(TagDC);
10800 }
10801 }
10802 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10803 // When we're declaring a function with a typedef, typeof, etc as in the
10804 // following example, we'll need to synthesize (unnamed)
10805 // parameters for use in the declaration.
10806 //
10807 // @code
10808 // typedef void fn(int);
10809 // fn f;
10810 // @endcode
10811
10812 // Synthesize a parameter for each argument type.
10813 for (const auto &AI : FT->param_types()) {
10814 ParmVarDecl *Param =
10815 BuildParmVarDeclForTypedef(DC: NewFD, Loc: D.getIdentifierLoc(), T: AI);
10816 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
10817 Params.push_back(Elt: Param);
10818 }
10819 } else {
10820 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10821 "Should not need args for typedef of non-prototype fn");
10822 }
10823
10824 // Finally, we know we have the right number of parameters, install them.
10825 NewFD->setParams(Params);
10826
10827 // If this declarator is a declaration and not a definition, its parameters
10828 // will not be pushed onto a scope chain. That means we will not issue any
10829 // reserved identifier warnings for the declaration, but we will for the
10830 // definition. Handle those here.
10831 if (!D.isFunctionDefinition()) {
10832 for (const ParmVarDecl *PVD : Params)
10833 warnOnReservedIdentifier(D: PVD);
10834 }
10835
10836 if (D.getDeclSpec().isNoreturnSpecified())
10837 NewFD->addAttr(
10838 A: C11NoReturnAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getNoreturnSpecLoc()));
10839
10840 // Functions returning a variably modified type violate C99 6.7.5.2p2
10841 // because all functions have linkage.
10842 if (!NewFD->isInvalidDecl() &&
10843 NewFD->getReturnType()->isVariablyModifiedType()) {
10844 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_vm_func_decl);
10845 NewFD->setInvalidDecl();
10846 }
10847
10848 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10849 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10850 !NewFD->hasAttr<SectionAttr>())
10851 NewFD->addAttr(A: PragmaClangTextSectionAttr::CreateImplicit(
10852 Ctx&: Context, Name: PragmaClangTextSection.SectionName,
10853 Range: PragmaClangTextSection.PragmaLocation));
10854
10855 // Apply an implicit SectionAttr if #pragma code_seg is active.
10856 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10857 !NewFD->hasAttr<SectionAttr>()) {
10858 NewFD->addAttr(A: SectionAttr::CreateImplicit(
10859 Ctx&: Context, Name: CodeSegStack.CurrentValue->getString(),
10860 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate));
10861 if (UnifySection(SectionName: CodeSegStack.CurrentValue->getString(),
10862 SectionFlags: ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10863 ASTContext::PSF_Read,
10864 TheDecl: NewFD))
10865 NewFD->dropAttr<SectionAttr>();
10866 }
10867
10868 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10869 // active.
10870 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10871 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10872 NewFD->addAttr(A: StrictGuardStackCheckAttr::CreateImplicit(
10873 Ctx&: Context, Range: PragmaClangTextSection.PragmaLocation));
10874
10875 // Apply an implicit CodeSegAttr from class declspec or
10876 // apply an implicit SectionAttr from #pragma code_seg if active.
10877 if (!NewFD->hasAttr<CodeSegAttr>()) {
10878 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(FD: NewFD,
10879 IsDefinition: D.isFunctionDefinition())) {
10880 NewFD->addAttr(A: SAttr);
10881 }
10882 }
10883
10884 // Handle attributes.
10885 ProcessDeclAttributes(S, D: NewFD, PD: D);
10886 addImplicitCallingConvAbiTag(FD: NewFD);
10887 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10888 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10889 !NewTVA->isDefaultVersion() &&
10890 !Context.getTargetInfo().hasFeature(Feature: "fmv")) {
10891 // Don't add to scope fmv functions declarations if fmv disabled
10892 AddToScope = false;
10893 return NewFD;
10894 }
10895
10896 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10897 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10898 // type.
10899 //
10900 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10901 // type declaration will generate a compilation error.
10902 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10903 if (AddressSpace != LangAS::Default) {
10904 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_return_value_with_address_space);
10905 NewFD->setInvalidDecl();
10906 }
10907 }
10908
10909 if (!getLangOpts().CPlusPlus) {
10910 // Perform semantic checking on the function declaration.
10911 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10912 CheckMain(FD: NewFD, D: D.getDeclSpec());
10913
10914 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10915 CheckMSVCRTEntryPoint(FD: NewFD);
10916
10917 if (!NewFD->isInvalidDecl())
10918 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10919 IsMemberSpecialization: isMemberSpecialization,
10920 DeclIsDefn: D.isFunctionDefinition()));
10921 else if (!Previous.empty())
10922 // Recover gracefully from an invalid redeclaration.
10923 D.setRedeclaration(true);
10924 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10925 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10926 "previous declaration set still overloaded");
10927
10928 // Diagnose no-prototype function declarations with calling conventions that
10929 // don't support variadic calls. Only do this in C and do it after merging
10930 // possibly prototyped redeclarations.
10931 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10932 if (isa<FunctionNoProtoType>(Val: FT) && !D.isFunctionDefinition()) {
10933 CallingConv CC = FT->getExtInfo().getCC();
10934 if (!supportsVariadicCall(CC)) {
10935 // Windows system headers sometimes accidentally use stdcall without
10936 // (void) parameters, so we relax this to a warning.
10937 int DiagID =
10938 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10939 Diag(Loc: NewFD->getLocation(), DiagID)
10940 << FunctionType::getNameForCallConv(CC);
10941 }
10942 }
10943
10944 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10945 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10946 checkNonTrivialCUnion(
10947 QT: NewFD->getReturnType(), Loc: NewFD->getReturnTypeSourceRange().getBegin(),
10948 UseContext: NonTrivialCUnionContext::FunctionReturn, NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
10949 } else {
10950 // C++11 [replacement.functions]p3:
10951 // The program's definitions shall not be specified as inline.
10952 //
10953 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10954 //
10955 // Suppress the diagnostic if the function is __attribute__((used)), since
10956 // that forces an external definition to be emitted.
10957 if (D.getDeclSpec().isInlineSpecified() &&
10958 NewFD->isReplaceableGlobalAllocationFunction() &&
10959 !NewFD->hasAttr<UsedAttr>())
10960 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10961 DiagID: diag::ext_operator_new_delete_declared_inline)
10962 << NewFD->getDeclName();
10963
10964 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10965 // C++20 [dcl.decl.general]p4:
10966 // The optional requires-clause in an init-declarator or
10967 // member-declarator shall be present only if the declarator declares a
10968 // templated function.
10969 //
10970 // C++20 [temp.pre]p8:
10971 // An entity is templated if it is
10972 // - a template,
10973 // - an entity defined or created in a templated entity,
10974 // - a member of a templated entity,
10975 // - an enumerator for an enumeration that is a templated entity, or
10976 // - the closure type of a lambda-expression appearing in the
10977 // declaration of a templated entity.
10978 //
10979 // [Note 6: A local class, a local or block variable, or a friend
10980 // function defined in a templated entity is a templated entity.
10981 // — end note]
10982 //
10983 // A templated function is a function template or a function that is
10984 // templated. A templated class is a class template or a class that is
10985 // templated. A templated variable is a variable template or a variable
10986 // that is templated.
10987 if (!FunctionTemplate) {
10988 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10989 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10990 // An explicit specialization shall not have a trailing
10991 // requires-clause unless it declares a function template.
10992 //
10993 // Since a friend function template specialization cannot be
10994 // definition, and since a non-template friend declaration with a
10995 // trailing requires-clause must be a definition, we diagnose
10996 // friend function template specializations with trailing
10997 // requires-clauses on the same path as explicit specializations
10998 // even though they aren't necessarily prohibited by the same
10999 // language rule.
11000 Diag(Loc: TRC->getBeginLoc(), DiagID: diag::err_non_temp_spec_requires_clause)
11001 << isFriend;
11002 } else if (isFriend && NewFD->isTemplated() &&
11003 !D.isFunctionDefinition()) {
11004 // C++ [temp.friend]p9:
11005 // A non-template friend declaration with a requires-clause shall be
11006 // a definition.
11007 Diag(Loc: NewFD->getBeginLoc(),
11008 DiagID: diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
11009 NewFD->setInvalidDecl();
11010 } else if (!NewFD->isTemplated() ||
11011 !(isa<CXXMethodDecl>(Val: NewFD) || D.isFunctionDefinition())) {
11012 Diag(Loc: TRC->getBeginLoc(),
11013 DiagID: diag::err_constrained_non_templated_function);
11014 }
11015 }
11016 }
11017
11018 // We do not add HD attributes to specializations here because
11019 // they may have different constexpr-ness compared to their
11020 // templates and, after maybeAddHostDeviceAttrs() is applied,
11021 // may end up with different effective targets. Instead, a
11022 // specialization inherits its target attributes from its template
11023 // in the CheckFunctionTemplateSpecialization() call below.
11024 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
11025 CUDA().maybeAddHostDeviceAttrs(FD: NewFD, Previous);
11026
11027 // Handle explicit specializations of function templates
11028 // and friend function declarations with an explicit
11029 // template argument list.
11030 if (isFunctionTemplateSpecialization) {
11031 bool isDependentSpecialization = false;
11032 if (isFriend) {
11033 // For friend function specializations, this is a dependent
11034 // specialization if its semantic context is dependent, its
11035 // qualifier is dependent, its type is dependent, or its template-id is
11036 // dependent.
11037 isDependentSpecialization =
11038 DC->isDependentContext() || NewFD->getQualifier().isDependent() ||
11039 NewFD->getType()->isDependentType() ||
11040 (HasExplicitTemplateArgs &&
11041 TemplateSpecializationType::
11042 anyInstantiationDependentTemplateArguments(
11043 Args: TemplateArgs.arguments()));
11044 assert((!isDependentSpecialization ||
11045 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
11046 "dependent friend function specialization without template "
11047 "args");
11048 } else {
11049 // For class-scope explicit specializations of function templates,
11050 // if the lexical context is dependent, then the specialization
11051 // is dependent.
11052 isDependentSpecialization =
11053 CurContext->isRecord() && CurContext->isDependentContext();
11054 }
11055
11056 TemplateArgumentListInfo *ExplicitTemplateArgs =
11057 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
11058 if (isDependentSpecialization) {
11059 // If it's a dependent specialization, it may not be possible
11060 // to determine the primary template (for explicit specializations)
11061 // or befriended declaration (for friends) until the enclosing
11062 // template is instantiated. In such cases, we store the declarations
11063 // found by name lookup and defer resolution until instantiation.
11064 if (CheckDependentFunctionTemplateSpecialization(
11065 FD: NewFD, ExplicitTemplateArgs, Previous))
11066 NewFD->setInvalidDecl();
11067 } else if (!NewFD->isInvalidDecl()) {
11068 if (CheckFunctionTemplateSpecialization(FD: NewFD, ExplicitTemplateArgs,
11069 Previous))
11070 NewFD->setInvalidDecl();
11071 }
11072 } else if (isMemberSpecialization && !FunctionTemplate) {
11073 if (CheckMemberSpecialization(Member: NewFD, Previous))
11074 NewFD->setInvalidDecl();
11075 }
11076
11077 // Perform semantic checking on the function declaration.
11078 if (!NewFD->isInvalidDecl() && NewFD->isMain())
11079 CheckMain(FD: NewFD, D: D.getDeclSpec());
11080
11081 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
11082 CheckMSVCRTEntryPoint(FD: NewFD);
11083
11084 if (!NewFD->isInvalidDecl())
11085 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
11086 IsMemberSpecialization: isMemberSpecialization,
11087 DeclIsDefn: D.isFunctionDefinition()));
11088 else if (!Previous.empty())
11089 // Recover gracefully from an invalid redeclaration.
11090 D.setRedeclaration(true);
11091
11092 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
11093 !D.isRedeclaration() ||
11094 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
11095 "previous declaration set still overloaded");
11096
11097 NamedDecl *PrincipalDecl = (FunctionTemplate
11098 ? cast<NamedDecl>(Val: FunctionTemplate)
11099 : NewFD);
11100
11101 if (isFriend && NewFD->getPreviousDecl()) {
11102 AccessSpecifier Access = AS_public;
11103 if (!NewFD->isInvalidDecl())
11104 Access = NewFD->getPreviousDecl()->getAccess();
11105
11106 NewFD->setAccess(Access);
11107 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
11108 }
11109
11110 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
11111 PrincipalDecl->isInIdentifierNamespace(NS: Decl::IDNS_Ordinary))
11112 PrincipalDecl->setNonMemberOperator();
11113
11114 // If we have a function template, check the template parameter
11115 // list. This will check and merge default template arguments.
11116 if (FunctionTemplate) {
11117 FunctionTemplateDecl *PrevTemplate =
11118 FunctionTemplate->getPreviousDecl();
11119 CheckTemplateParameterList(NewParams: FunctionTemplate->getTemplateParameters(),
11120 OldParams: PrevTemplate ? PrevTemplate->getTemplateParameters()
11121 : nullptr,
11122 TPC: D.getDeclSpec().isFriendSpecified()
11123 ? (D.isFunctionDefinition()
11124 ? TPC_FriendFunctionTemplateDefinition
11125 : TPC_FriendFunctionTemplate)
11126 : (D.getCXXScopeSpec().isSet() &&
11127 DC && DC->isRecord() &&
11128 DC->isDependentContext())
11129 ? TPC_ClassTemplateMember
11130 : TPC_FunctionTemplate);
11131 }
11132
11133 if (NewFD->isInvalidDecl()) {
11134 // Ignore all the rest of this.
11135 } else if (!D.isRedeclaration()) {
11136 struct ActOnFDArgs ExtraArgs = { .S: S, .D: D, .TemplateParamLists: TemplateParamLists,
11137 .AddToScope: AddToScope };
11138 // Fake up an access specifier if it's supposed to be a class member.
11139 if (isa<CXXRecordDecl>(Val: NewFD->getDeclContext()))
11140 NewFD->setAccess(AS_public);
11141
11142 // Qualified decls generally require a previous declaration.
11143 if (D.getCXXScopeSpec().isSet()) {
11144 // ...with the major exception of templated-scope or
11145 // dependent-scope friend declarations.
11146
11147 // TODO: we currently also suppress this check in dependent
11148 // contexts because (1) the parameter depth will be off when
11149 // matching friend templates and (2) we might actually be
11150 // selecting a friend based on a dependent factor. But there
11151 // are situations where these conditions don't apply and we
11152 // can actually do this check immediately.
11153 //
11154 // Unless the scope is dependent, it's always an error if qualified
11155 // redeclaration lookup found nothing at all. Diagnose that now;
11156 // nothing will diagnose that error later.
11157 if (isFriend &&
11158 (D.getCXXScopeSpec().getScopeRep().isDependent() ||
11159 (!Previous.empty() && CurContext->isDependentContext()))) {
11160 // ignore these
11161 } else if (NewFD->isCPUDispatchMultiVersion() ||
11162 NewFD->isCPUSpecificMultiVersion()) {
11163 // ignore this, we allow the redeclaration behavior here to create new
11164 // versions of the function.
11165 } else {
11166 // The user tried to provide an out-of-line definition for a
11167 // function that is a member of a class or namespace, but there
11168 // was no such member function declared (C++ [class.mfct]p2,
11169 // C++ [namespace.memdef]p2). For example:
11170 //
11171 // class X {
11172 // void f() const;
11173 // };
11174 //
11175 // void X::f() { } // ill-formed
11176 //
11177 // Complain about this problem, and attempt to suggest close
11178 // matches (e.g., those that differ only in cv-qualifiers and
11179 // whether the parameter types are references).
11180
11181 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
11182 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: false, S: nullptr)) {
11183 AddToScope = ExtraArgs.AddToScope;
11184 return Result;
11185 }
11186 }
11187
11188 // Unqualified local friend declarations are required to resolve
11189 // to something.
11190 } else if (isFriend && cast<CXXRecordDecl>(Val: CurContext)->isLocalClass()) {
11191 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
11192 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: true, S)) {
11193 AddToScope = ExtraArgs.AddToScope;
11194 return Result;
11195 }
11196 }
11197 } else if (!D.isFunctionDefinition() &&
11198 isa<CXXMethodDecl>(Val: NewFD) && NewFD->isOutOfLine() &&
11199 !isFriend && !isFunctionTemplateSpecialization &&
11200 !isMemberSpecialization) {
11201 // An out-of-line member function declaration must also be a
11202 // definition (C++ [class.mfct]p2).
11203 // Note that this is not the case for explicit specializations of
11204 // function templates or member functions of class templates, per
11205 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11206 // extension for compatibility with old SWIG code which likes to
11207 // generate them.
11208 Diag(Loc: NewFD->getLocation(), DiagID: diag::ext_out_of_line_declaration)
11209 << D.getCXXScopeSpec().getRange();
11210 }
11211 }
11212
11213 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11214 // Any top level function could potentially be specified as an entry.
11215 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11216 HLSL().ActOnTopLevelFunction(FD: NewFD);
11217
11218 if (NewFD->hasAttr<HLSLShaderAttr>())
11219 HLSL().CheckEntryPoint(FD: NewFD);
11220
11221 // Resources cannot be passed to functions that are not inlined.
11222 if (const NoInlineAttr *NoInline = NewFD->getAttr<NoInlineAttr>()) {
11223 for (const ParmVarDecl *PVD : NewFD->parameters()) {
11224 QualType ParamTy = PVD->getType().getNonReferenceType();
11225 QualType EltTy = Context.getBaseElementType(QT: ParamTy);
11226 // `isCompleteType` forces completion of the element type without
11227 // reporting an error (diagnosed elsewhere) so the resource parameter
11228 // check is valid.
11229 if (!EltTy->isDependentType() &&
11230 isCompleteType(Loc: PVD->getLocation(), T: EltTy) &&
11231 ParamTy->isHLSLIntangibleType()) {
11232 Diag(Loc: PVD->getLocation(),
11233 DiagID: diag::err_hlsl_resource_param_in_noinline_function)
11234 << ParamTy;
11235 Diag(Loc: NoInline->getLocation(), DiagID: diag::note_attribute);
11236 }
11237 }
11238 }
11239 }
11240
11241 // If this is the first declaration of a library builtin function, add
11242 // attributes as appropriate.
11243 if (!D.isRedeclaration()) {
11244 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11245 if (unsigned BuiltinID = II->getBuiltinID()) {
11246 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID);
11247 if (!InStdNamespace &&
11248 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
11249 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11250 // Validate the type matches unless this builtin is specified as
11251 // matching regardless of its declared type.
11252 if (Context.BuiltinInfo.allowTypeMismatch(ID: BuiltinID)) {
11253 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11254 } else {
11255 ASTContext::GetBuiltinTypeError Error;
11256 LookupNecessaryTypesForBuiltin(S, ID: BuiltinID);
11257 QualType BuiltinType = Context.GetBuiltinType(ID: BuiltinID, Error);
11258
11259 if (!Error && !BuiltinType.isNull() &&
11260 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11261 T: NewFD->getType(), U: BuiltinType))
11262 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11263 }
11264 }
11265 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11266 isStdBuiltin(Ctx&: Context, FD: NewFD, BuiltinID)) {
11267 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11268 }
11269 }
11270 }
11271 }
11272
11273 ProcessPragmaWeak(S, D: NewFD);
11274 ProcessPragmaExport(NewD: NewFD);
11275 checkAttributesAfterMerging(S&: *this, ND&: *NewFD);
11276
11277 AddKnownFunctionAttributes(FD: NewFD);
11278 // The above can add the format attribute for known builtin/library functions
11279 // which is required by the modular_format attribute, thus
11280 // validate modular_format now after those attributes have been added.
11281 checkModularFormatAttr(S&: *this, ND&: *NewFD);
11282
11283 if (NewFD->hasAttr<OverloadableAttr>() &&
11284 !NewFD->getType()->getAs<FunctionProtoType>()) {
11285 Diag(Loc: NewFD->getLocation(),
11286 DiagID: diag::err_attribute_overloadable_no_prototype)
11287 << NewFD;
11288 NewFD->dropAttr<OverloadableAttr>();
11289 }
11290
11291 // If there's a #pragma GCC visibility in scope, and this isn't a class
11292 // member, set the visibility of this function.
11293 if (!DC->isRecord() && NewFD->isExternallyVisible())
11294 AddPushedVisibilityAttribute(RD: NewFD);
11295
11296 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11297 // marking the function.
11298 ObjC().AddCFAuditedAttribute(D: NewFD);
11299
11300 // If this is a function definition, check if we have to apply any
11301 // attributes (i.e. optnone and no_builtin) due to a pragma.
11302 if (D.isFunctionDefinition()) {
11303 AddRangeBasedOptnone(FD: NewFD);
11304 AddImplicitMSFunctionNoBuiltinAttr(FD: NewFD);
11305 AddSectionMSAllocText(FD: NewFD);
11306 ModifyFnAttributesMSPragmaOptimize(FD: NewFD);
11307 }
11308
11309 // If this is the first declaration of an extern C variable, update
11310 // the map of such variables.
11311 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11312 isIncompleteDeclExternC(S&: *this, D: NewFD))
11313 RegisterLocallyScopedExternCDecl(ND: NewFD, S);
11314
11315 // Set this FunctionDecl's range up to the right paren.
11316 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11317
11318 if (D.isRedeclaration() && !Previous.empty()) {
11319 NamedDecl *Prev = Previous.getRepresentativeDecl();
11320 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewFD,
11321 IsSpecialization: isMemberSpecialization ||
11322 isFunctionTemplateSpecialization,
11323 IsDefinition: D.isFunctionDefinition());
11324 }
11325
11326 if (getLangOpts().CUDA) {
11327 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11328 if (II->isStr(Str: CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11329 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11330 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11331 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11332 << CUDA().getConfigureFuncName();
11333 Context.setcudaConfigureCallDecl(NewFD);
11334 }
11335 if (II->isStr(Str: CUDA().getGetParameterBufferFuncName()) &&
11336 !NewFD->isInvalidDecl() &&
11337 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11338 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11339 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_pointer_return)
11340 << CUDA().getConfigureFuncName();
11341 Context.setcudaGetParameterBufferDecl(NewFD);
11342 }
11343 if (II->isStr(Str: CUDA().getLaunchDeviceFuncName()) &&
11344 !NewFD->isInvalidDecl() &&
11345 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11346 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11347 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11348 << CUDA().getConfigureFuncName();
11349 Context.setcudaLaunchDeviceDecl(NewFD);
11350 }
11351 }
11352 }
11353
11354 MarkUnusedFileScopedDecl(D: NewFD);
11355
11356 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11357 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11358 if (SC == SC_Static) {
11359 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_static_kernel);
11360 D.setInvalidType();
11361 }
11362
11363 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11364 if (!NewFD->getReturnType()->isVoidType()) {
11365 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11366 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_expected_kernel_void_return_type)
11367 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "void")
11368 : FixItHint());
11369 D.setInvalidType();
11370 }
11371
11372 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
11373 for (auto *Param : NewFD->parameters())
11374 checkIsValidOpenCLKernelParameter(S&: *this, D, Param, ValidTypes);
11375
11376 if (getLangOpts().OpenCLCPlusPlus) {
11377 if (DC->isRecord()) {
11378 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_method_kernel);
11379 D.setInvalidType();
11380 }
11381 if (FunctionTemplate) {
11382 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_kernel);
11383 D.setInvalidType();
11384 }
11385 }
11386 }
11387
11388 if (getLangOpts().CPlusPlus) {
11389 // Precalculate whether this is a friend function template with a constraint
11390 // that depends on an enclosing template, per [temp.friend]p9.
11391 if (isFriend && FunctionTemplate &&
11392 FriendConstraintsDependOnEnclosingTemplate(FD: NewFD)) {
11393 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
11394
11395 // C++ [temp.friend]p9:
11396 // A friend function template with a constraint that depends on a
11397 // template parameter from an enclosing template shall be a definition.
11398 if (!D.isFunctionDefinition()) {
11399 Diag(Loc: NewFD->getBeginLoc(),
11400 DiagID: diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11401 NewFD->setInvalidDecl();
11402 }
11403 }
11404
11405 if (FunctionTemplate) {
11406 if (NewFD->isInvalidDecl())
11407 FunctionTemplate->setInvalidDecl();
11408 return FunctionTemplate;
11409 }
11410
11411 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11412 CompleteMemberSpecialization(Member: NewFD, Previous);
11413 }
11414
11415 for (const ParmVarDecl *Param : NewFD->parameters()) {
11416 QualType PT = Param->getType();
11417
11418 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11419 // types.
11420 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11421 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11422 QualType ElemTy = PipeTy->getElementType();
11423 if (ElemTy->isPointerOrReferenceType()) {
11424 Diag(Loc: Param->getTypeSpecStartLoc(), DiagID: diag::err_reference_pipe_type);
11425 D.setInvalidType();
11426 }
11427 }
11428 }
11429 // WebAssembly tables can't be used as function parameters.
11430 if (Context.getTargetInfo().getTriple().isWasm()) {
11431 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
11432 Diag(Loc: Param->getTypeSpecStartLoc(),
11433 DiagID: diag::err_wasm_table_as_function_parameter);
11434 D.setInvalidType();
11435 }
11436 }
11437 }
11438
11439 // Diagnose availability attributes. Availability cannot be used on functions
11440 // that are run during load/unload.
11441 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11442 if (NewFD->hasAttr<ConstructorAttr>()) {
11443 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11444 << 1;
11445 NewFD->dropAttr<AvailabilityAttr>();
11446 }
11447 if (NewFD->hasAttr<DestructorAttr>()) {
11448 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11449 << 2;
11450 NewFD->dropAttr<AvailabilityAttr>();
11451 }
11452 }
11453
11454 // Diagnose no_builtin attribute on function declaration that are not a
11455 // definition.
11456 // FIXME: We should really be doing this in
11457 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11458 // the FunctionDecl and at this point of the code
11459 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11460 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11461 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11462 switch (D.getFunctionDefinitionKind()) {
11463 case FunctionDefinitionKind::Defaulted:
11464 case FunctionDefinitionKind::Deleted:
11465 Diag(Loc: NBA->getLocation(),
11466 DiagID: diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11467 << NBA->getSpelling();
11468 break;
11469 case FunctionDefinitionKind::Declaration:
11470 Diag(Loc: NBA->getLocation(), DiagID: diag::err_attribute_no_builtin_on_non_definition)
11471 << NBA->getSpelling();
11472 break;
11473 case FunctionDefinitionKind::Definition:
11474 break;
11475 }
11476
11477 // Similar to no_builtin logic above, at this point of the code
11478 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11479 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11480 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11481 !NewFD->isInvalidDecl() &&
11482 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
11483 ExternalDeclarations.push_back(Elt: NewFD);
11484
11485 // Used for a warning on the 'next' declaration when used with a
11486 // `routine(name)`.
11487 if (getLangOpts().OpenACC)
11488 OpenACC().ActOnFunctionDeclarator(FD: NewFD);
11489
11490 return NewFD;
11491}
11492
11493/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11494/// when __declspec(code_seg) "is applied to a class, all member functions of
11495/// the class and nested classes -- this includes compiler-generated special
11496/// member functions -- are put in the specified segment."
11497/// The actual behavior is a little more complicated. The Microsoft compiler
11498/// won't check outer classes if there is an active value from #pragma code_seg.
11499/// The CodeSeg is always applied from the direct parent but only from outer
11500/// classes when the #pragma code_seg stack is empty. See:
11501/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11502/// available since MS has removed the page.
11503static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
11504 const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
11505 if (!Method)
11506 return nullptr;
11507 const CXXRecordDecl *Parent = Method->getParent();
11508 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11509 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11510 NewAttr->setImplicit(true);
11511 return NewAttr;
11512 }
11513
11514 // The Microsoft compiler won't check outer classes for the CodeSeg
11515 // when the #pragma code_seg stack is active.
11516 if (S.CodeSegStack.CurrentValue)
11517 return nullptr;
11518
11519 while ((Parent = dyn_cast<CXXRecordDecl>(Val: Parent->getParent()))) {
11520 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11521 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11522 NewAttr->setImplicit(true);
11523 return NewAttr;
11524 }
11525 }
11526 return nullptr;
11527}
11528
11529Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
11530 bool IsDefinition) {
11531 if (Attr *A = getImplicitCodeSegAttrFromClass(S&: *this, FD))
11532 return A;
11533 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11534 CodeSegStack.CurrentValue)
11535 return SectionAttr::CreateImplicit(
11536 Ctx&: getASTContext(), Name: CodeSegStack.CurrentValue->getString(),
11537 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate);
11538 return nullptr;
11539}
11540
11541bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
11542 QualType NewT, QualType OldT) {
11543 if (!NewD->getLexicalDeclContext()->isDependentContext())
11544 return true;
11545
11546 // For dependently-typed local extern declarations and friends, we can't
11547 // perform a correct type check in general until instantiation:
11548 //
11549 // int f();
11550 // template<typename T> void g() { T f(); }
11551 //
11552 // (valid if g() is only instantiated with T = int).
11553 if (NewT->isDependentType() &&
11554 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11555 return false;
11556
11557 // Similarly, if the previous declaration was a dependent local extern
11558 // declaration, we don't really know its type yet.
11559 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11560 return false;
11561
11562 return true;
11563}
11564
11565bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11566 if (!D->getLexicalDeclContext()->isDependentContext())
11567 return true;
11568
11569 // Don't chain dependent friend function definitions until instantiation, to
11570 // permit cases like
11571 //
11572 // void func();
11573 // template<typename T> class C1 { friend void func() {} };
11574 // template<typename T> class C2 { friend void func() {} };
11575 //
11576 // ... which is valid if only one of C1 and C2 is ever instantiated.
11577 //
11578 // FIXME: This need only apply to function definitions. For now, we proxy
11579 // this by checking for a file-scope function. We do not want this to apply
11580 // to friend declarations nominating member functions, because that gets in
11581 // the way of access checks.
11582 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11583 return false;
11584
11585 auto *VD = dyn_cast<ValueDecl>(Val: D);
11586 auto *PrevVD = dyn_cast<ValueDecl>(Val: PrevDecl);
11587 return !VD || !PrevVD ||
11588 canFullyTypeCheckRedeclaration(NewD: VD, OldD: PrevVD, NewT: VD->getType(),
11589 OldT: PrevVD->getType());
11590}
11591
11592/// Check the target or target_version attribute of the function for
11593/// MultiVersion validity.
11594///
11595/// Returns true if there was an error, false otherwise.
11596static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11597 const auto *TA = FD->getAttr<TargetAttr>();
11598 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11599
11600 assert((TA || TVA) && "Expecting target or target_version attribute");
11601
11602 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11603 enum ErrType { Feature = 0, Architecture = 1 };
11604
11605 if (TA) {
11606 ParsedTargetAttr ParseInfo =
11607 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TA->getFeaturesStr());
11608 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(Name: ParseInfo.CPU)) {
11609 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11610 << Architecture << ParseInfo.CPU;
11611 return true;
11612 }
11613 for (const auto &Feat : ParseInfo.Features) {
11614 auto BareFeat = StringRef{Feat}.substr(Start: 1);
11615 if (Feat[0] == '-') {
11616 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11617 << Feature << ("no-" + BareFeat);
11618 return true;
11619 }
11620
11621 if (!TargetInfo.validateCpuSupports(Name: BareFeat) ||
11622 !TargetInfo.isValidFeatureName(Feature: BareFeat) ||
11623 (BareFeat != "default" && TargetInfo.getFMVPriority(Features: BareFeat) == 0)) {
11624 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11625 << Feature << BareFeat;
11626 return true;
11627 }
11628 }
11629 }
11630
11631 if (TVA) {
11632 llvm::SmallVector<StringRef, 8> Feats;
11633 ParsedTargetAttr ParseInfo;
11634 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11635 ParseInfo =
11636 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TVA->getName());
11637 for (auto &Feat : ParseInfo.Features)
11638 Feats.push_back(Elt: StringRef{Feat}.substr(Start: 1));
11639 } else {
11640 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11641 TVA->getFeatures(Out&: Feats);
11642 }
11643 for (const auto &Feat : Feats) {
11644 if (!TargetInfo.validateCpuSupports(Name: Feat)) {
11645 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11646 << Feature << Feat;
11647 return true;
11648 }
11649 }
11650 }
11651 return false;
11652}
11653
11654// Provide a white-list of attributes that are allowed to be combined with
11655// multiversion functions.
11656static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11657 MultiVersionKind MVKind) {
11658 // Note: this list/diagnosis must match the list in
11659 // checkMultiversionAttributesAllSame.
11660 switch (Kind) {
11661 default:
11662 return false;
11663 case attr::ArmLocallyStreaming:
11664 return MVKind == MultiVersionKind::TargetVersion ||
11665 MVKind == MultiVersionKind::TargetClones;
11666 case attr::Used:
11667 return MVKind == MultiVersionKind::Target;
11668 case attr::NonNull:
11669 case attr::NoThrow:
11670 return true;
11671 }
11672}
11673
11674static bool checkNonMultiVersionCompatAttributes(Sema &S,
11675 const FunctionDecl *FD,
11676 const FunctionDecl *CausedFD,
11677 MultiVersionKind MVKind) {
11678 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11679 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_disallowed_other_attr)
11680 << static_cast<unsigned>(MVKind) << A;
11681 if (CausedFD)
11682 S.Diag(Loc: CausedFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11683 return true;
11684 };
11685
11686 for (const Attr *A : FD->attrs()) {
11687 switch (A->getKind()) {
11688 case attr::CPUDispatch:
11689 case attr::CPUSpecific:
11690 if (MVKind != MultiVersionKind::CPUDispatch &&
11691 MVKind != MultiVersionKind::CPUSpecific)
11692 return Diagnose(S, A);
11693 break;
11694 case attr::Target:
11695 if (MVKind != MultiVersionKind::Target)
11696 return Diagnose(S, A);
11697 break;
11698 case attr::TargetVersion:
11699 if (MVKind != MultiVersionKind::TargetVersion &&
11700 MVKind != MultiVersionKind::TargetClones)
11701 return Diagnose(S, A);
11702 break;
11703 case attr::TargetClones:
11704 if (MVKind != MultiVersionKind::TargetClones &&
11705 MVKind != MultiVersionKind::TargetVersion)
11706 return Diagnose(S, A);
11707 break;
11708 default:
11709 if (!AttrCompatibleWithMultiVersion(Kind: A->getKind(), MVKind))
11710 return Diagnose(S, A);
11711 break;
11712 }
11713 }
11714 return false;
11715}
11716
11717bool Sema::areMultiversionVariantFunctionsCompatible(
11718 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11719 const PartialDiagnostic &NoProtoDiagID,
11720 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11721 const PartialDiagnosticAt &NoSupportDiagIDAt,
11722 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11723 bool ConstexprSupported, bool CLinkageMayDiffer) {
11724 enum DoesntSupport {
11725 FuncTemplates = 0,
11726 VirtFuncs = 1,
11727 DeducedReturn = 2,
11728 Constructors = 3,
11729 Destructors = 4,
11730 DeletedFuncs = 5,
11731 DefaultedFuncs = 6,
11732 ConstexprFuncs = 7,
11733 ConstevalFuncs = 8,
11734 Lambda = 9,
11735 };
11736 enum Different {
11737 CallingConv = 0,
11738 ReturnType = 1,
11739 ConstexprSpec = 2,
11740 InlineSpec = 3,
11741 Linkage = 4,
11742 LanguageLinkage = 5,
11743 };
11744
11745 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11746 !OldFD->getType()->getAs<FunctionProtoType>()) {
11747 Diag(Loc: OldFD->getLocation(), PD: NoProtoDiagID);
11748 Diag(Loc: NoteCausedDiagIDAt.first, PD: NoteCausedDiagIDAt.second);
11749 return true;
11750 }
11751
11752 if (NoProtoDiagID.getDiagID() != 0 &&
11753 !NewFD->getType()->getAs<FunctionProtoType>())
11754 return Diag(Loc: NewFD->getLocation(), PD: NoProtoDiagID);
11755
11756 if (!TemplatesSupported &&
11757 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11758 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11759 << FuncTemplates;
11760
11761 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
11762 if (NewCXXFD->isVirtual())
11763 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11764 << VirtFuncs;
11765
11766 if (isa<CXXConstructorDecl>(Val: NewCXXFD))
11767 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11768 << Constructors;
11769
11770 if (isa<CXXDestructorDecl>(Val: NewCXXFD))
11771 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11772 << Destructors;
11773 }
11774
11775 if (NewFD->isDeleted())
11776 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11777 << DeletedFuncs;
11778
11779 if (NewFD->isDefaulted())
11780 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11781 << DefaultedFuncs;
11782
11783 if (!ConstexprSupported && NewFD->isConstexpr())
11784 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11785 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11786
11787 QualType NewQType = Context.getCanonicalType(T: NewFD->getType());
11788 const auto *NewType = cast<FunctionType>(Val&: NewQType);
11789 QualType NewReturnType = NewType->getReturnType();
11790
11791 if (NewReturnType->isUndeducedType())
11792 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11793 << DeducedReturn;
11794
11795 // Ensure the return type is identical.
11796 if (OldFD) {
11797 QualType OldQType = Context.getCanonicalType(T: OldFD->getType());
11798 const auto *OldType = cast<FunctionType>(Val&: OldQType);
11799 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11800 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11801
11802 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11803 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11804
11805 bool ArmStreamingCCMismatched = false;
11806 if (OldFPT && NewFPT) {
11807 unsigned Diff =
11808 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11809 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11810 // cannot be mixed.
11811 if (Diff & (FunctionType::SME_PStateSMEnabledMask |
11812 FunctionType::SME_PStateSMCompatibleMask))
11813 ArmStreamingCCMismatched = true;
11814 }
11815
11816 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11817 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << CallingConv;
11818
11819 QualType OldReturnType = OldType->getReturnType();
11820
11821 if (OldReturnType != NewReturnType)
11822 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ReturnType;
11823
11824 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11825 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ConstexprSpec;
11826
11827 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11828 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << InlineSpec;
11829
11830 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11831 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << Linkage;
11832
11833 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11834 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << LanguageLinkage;
11835
11836 if (CheckEquivalentExceptionSpec(Old: OldFPT, OldLoc: OldFD->getLocation(), New: NewFPT,
11837 NewLoc: NewFD->getLocation()))
11838 return true;
11839 }
11840 return false;
11841}
11842
11843static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11844 const FunctionDecl *NewFD,
11845 bool CausesMV,
11846 MultiVersionKind MVKind) {
11847 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11848 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_supported);
11849 if (OldFD)
11850 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11851 return true;
11852 }
11853
11854 bool IsCPUSpecificCPUDispatchMVKind =
11855 MVKind == MultiVersionKind::CPUDispatch ||
11856 MVKind == MultiVersionKind::CPUSpecific;
11857
11858 if (CausesMV && OldFD &&
11859 checkNonMultiVersionCompatAttributes(S, FD: OldFD, CausedFD: NewFD, MVKind))
11860 return true;
11861
11862 if (checkNonMultiVersionCompatAttributes(S, FD: NewFD, CausedFD: nullptr, MVKind))
11863 return true;
11864
11865 // Only allow transition to MultiVersion if it hasn't been used.
11866 if (OldFD && CausesMV && OldFD->isUsed(CheckUsedAttr: false)) {
11867 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
11868 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11869 return true;
11870 }
11871
11872 return S.areMultiversionVariantFunctionsCompatible(
11873 OldFD, NewFD, NoProtoDiagID: S.PDiag(DiagID: diag::err_multiversion_noproto),
11874 NoteCausedDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11875 S.PDiag(DiagID: diag::note_multiversioning_caused_here)),
11876 NoSupportDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11877 S.PDiag(DiagID: diag::err_multiversion_doesnt_support)
11878 << static_cast<unsigned>(MVKind)),
11879 DiffDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11880 S.PDiag(DiagID: diag::err_multiversion_diff)),
11881 /*TemplatesSupported=*/false,
11882 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11883 /*CLinkageMayDiffer=*/false);
11884}
11885
11886/// Check the validity of a multiversion function declaration that is the
11887/// first of its kind. Also sets the multiversion'ness' of the function itself.
11888///
11889/// This sets NewFD->isInvalidDecl() to true if there was an error.
11890///
11891/// Returns true if there was an error, false otherwise.
11892static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11893 MultiVersionKind MVKind = FD->getMultiVersionKind();
11894 assert(MVKind != MultiVersionKind::None &&
11895 "Function lacks multiversion attribute");
11896 const auto *TA = FD->getAttr<TargetAttr>();
11897 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11898 // The target attribute only causes MV if this declaration is the default,
11899 // otherwise it is treated as a normal function.
11900 if (TA && !TA->isDefaultVersion())
11901 return false;
11902
11903 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11904 FD->setInvalidDecl();
11905 return true;
11906 }
11907
11908 if (CheckMultiVersionAdditionalRules(S, OldFD: nullptr, NewFD: FD, CausesMV: true, MVKind)) {
11909 FD->setInvalidDecl();
11910 return true;
11911 }
11912
11913 FD->setIsMultiVersion();
11914 return false;
11915}
11916
11917static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11918 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11919 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11920 return true;
11921 }
11922
11923 return false;
11924}
11925
11926static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
11927 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11928 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11929 return;
11930
11931 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11932 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11933
11934 if (MVKindTo == MultiVersionKind::None &&
11935 (MVKindFrom == MultiVersionKind::TargetVersion ||
11936 MVKindFrom == MultiVersionKind::TargetClones))
11937 To->addAttr(A: TargetVersionAttr::CreateImplicit(
11938 Ctx&: To->getASTContext(), NamesStr: "default", Range: To->getSourceRange()));
11939}
11940
11941static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11942 FunctionDecl *NewFD,
11943 bool &Redeclaration,
11944 NamedDecl *&OldDecl,
11945 LookupResult &Previous) {
11946 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11947
11948 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11949 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11950 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11951 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11952
11953 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11954
11955 // The definitions should be allowed in any order. If we have discovered
11956 // a new target version and the preceeding was the default, then add the
11957 // corresponding attribute to it.
11958 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11959
11960 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11961 // to change, this is a simple redeclaration.
11962 if (NewTA && !NewTA->isDefaultVersion() &&
11963 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11964 return false;
11965
11966 // Otherwise, this decl causes MultiVersioning.
11967 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, CausesMV: true,
11968 MVKind: NewTVA ? MultiVersionKind::TargetVersion
11969 : MultiVersionKind::Target)) {
11970 NewFD->setInvalidDecl();
11971 return true;
11972 }
11973
11974 if (CheckMultiVersionValue(S, FD: NewFD)) {
11975 NewFD->setInvalidDecl();
11976 return true;
11977 }
11978
11979 // If this is 'default', permit the forward declaration.
11980 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11981 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11982 Redeclaration = true;
11983 OldDecl = OldFD;
11984 OldFD->setIsMultiVersion();
11985 NewFD->setIsMultiVersion();
11986 return false;
11987 }
11988
11989 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, FD: OldFD)) {
11990 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11991 NewFD->setInvalidDecl();
11992 return true;
11993 }
11994
11995 if (NewTA) {
11996 ParsedTargetAttr OldParsed =
11997 S.getASTContext().getTargetInfo().parseTargetAttr(
11998 Str: OldTA->getFeaturesStr());
11999 llvm::sort(C&: OldParsed.Features);
12000 ParsedTargetAttr NewParsed =
12001 S.getASTContext().getTargetInfo().parseTargetAttr(
12002 Str: NewTA->getFeaturesStr());
12003 // Sort order doesn't matter, it just needs to be consistent.
12004 llvm::sort(C&: NewParsed.Features);
12005 if (OldParsed == NewParsed) {
12006 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12007 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
12008 NewFD->setInvalidDecl();
12009 return true;
12010 }
12011 }
12012
12013 for (const auto *FD : OldFD->redecls()) {
12014 const auto *CurTA = FD->getAttr<TargetAttr>();
12015 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
12016 // We allow forward declarations before ANY multiversioning attributes, but
12017 // nothing after the fact.
12018 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
12019 ((NewTA && (!CurTA || CurTA->isInherited())) ||
12020 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
12021 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
12022 << (NewTA ? 0 : 2);
12023 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
12024 NewFD->setInvalidDecl();
12025 return true;
12026 }
12027 }
12028
12029 OldFD->setIsMultiVersion();
12030 NewFD->setIsMultiVersion();
12031 Redeclaration = false;
12032 OldDecl = nullptr;
12033 Previous.clear();
12034 return false;
12035}
12036
12037static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {
12038 MultiVersionKind OldKind = Old->getMultiVersionKind();
12039 MultiVersionKind NewKind = New->getMultiVersionKind();
12040
12041 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
12042 NewKind == MultiVersionKind::None)
12043 return true;
12044
12045 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
12046 switch (OldKind) {
12047 case MultiVersionKind::TargetVersion:
12048 return NewKind == MultiVersionKind::TargetClones;
12049 case MultiVersionKind::TargetClones:
12050 return NewKind == MultiVersionKind::TargetVersion;
12051 default:
12052 return false;
12053 }
12054 } else {
12055 switch (OldKind) {
12056 case MultiVersionKind::CPUDispatch:
12057 return NewKind == MultiVersionKind::CPUSpecific;
12058 case MultiVersionKind::CPUSpecific:
12059 return NewKind == MultiVersionKind::CPUDispatch;
12060 default:
12061 return false;
12062 }
12063 }
12064}
12065
12066/// Check the validity of a new function declaration being added to an existing
12067/// multiversioned declaration collection.
12068static bool CheckMultiVersionAdditionalDecl(
12069 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
12070 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
12071 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
12072 LookupResult &Previous) {
12073
12074 // Disallow mixing of multiversioning types.
12075 if (!MultiVersionTypesCompatible(Old: OldFD, New: NewFD)) {
12076 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_types_mixed);
12077 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
12078 NewFD->setInvalidDecl();
12079 return true;
12080 }
12081
12082 // Add the default target_version attribute if it's missing.
12083 patchDefaultTargetVersion(From: OldFD, To: NewFD);
12084 patchDefaultTargetVersion(From: NewFD, To: OldFD);
12085
12086 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12087 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12088 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
12089 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
12090
12091 ParsedTargetAttr NewParsed;
12092 if (NewTA) {
12093 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
12094 Str: NewTA->getFeaturesStr());
12095 llvm::sort(C&: NewParsed.Features);
12096 }
12097 llvm::SmallVector<StringRef, 8> NewFeats;
12098 if (NewTVA) {
12099 NewTVA->getFeatures(Out&: NewFeats);
12100 llvm::sort(C&: NewFeats);
12101 }
12102
12103 bool UseMemberUsingDeclRules =
12104 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
12105
12106 bool MayNeedOverloadableChecks =
12107 AllowOverloadingOfFunction(Previous, Context&: S.Context, New: NewFD);
12108
12109 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
12110 // of a previous member of the MultiVersion set.
12111 for (NamedDecl *ND : Previous) {
12112 FunctionDecl *CurFD = ND->getAsFunction();
12113 if (!CurFD || CurFD->isInvalidDecl())
12114 continue;
12115 if (MayNeedOverloadableChecks &&
12116 S.IsOverload(New: NewFD, Old: CurFD, UseMemberUsingDeclRules))
12117 continue;
12118
12119 switch (NewMVKind) {
12120 case MultiVersionKind::None:
12121 assert(OldMVKind == MultiVersionKind::TargetClones &&
12122 "Only target_clones can be omitted in subsequent declarations");
12123 break;
12124 case MultiVersionKind::Target: {
12125 const auto *CurTA = CurFD->getAttr<TargetAttr>();
12126 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
12127 NewFD->setIsMultiVersion();
12128 Redeclaration = true;
12129 OldDecl = ND;
12130 return false;
12131 }
12132
12133 ParsedTargetAttr CurParsed =
12134 S.getASTContext().getTargetInfo().parseTargetAttr(
12135 Str: CurTA->getFeaturesStr());
12136 llvm::sort(C&: CurParsed.Features);
12137 if (CurParsed == NewParsed) {
12138 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12139 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12140 NewFD->setInvalidDecl();
12141 return true;
12142 }
12143 break;
12144 }
12145 case MultiVersionKind::TargetVersion: {
12146 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12147 if (CurTVA->getName() == NewTVA->getName()) {
12148 NewFD->setIsMultiVersion();
12149 Redeclaration = true;
12150 OldDecl = ND;
12151 return false;
12152 }
12153 llvm::SmallVector<StringRef, 8> CurFeats;
12154 CurTVA->getFeatures(Out&: CurFeats);
12155 llvm::sort(C&: CurFeats);
12156
12157 if (CurFeats == NewFeats) {
12158 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12159 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12160 NewFD->setInvalidDecl();
12161 return true;
12162 }
12163 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12164 // Default
12165 if (NewFeats.empty())
12166 break;
12167
12168 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
12169 llvm::SmallVector<StringRef, 8> CurFeats;
12170 CurClones->getFeatures(Out&: CurFeats, Index: I);
12171 llvm::sort(C&: CurFeats);
12172
12173 if (CurFeats == NewFeats) {
12174 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12175 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12176 NewFD->setInvalidDecl();
12177 return true;
12178 }
12179 }
12180 }
12181 break;
12182 }
12183 case MultiVersionKind::TargetClones: {
12184 assert(NewClones && "MultiVersionKind does not match attribute type");
12185 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12186 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
12187 !std::equal(first1: CurClones->featuresStrs_begin(),
12188 last1: CurClones->featuresStrs_end(),
12189 first2: NewClones->featuresStrs_begin())) {
12190 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_target_clone_doesnt_match);
12191 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12192 NewFD->setInvalidDecl();
12193 return true;
12194 }
12195 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12196 llvm::SmallVector<StringRef, 8> CurFeats;
12197 CurTVA->getFeatures(Out&: CurFeats);
12198 llvm::sort(C&: CurFeats);
12199
12200 // Default
12201 if (CurFeats.empty())
12202 break;
12203
12204 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
12205 NewFeats.clear();
12206 NewClones->getFeatures(Out&: NewFeats, Index: I);
12207 llvm::sort(C&: NewFeats);
12208
12209 if (CurFeats == NewFeats) {
12210 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12211 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12212 NewFD->setInvalidDecl();
12213 return true;
12214 }
12215 }
12216 break;
12217 }
12218 Redeclaration = true;
12219 OldDecl = CurFD;
12220 NewFD->setIsMultiVersion();
12221 return false;
12222 }
12223 case MultiVersionKind::CPUSpecific:
12224 case MultiVersionKind::CPUDispatch: {
12225 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
12226 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
12227 // Handle CPUDispatch/CPUSpecific versions.
12228 // Only 1 CPUDispatch function is allowed, this will make it go through
12229 // the redeclaration errors.
12230 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12231 CurFD->hasAttr<CPUDispatchAttr>()) {
12232 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12233 std::equal(
12234 first1: CurCPUDisp->cpus_begin(), last1: CurCPUDisp->cpus_end(),
12235 first2: NewCPUDisp->cpus_begin(),
12236 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12237 return Cur->getName() == New->getName();
12238 })) {
12239 NewFD->setIsMultiVersion();
12240 Redeclaration = true;
12241 OldDecl = ND;
12242 return false;
12243 }
12244
12245 // If the declarations don't match, this is an error condition.
12246 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_dispatch_mismatch);
12247 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12248 NewFD->setInvalidDecl();
12249 return true;
12250 }
12251 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12252 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12253 std::equal(
12254 first1: CurCPUSpec->cpus_begin(), last1: CurCPUSpec->cpus_end(),
12255 first2: NewCPUSpec->cpus_begin(),
12256 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12257 return Cur->getName() == New->getName();
12258 })) {
12259 NewFD->setIsMultiVersion();
12260 Redeclaration = true;
12261 OldDecl = ND;
12262 return false;
12263 }
12264
12265 // Only 1 version of CPUSpecific is allowed for each CPU.
12266 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12267 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12268 if (CurII == NewII) {
12269 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_specific_multiple_defs)
12270 << NewII;
12271 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12272 NewFD->setInvalidDecl();
12273 return true;
12274 }
12275 }
12276 }
12277 }
12278 break;
12279 }
12280 }
12281 }
12282
12283 // Redeclarations of a target_clones function may omit the attribute, in which
12284 // case it will be inherited during declaration merging.
12285 if (NewMVKind == MultiVersionKind::None &&
12286 OldMVKind == MultiVersionKind::TargetClones) {
12287 NewFD->setIsMultiVersion();
12288 Redeclaration = true;
12289 OldDecl = OldFD;
12290 return false;
12291 }
12292
12293 // Else, this is simply a non-redecl case. Checking the 'value' is only
12294 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12295 // handled in the attribute adding step.
12296 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, FD: NewFD)) {
12297 NewFD->setInvalidDecl();
12298 return true;
12299 }
12300
12301 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12302 CausesMV: !OldFD->isMultiVersion(), MVKind: NewMVKind)) {
12303 NewFD->setInvalidDecl();
12304 return true;
12305 }
12306
12307 // Permit forward declarations in the case where these two are compatible.
12308 if (!OldFD->isMultiVersion()) {
12309 OldFD->setIsMultiVersion();
12310 NewFD->setIsMultiVersion();
12311 Redeclaration = true;
12312 OldDecl = OldFD;
12313 return false;
12314 }
12315
12316 NewFD->setIsMultiVersion();
12317 Redeclaration = false;
12318 OldDecl = nullptr;
12319 Previous.clear();
12320 return false;
12321}
12322
12323/// Check the validity of a mulitversion function declaration.
12324/// Also sets the multiversion'ness' of the function itself.
12325///
12326/// This sets NewFD->isInvalidDecl() to true if there was an error.
12327///
12328/// Returns true if there was an error, false otherwise.
12329static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
12330 bool &Redeclaration, NamedDecl *&OldDecl,
12331 LookupResult &Previous) {
12332 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12333
12334 // Check if FMV is disabled.
12335 if (TI.getTriple().isAArch64() && !TI.hasFeature(Feature: "fmv"))
12336 return false;
12337
12338 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12339 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12340 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12341 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12342 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12343 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12344
12345 // Main isn't allowed to become a multiversion function, however it IS
12346 // permitted to have 'main' be marked with the 'target' optimization hint,
12347 // for 'target_version' only default is allowed.
12348 if (NewFD->isMain()) {
12349 if (MVKind != MultiVersionKind::None &&
12350 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12351 !(MVKind == MultiVersionKind::TargetVersion &&
12352 NewTVA->isDefaultVersion())) {
12353 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_allowed_on_main);
12354 NewFD->setInvalidDecl();
12355 return true;
12356 }
12357 return false;
12358 }
12359
12360 // Target attribute on AArch64 is not used for multiversioning
12361 if (NewTA && TI.getTriple().isAArch64())
12362 return false;
12363
12364 // Target attribute on RISCV is not used for multiversioning
12365 if (NewTA && TI.getTriple().isRISCV())
12366 return false;
12367
12368 if (!OldDecl || !OldDecl->getAsFunction() ||
12369 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12370 DC: NewFD->getDeclContext()->getRedeclContext())) {
12371 // If there's no previous declaration, AND this isn't attempting to cause
12372 // multiversioning, this isn't an error condition.
12373 if (MVKind == MultiVersionKind::None)
12374 return false;
12375 return CheckMultiVersionFirstFunction(S, FD: NewFD);
12376 }
12377
12378 FunctionDecl *OldFD = OldDecl->getAsFunction();
12379
12380 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12381 return false;
12382
12383 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12384 // for target_clones and target_version.
12385 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12386 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
12387 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
12388 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
12389 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
12390 NewFD->setInvalidDecl();
12391 return true;
12392 }
12393
12394 if (!OldFD->isMultiVersion()) {
12395 switch (MVKind) {
12396 case MultiVersionKind::Target:
12397 case MultiVersionKind::TargetVersion:
12398 return CheckDeclarationCausesMultiVersioning(
12399 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12400 case MultiVersionKind::TargetClones:
12401 if (OldFD->isUsed(CheckUsedAttr: false)) {
12402 NewFD->setInvalidDecl();
12403 return S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
12404 }
12405 OldFD->setIsMultiVersion();
12406 break;
12407
12408 case MultiVersionKind::CPUDispatch:
12409 case MultiVersionKind::CPUSpecific:
12410 case MultiVersionKind::None:
12411 break;
12412 }
12413 }
12414
12415 // At this point, we have a multiversion function decl (in OldFD) AND an
12416 // appropriate attribute in the current function decl (unless it's allowed to
12417 // omit the attribute). Resolve that these are still compatible with previous
12418 // declarations.
12419 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12420 NewCPUSpec, NewClones, Redeclaration,
12421 OldDecl, Previous);
12422}
12423
12424static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {
12425 bool IsPure = NewFD->hasAttr<PureAttr>();
12426 bool IsConst = NewFD->hasAttr<ConstAttr>();
12427
12428 // If there are no pure or const attributes, there's nothing to check.
12429 if (!IsPure && !IsConst)
12430 return;
12431
12432 // If the function is marked both pure and const, we retain the const
12433 // attribute because it makes stronger guarantees than the pure attribute, and
12434 // we drop the pure attribute explicitly to prevent later confusion about
12435 // semantics.
12436 if (IsPure && IsConst) {
12437 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_const_attr_with_pure_attr);
12438 NewFD->dropAttrs<PureAttr>();
12439 }
12440
12441 // Constructors and destructors are functions which return void, so are
12442 // handled here as well.
12443 if (NewFD->getReturnType()->isVoidType()) {
12444 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_pure_function_returns_void)
12445 << IsConst;
12446 NewFD->dropAttrs<PureAttr, ConstAttr>();
12447 }
12448}
12449
12450bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
12451 LookupResult &Previous,
12452 bool IsMemberSpecialization,
12453 bool DeclIsDefn) {
12454 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12455 "Variably modified return types are not handled here");
12456
12457 // Determine whether the type of this function should be merged with
12458 // a previous visible declaration. This never happens for functions in C++,
12459 // and always happens in C if the previous declaration was visible.
12460 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12461 !Previous.isShadowed();
12462
12463 bool Redeclaration = false;
12464 NamedDecl *OldDecl = nullptr;
12465 bool MayNeedOverloadableChecks = false;
12466
12467 inferLifetimeCaptureByAttribute(FD: NewFD);
12468 // Merge or overload the declaration with an existing declaration of
12469 // the same name, if appropriate.
12470 if (!Previous.empty()) {
12471 // Determine whether NewFD is an overload of PrevDecl or
12472 // a declaration that requires merging. If it's an overload,
12473 // there's no more work to do here; we'll just add the new
12474 // function to the scope.
12475 if (!AllowOverloadingOfFunction(Previous, Context, New: NewFD)) {
12476 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12477 if (shouldLinkPossiblyHiddenDecl(Old: Candidate, New: NewFD)) {
12478 Redeclaration = true;
12479 OldDecl = Candidate;
12480 }
12481 } else {
12482 MayNeedOverloadableChecks = true;
12483 switch (CheckOverload(S, New: NewFD, OldDecls: Previous, OldDecl,
12484 /*NewIsUsingDecl*/ UseMemberUsingDeclRules: false)) {
12485 case OverloadKind::Match:
12486 Redeclaration = true;
12487 break;
12488
12489 case OverloadKind::NonFunction:
12490 Redeclaration = true;
12491 break;
12492
12493 case OverloadKind::Overload:
12494 Redeclaration = false;
12495 break;
12496 }
12497 }
12498 }
12499
12500 // Check for a previous extern "C" declaration with this name.
12501 if (!Redeclaration &&
12502 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewFD, Previous)) {
12503 if (!Previous.empty()) {
12504 // This is an extern "C" declaration with the same name as a previous
12505 // declaration, and thus redeclares that entity...
12506 Redeclaration = true;
12507 OldDecl = Previous.getFoundDecl();
12508 MergeTypeWithPrevious = false;
12509
12510 // ... except in the presence of __attribute__((overloadable)).
12511 if (OldDecl->hasAttr<OverloadableAttr>() ||
12512 NewFD->hasAttr<OverloadableAttr>()) {
12513 if (IsOverload(New: NewFD, Old: cast<FunctionDecl>(Val: OldDecl), UseMemberUsingDeclRules: false)) {
12514 MayNeedOverloadableChecks = true;
12515 Redeclaration = false;
12516 OldDecl = nullptr;
12517 }
12518 }
12519 }
12520 }
12521
12522 if (CheckMultiVersionFunction(S&: *this, NewFD, Redeclaration, OldDecl, Previous))
12523 return Redeclaration;
12524
12525 // PPC MMA non-pointer types are not allowed as function return types.
12526 if (Context.getTargetInfo().getTriple().isPPC64() &&
12527 PPC().CheckPPCMMAType(Type: NewFD->getReturnType(), TypeLoc: NewFD->getLocation())) {
12528 NewFD->setInvalidDecl();
12529 }
12530
12531 CheckConstPureAttributesUsage(S&: *this, NewFD);
12532
12533 // C++ [dcl.spec.auto.general]p12:
12534 // Return type deduction for a templated function with a placeholder in its
12535 // declared type occurs when the definition is instantiated even if the
12536 // function body contains a return statement with a non-type-dependent
12537 // operand.
12538 //
12539 // C++ [temp.dep.expr]p3:
12540 // An id-expression is type-dependent if it is a template-id that is not a
12541 // concept-id and is dependent; or if its terminal name is:
12542 // - [...]
12543 // - associated by name lookup with one or more declarations of member
12544 // functions of a class that is the current instantiation declared with a
12545 // return type that contains a placeholder type,
12546 // - [...]
12547 //
12548 // If this is a templated function with a placeholder in its return type,
12549 // make the placeholder type dependent since it won't be deduced until the
12550 // definition is instantiated. We do this here because it needs to happen
12551 // for implicitly instantiated member functions/member function templates.
12552 if (getLangOpts().CPlusPlus14 &&
12553 (NewFD->isDependentContext() &&
12554 NewFD->getReturnType()->isUndeducedType())) {
12555 const FunctionProtoType *FPT =
12556 NewFD->getType()->castAs<FunctionProtoType>();
12557 QualType NewReturnType = SubstAutoTypeDependent(TypeWithAuto: FPT->getReturnType());
12558 NewFD->setType(Context.getFunctionType(ResultTy: NewReturnType, Args: FPT->getParamTypes(),
12559 EPI: FPT->getExtProtoInfo()));
12560 }
12561
12562 // C++11 [dcl.constexpr]p8:
12563 // A constexpr specifier for a non-static member function that is not
12564 // a constructor declares that member function to be const.
12565 //
12566 // This needs to be delayed until we know whether this is an out-of-line
12567 // definition of a static member function.
12568 //
12569 // This rule is not present in C++1y, so we produce a backwards
12570 // compatibility warning whenever it happens in C++11.
12571 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
12572 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12573 !MD->isStatic() && !isa<CXXConstructorDecl>(Val: MD) &&
12574 !isa<CXXDestructorDecl>(Val: MD) && !MD->getMethodQualifiers().hasConst()) {
12575 CXXMethodDecl *OldMD = nullptr;
12576 if (OldDecl)
12577 OldMD = dyn_cast_or_null<CXXMethodDecl>(Val: OldDecl->getAsFunction());
12578 if (!OldMD || !OldMD->isStatic()) {
12579 const FunctionProtoType *FPT =
12580 MD->getType()->castAs<FunctionProtoType>();
12581 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12582 EPI.TypeQuals.addConst();
12583 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
12584 Args: FPT->getParamTypes(), EPI));
12585
12586 // Warn that we did this, if we're not performing template instantiation.
12587 // In that case, we'll have warned already when the template was defined.
12588 if (!inTemplateInstantiation()) {
12589 SourceLocation AddConstLoc;
12590 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
12591 .IgnoreParens().getAs<FunctionTypeLoc>())
12592 AddConstLoc = getLocForEndOfToken(Loc: FTL.getRParenLoc());
12593
12594 Diag(Loc: MD->getLocation(), DiagID: diag::warn_cxx14_compat_constexpr_not_const)
12595 << FixItHint::CreateInsertion(InsertionLoc: AddConstLoc, Code: " const");
12596 }
12597 }
12598 }
12599
12600 if (Redeclaration) {
12601 // NewFD and OldDecl represent declarations that need to be
12602 // merged.
12603 if (MergeFunctionDecl(New: NewFD, OldD&: OldDecl, S, MergeTypeWithOld: MergeTypeWithPrevious,
12604 NewDeclIsDefn: DeclIsDefn)) {
12605 NewFD->setInvalidDecl();
12606 return Redeclaration;
12607 }
12608
12609 Previous.clear();
12610 Previous.addDecl(D: OldDecl);
12611
12612 if (FunctionTemplateDecl *OldTemplateDecl =
12613 dyn_cast<FunctionTemplateDecl>(Val: OldDecl)) {
12614 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12615 FunctionTemplateDecl *NewTemplateDecl
12616 = NewFD->getDescribedFunctionTemplate();
12617 assert(NewTemplateDecl && "Template/non-template mismatch");
12618
12619 // The call to MergeFunctionDecl above may have created some state in
12620 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12621 // can add it as a redeclaration.
12622 NewTemplateDecl->mergePrevDecl(Prev: OldTemplateDecl);
12623
12624 NewFD->setPreviousDeclaration(OldFD);
12625 if (NewFD->isCXXClassMember()) {
12626 NewFD->setAccess(OldTemplateDecl->getAccess());
12627 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12628 }
12629
12630 // If this is an explicit specialization of a member that is a function
12631 // template, mark it as a member specialization.
12632 if (IsMemberSpecialization &&
12633 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12634 NewTemplateDecl->setMemberSpecialization();
12635 assert(OldTemplateDecl->isMemberSpecialization());
12636 // Explicit specializations of a member template do not inherit deleted
12637 // status from the parent member template that they are specializing.
12638 if (OldFD->isDeleted()) {
12639 // FIXME: This assert will not hold in the presence of modules.
12640 assert(OldFD->getCanonicalDecl() == OldFD);
12641 // FIXME: We need an update record for this AST mutation.
12642 OldFD->setDeletedAsWritten(D: false);
12643 }
12644 }
12645
12646 } else {
12647 if (shouldLinkDependentDeclWithPrevious(D: NewFD, PrevDecl: OldDecl)) {
12648 auto *OldFD = cast<FunctionDecl>(Val: OldDecl);
12649 // This needs to happen first so that 'inline' propagates.
12650 NewFD->setPreviousDeclaration(OldFD);
12651 if (NewFD->isCXXClassMember())
12652 NewFD->setAccess(OldFD->getAccess());
12653 }
12654 }
12655 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12656 !NewFD->getAttr<OverloadableAttr>()) {
12657 assert((Previous.empty() ||
12658 llvm::any_of(Previous,
12659 [](const NamedDecl *ND) {
12660 return ND->hasAttr<OverloadableAttr>();
12661 })) &&
12662 "Non-redecls shouldn't happen without overloadable present");
12663
12664 auto OtherUnmarkedIter = llvm::find_if(Range&: Previous, P: [](const NamedDecl *ND) {
12665 const auto *FD = dyn_cast<FunctionDecl>(Val: ND);
12666 return FD && !FD->hasAttr<OverloadableAttr>();
12667 });
12668
12669 if (OtherUnmarkedIter != Previous.end()) {
12670 Diag(Loc: NewFD->getLocation(),
12671 DiagID: diag::err_attribute_overloadable_multiple_unmarked_overloads);
12672 Diag(Loc: (*OtherUnmarkedIter)->getLocation(),
12673 DiagID: diag::note_attribute_overloadable_prev_overload)
12674 << false;
12675
12676 NewFD->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
12677 }
12678 }
12679
12680 if (LangOpts.OpenMP)
12681 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(D: NewFD);
12682
12683 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12684 SYCL().CheckSYCLEntryPointFunctionDecl(FD: NewFD);
12685
12686 if (NewFD->hasAttr<SYCLExternalAttr>())
12687 SYCL().CheckSYCLExternalFunctionDecl(FD: NewFD);
12688
12689 // Semantic checking for this function declaration (in isolation).
12690
12691 if (getLangOpts().CPlusPlus) {
12692 // C++-specific checks.
12693 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: NewFD)) {
12694 CheckConstructor(Constructor);
12695 } else if (CXXDestructorDecl *Destructor =
12696 dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
12697 // We check here for invalid destructor names.
12698 // If we have a friend destructor declaration that is dependent, we can't
12699 // diagnose right away because cases like this are still valid:
12700 // template <class T> struct A { friend T::X::~Y(); };
12701 // struct B { struct Y { ~Y(); }; using X = Y; };
12702 // template struct A<B>;
12703 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12704 (!Destructor->getFunctionObjectParameterType()->isDependentType() &&
12705 !Destructor->getDeclName().isDependentName())) {
12706 CanQualType ClassType =
12707 Context.getCanonicalTagType(TD: Destructor->getParent());
12708
12709 DeclarationName Name =
12710 Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
12711 if (NewFD->getDeclName() != Name) {
12712 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_name);
12713 NewFD->setInvalidDecl();
12714 return Redeclaration;
12715 }
12716 }
12717 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: NewFD)) {
12718 if (auto *TD = Guide->getDescribedFunctionTemplate())
12719 CheckDeductionGuideTemplate(TD);
12720
12721 // A deduction guide is not on the list of entities that can be
12722 // explicitly specialized.
12723 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12724 Diag(Loc: Guide->getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
12725 << /*explicit specialization*/ 1;
12726 }
12727
12728 // Find any virtual functions that this function overrides.
12729 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
12730 if (!Method->isFunctionTemplateSpecialization() &&
12731 !Method->getDescribedFunctionTemplate() &&
12732 Method->isCanonicalDecl()) {
12733 AddOverriddenMethods(DC: Method->getParent(), MD: Method);
12734 }
12735 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12736 // C++2a [class.virtual]p6
12737 // A virtual method shall not have a requires-clause.
12738 Diag(Loc: NewFD->getTrailingRequiresClause().ConstraintExpr->getBeginLoc(),
12739 DiagID: diag::err_constrained_virtual_method);
12740
12741 if (Method->isStatic())
12742 checkThisInStaticMemberFunctionType(Method);
12743 }
12744
12745 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: NewFD))
12746 ActOnConversionDeclarator(Conversion);
12747
12748 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12749 if (NewFD->isOverloadedOperator() &&
12750 CheckOverloadedOperatorDeclaration(FnDecl: NewFD)) {
12751 NewFD->setInvalidDecl();
12752 return Redeclaration;
12753 }
12754
12755 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12756 if (NewFD->getLiteralIdentifier() &&
12757 CheckLiteralOperatorDeclaration(FnDecl: NewFD)) {
12758 NewFD->setInvalidDecl();
12759 return Redeclaration;
12760 }
12761
12762 // In C++, check default arguments now that we have merged decls. Unless
12763 // the lexical context is the class, because in this case this is done
12764 // during delayed parsing anyway.
12765 if (!CurContext->isRecord())
12766 CheckCXXDefaultArguments(FD: NewFD);
12767
12768 // If this function is declared as being extern "C", then check to see if
12769 // the function returns a UDT (class, struct, or union type) that is not C
12770 // compatible, and if it does, warn the user.
12771 // But, issue any diagnostic on the first declaration only.
12772 if (Previous.empty() && NewFD->isExternC()) {
12773 QualType R = NewFD->getReturnType();
12774 if (R->isIncompleteType() && !R->isVoidType())
12775 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt_incomplete)
12776 << NewFD << R;
12777 else if (!R.isPODType(Context) && !R->isVoidType() &&
12778 !R->isObjCObjectPointerType())
12779 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt) << NewFD << R;
12780 }
12781
12782 // C++1z [dcl.fct]p6:
12783 // [...] whether the function has a non-throwing exception-specification
12784 // [is] part of the function type
12785 //
12786 // This results in an ABI break between C++14 and C++17 for functions whose
12787 // declared type includes an exception-specification in a parameter or
12788 // return type. (Exception specifications on the function itself are OK in
12789 // most cases, and exception specifications are not permitted in most other
12790 // contexts where they could make it into a mangling.)
12791 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12792 auto HasNoexcept = [&](QualType T) -> bool {
12793 // Strip off declarator chunks that could be between us and a function
12794 // type. We don't need to look far, exception specifications are very
12795 // restricted prior to C++17.
12796 if (auto *RT = T->getAs<ReferenceType>())
12797 T = RT->getPointeeType();
12798 else if (T->isAnyPointerType())
12799 T = T->getPointeeType();
12800 else if (auto *MPT = T->getAs<MemberPointerType>())
12801 T = MPT->getPointeeType();
12802 if (auto *FPT = T->getAs<FunctionProtoType>())
12803 if (FPT->isNothrow())
12804 return true;
12805 return false;
12806 };
12807
12808 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12809 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12810 for (QualType T : FPT->param_types())
12811 AnyNoexcept |= HasNoexcept(T);
12812 if (AnyNoexcept)
12813 Diag(Loc: NewFD->getLocation(),
12814 DiagID: diag::warn_cxx17_compat_exception_spec_in_signature)
12815 << NewFD;
12816 }
12817
12818 if (!Redeclaration && LangOpts.CUDA) {
12819 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12820 for (auto *Parm : NewFD->parameters()) {
12821 if (!Parm->getType()->isDependentType() &&
12822 Parm->hasAttr<CUDAGridConstantAttr>() &&
12823 !(IsKernel && Parm->getType().isConstQualified()))
12824 Diag(Loc: Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12825 DiagID: diag::err_cuda_grid_constant_not_allowed);
12826 }
12827 CUDA().checkTargetOverload(NewFD, Previous);
12828 }
12829 }
12830
12831 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12832 ARM().CheckSMEFunctionDefAttributes(FD: NewFD);
12833
12834 return Redeclaration;
12835}
12836
12837void Sema::CheckMain(FunctionDecl *FD, const DeclSpec &DS) {
12838 // [basic.start.main]p3
12839 // The main function shall not be declared with C linkage-specification.
12840 if (FD->isExternCContext())
12841 Diag(Loc: FD->getLocation(), DiagID: diag::ext_main_invalid_linkage_specification);
12842
12843 // C++11 [basic.start.main]p3:
12844 // A program that [...] declares main to be inline, static or
12845 // constexpr is ill-formed.
12846 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12847 // appear in a declaration of main.
12848 // static main is not an error under C99, but we should warn about it.
12849 // We accept _Noreturn main as an extension.
12850 if (FD->getStorageClass() == SC_Static)
12851 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus
12852 ? diag::err_static_main : diag::warn_static_main)
12853 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
12854 if (FD->isInlineSpecified())
12855 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_main)
12856 << FixItHint::CreateRemoval(RemoveRange: DS.getInlineSpecLoc());
12857 if (DS.isNoreturnSpecified()) {
12858 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12859 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(Loc: NoreturnLoc));
12860 Diag(Loc: NoreturnLoc, DiagID: diag::ext_noreturn_main);
12861 Diag(Loc: NoreturnLoc, DiagID: diag::note_main_remove_noreturn)
12862 << FixItHint::CreateRemoval(RemoveRange: NoreturnRange);
12863 }
12864 if (FD->isConstexpr()) {
12865 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_main)
12866 << FD->isConsteval()
12867 << FixItHint::CreateRemoval(RemoveRange: DS.getConstexprSpecLoc());
12868 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12869 }
12870
12871 if (getLangOpts().OpenCL) {
12872 Diag(Loc: FD->getLocation(), DiagID: diag::err_opencl_no_main)
12873 << FD->hasAttr<DeviceKernelAttr>();
12874 FD->setInvalidDecl();
12875 return;
12876 }
12877
12878 if (FD->hasAttr<SYCLExternalAttr>()) {
12879 Diag(Loc: FD->getLocation(), DiagID: diag::err_sycl_external_invalid_main)
12880 << FD->getAttr<SYCLExternalAttr>();
12881 FD->setInvalidDecl();
12882 return;
12883 }
12884
12885 // Functions named main in hlsl are default entries, but don't have specific
12886 // signatures they are required to conform to.
12887 if (getLangOpts().HLSL)
12888 return;
12889
12890 QualType T = FD->getType();
12891 assert(T->isFunctionType() && "function decl is not of function type");
12892 const FunctionType* FT = T->castAs<FunctionType>();
12893
12894 // Set default calling convention for main()
12895 if (FT->getCallConv() != CC_C) {
12896 FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12897 FD->setType(QualType(FT, 0));
12898 T = Context.getCanonicalType(T: FD->getType());
12899 }
12900
12901 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12902 // In C with GNU extensions we allow main() to have non-integer return
12903 // type, but we should warn about the extension, and we disable the
12904 // implicit-return-zero rule.
12905
12906 // GCC in C mode accepts qualified 'int'.
12907 if (Context.hasSameUnqualifiedType(T1: FT->getReturnType(), T2: Context.IntTy))
12908 FD->setHasImplicitReturnZero(true);
12909 else {
12910 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::ext_main_returns_nonint);
12911 SourceRange RTRange = FD->getReturnTypeSourceRange();
12912 if (RTRange.isValid())
12913 Diag(Loc: RTRange.getBegin(), DiagID: diag::note_main_change_return_type)
12914 << FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int");
12915 }
12916 } else {
12917 // In C and C++, main magically returns 0 if you fall off the end;
12918 // set the flag which tells us that.
12919 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12920
12921 // All the standards say that main() should return 'int'.
12922 if (Context.hasSameType(T1: FT->getReturnType(), T2: Context.IntTy))
12923 FD->setHasImplicitReturnZero(true);
12924 else {
12925 // Otherwise, this is just a flat-out error.
12926 SourceRange RTRange = FD->getReturnTypeSourceRange();
12927 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::err_main_returns_nonint)
12928 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int")
12929 : FixItHint());
12930 FD->setInvalidDecl(true);
12931 }
12932
12933 // [basic.start.main]p3:
12934 // A program that declares a function main that belongs to the global scope
12935 // and is attached to a named module is ill-formed.
12936 if (FD->isInNamedModule()) {
12937 const SourceLocation start = FD->getTypeSpecStartLoc();
12938 Diag(Loc: start, DiagID: diag::warn_main_in_named_module)
12939 << FixItHint::CreateInsertion(InsertionLoc: start, Code: "extern \"C++\" ", BeforePreviousInsertions: true);
12940 }
12941 }
12942
12943 // Treat protoless main() as nullary.
12944 if (isa<FunctionNoProtoType>(Val: FT)) return;
12945
12946 const FunctionProtoType* FTP = cast<const FunctionProtoType>(Val: FT);
12947 unsigned nparams = FTP->getNumParams();
12948 assert(FD->getNumParams() == nparams);
12949
12950 bool HasExtraParameters = (nparams > 3);
12951
12952 if (FTP->isVariadic()) {
12953 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variadic_main);
12954 // FIXME: if we had information about the location of the ellipsis, we
12955 // could add a FixIt hint to remove it as a parameter.
12956 }
12957
12958 // Darwin passes an undocumented fourth argument of type char**. If
12959 // other platforms start sprouting these, the logic below will start
12960 // getting shifty.
12961 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12962 HasExtraParameters = false;
12963
12964 if (HasExtraParameters) {
12965 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_surplus_args) << nparams;
12966 FD->setInvalidDecl(true);
12967 nparams = 3;
12968 }
12969
12970 // FIXME: a lot of the following diagnostics would be improved
12971 // if we had some location information about types.
12972
12973 QualType CharPP =
12974 Context.getPointerType(T: Context.getPointerType(T: Context.CharTy));
12975 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12976
12977 for (unsigned i = 0; i < nparams; ++i) {
12978 QualType AT = FTP->getParamType(i);
12979
12980 bool mismatch = true;
12981
12982 if (Context.hasSameUnqualifiedType(T1: AT, T2: Expected[i]))
12983 mismatch = false;
12984 else if (Expected[i] == CharPP) {
12985 // As an extension, the following forms are okay:
12986 // char const **
12987 // char const * const *
12988 // char * const *
12989
12990 QualifierCollector qs;
12991 const PointerType* PT;
12992 if ((PT = qs.strip(type: AT)->getAs<PointerType>()) &&
12993 (PT = qs.strip(type: PT->getPointeeType())->getAs<PointerType>()) &&
12994 Context.hasSameType(T1: QualType(qs.strip(type: PT->getPointeeType()), 0),
12995 T2: Context.CharTy)) {
12996 qs.removeConst();
12997 mismatch = !qs.empty();
12998 }
12999 }
13000
13001 if (mismatch) {
13002 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_arg_wrong) << i << Expected[i];
13003 // TODO: suggest replacing given type with expected type
13004 FD->setInvalidDecl(true);
13005 }
13006 }
13007
13008 if (nparams == 1 && !FD->isInvalidDecl()) {
13009 Diag(Loc: FD->getLocation(), DiagID: diag::warn_main_one_arg);
13010 }
13011
13012 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
13013 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
13014 FD->setInvalidDecl();
13015 }
13016}
13017
13018static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
13019
13020 // Default calling convention for main and wmain is __cdecl
13021 if (FD->getName() == "main" || FD->getName() == "wmain")
13022 return false;
13023
13024 // Default calling convention for MinGW and Cygwin is __cdecl
13025 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
13026 if (T.isOSCygMing())
13027 return false;
13028
13029 // Default calling convention for WinMain, wWinMain and DllMain
13030 // is __stdcall on 32 bit Windows
13031 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
13032 return true;
13033
13034 return false;
13035}
13036
13037void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
13038 QualType T = FD->getType();
13039 assert(T->isFunctionType() && "function decl is not of function type");
13040 const FunctionType *FT = T->castAs<FunctionType>();
13041
13042 // Set an implicit return of 'zero' if the function can return some integral,
13043 // enumeration, pointer or nullptr type.
13044 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
13045 FT->getReturnType()->isAnyPointerType() ||
13046 FT->getReturnType()->isNullPtrType())
13047 // DllMain is exempt because a return value of zero means it failed.
13048 if (FD->getName() != "DllMain")
13049 FD->setHasImplicitReturnZero(true);
13050
13051 // Explicitly specified calling conventions are applied to MSVC entry points
13052 if (!hasExplicitCallingConv(T)) {
13053 if (isDefaultStdCall(FD, S&: *this)) {
13054 if (FT->getCallConv() != CC_X86StdCall) {
13055 FT = Context.adjustFunctionType(
13056 Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_X86StdCall));
13057 FD->setType(QualType(FT, 0));
13058 }
13059 } else if (FT->getCallConv() != CC_C) {
13060 FT = Context.adjustFunctionType(Fn: FT,
13061 EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
13062 FD->setType(QualType(FT, 0));
13063 }
13064 }
13065
13066 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
13067 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
13068 FD->setInvalidDecl();
13069 }
13070}
13071
13072bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {
13073 // FIXME: Need strict checking. In C89, we need to check for
13074 // any assignment, increment, decrement, function-calls, or
13075 // commas outside of a sizeof. In C99, it's the same list,
13076 // except that the aforementioned are allowed in unevaluated
13077 // expressions. Everything else falls under the
13078 // "may accept other forms of constant expressions" exception.
13079 //
13080 // Regular C++ code will not end up here (exceptions: language extensions,
13081 // OpenCL C++ etc), so the constant expression rules there don't matter.
13082 if (Init->isValueDependent()) {
13083 assert(Init->containsErrors() &&
13084 "Dependent code should only occur in error-recovery path.");
13085 return true;
13086 }
13087 const Expr *Culprit;
13088 if (Init->isConstantInitializer(Ctx&: Context, /*ForRef=*/false, Culprit: &Culprit))
13089 return false;
13090
13091 // The culprit reported by isConstantInitializer() may be wrapped in implicit
13092 // casts and parentheses that it does not look through: under ARC an
13093 // object-pointer initializer is an `ImplicitCastExpr
13094 // <ARCReclaimReturnedObject>`, an `id`-typed (or otherwise differently-typed)
13095 // variable adds an `ImplicitCastExpr <BitCast>` on top, and a parenthesized
13096 // initializer such as `(@{...})` adds a `ParenExpr`. Strip all of these so
13097 // the ObjC-specific classification and per-element reporting below can see
13098 // the underlying literal regardless of how it is wrapped.
13099 const Expr *CulpritLiteral = Culprit->IgnoreParenImpCasts();
13100
13101 // Emit ObjC-specific diagnostics for non-constant literals at file scope.
13102 if (getLangOpts().ObjCConstantLiterals &&
13103 isa<ObjCObjectLiteral>(Val: CulpritLiteral)) {
13104
13105 // For collection literals, iterate the elements to point at the specific
13106 // offender. These per-element checks mirror the constant-initializer rules
13107 // applied when the literal was built (see SemaObjC::BuildObjCArrayLiteral
13108 // and SemaObjC::BuildObjCDictionaryLiteral): each element must itself be a
13109 // constant object literal, and dictionary keys must additionally be string
13110 // literals. Elements, keys and values are wrapped in an implicit BitCast to
13111 // `id`, so the isa<> classification is done on the unwrapped expression.
13112 if (const auto *ALE = dyn_cast<ObjCArrayLiteral>(Val: CulpritLiteral)) {
13113 for (const Expr *Elm : ALE->elements()) {
13114 if (!isa<ObjCObjectLiteral>(Val: Elm->IgnoreImpCasts()) ||
13115 !Elm->isConstantInitializer(Ctx&: Context)) {
13116 Diag(Loc: Elm->getExprLoc(),
13117 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13118 << ObjC().CheckLiteralKind(FromE: Init) << Elm->getSourceRange();
13119 return true;
13120 }
13121 }
13122 }
13123
13124 if (const auto *DLE = dyn_cast<ObjCDictionaryLiteral>(Val: CulpritLiteral)) {
13125 for (size_t I = 0, N = DLE->getNumElements(); I != N; ++I) {
13126 const ObjCDictionaryElement Elm = DLE->getKeyValueElement(Index: I);
13127
13128 // Keys must be constant string literals.
13129 if (!isa<ObjCStringLiteral>(Val: Elm.Key->IgnoreImpCasts()) ||
13130 !Elm.Key->isConstantInitializer(Ctx&: Context)) {
13131 Diag(Loc: Elm.Key->getExprLoc(),
13132 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13133 << ObjC().CheckLiteralKind(FromE: Init) << Elm.Key->getSourceRange();
13134 return true;
13135 }
13136
13137 // Values must be constant object literals.
13138 if (!isa<ObjCObjectLiteral>(Val: Elm.Value->IgnoreImpCasts()) ||
13139 !Elm.Value->isConstantInitializer(Ctx&: Context)) {
13140 Diag(Loc: Elm.Value->getExprLoc(),
13141 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13142 << ObjC().CheckLiteralKind(FromE: Init) << Elm.Value->getSourceRange();
13143 return true;
13144 }
13145 }
13146 }
13147
13148 Diag(Loc: CulpritLiteral->getExprLoc(),
13149 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13150 << ObjC().CheckLiteralKind(FromE: Init) << CulpritLiteral->getSourceRange();
13151 return true;
13152 }
13153
13154 Diag(Loc: Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
13155 return true;
13156}
13157
13158namespace {
13159 // Visits an initialization expression to see if OrigDecl is evaluated in
13160 // its own initialization and throws a warning if it does.
13161 class SelfReferenceChecker
13162 : public EvaluatedExprVisitor<SelfReferenceChecker> {
13163 Sema &S;
13164 Decl *OrigDecl;
13165 bool isRecordType;
13166 bool isPODType;
13167 bool isReferenceType;
13168 bool isInCXXOperatorCall;
13169
13170 bool isInitList;
13171 llvm::SmallVector<unsigned, 4> InitFieldIndex;
13172
13173 public:
13174 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
13175
13176 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
13177 S(S), OrigDecl(OrigDecl) {
13178 isPODType = false;
13179 isRecordType = false;
13180 isReferenceType = false;
13181 isInCXXOperatorCall = false;
13182 isInitList = false;
13183 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: OrigDecl)) {
13184 isPODType = VD->getType().isPODType(Context: S.Context);
13185 isRecordType = VD->getType()->isRecordType();
13186 isReferenceType = VD->getType()->isReferenceType();
13187 }
13188 }
13189
13190 // For most expressions, just call the visitor. For initializer lists,
13191 // track the index of the field being initialized since fields are
13192 // initialized in order allowing use of previously initialized fields.
13193 void CheckExpr(Expr *E) {
13194 InitListExpr *InitList = dyn_cast<InitListExpr>(Val: E);
13195 if (!InitList) {
13196 Visit(S: E);
13197 return;
13198 }
13199
13200 // Track and increment the index here.
13201 isInitList = true;
13202 InitFieldIndex.push_back(Elt: 0);
13203 for (auto *Child : InitList->children()) {
13204 CheckExpr(E: cast<Expr>(Val: Child));
13205 ++InitFieldIndex.back();
13206 }
13207 InitFieldIndex.pop_back();
13208 }
13209
13210 // Returns true if MemberExpr is checked and no further checking is needed.
13211 // Returns false if additional checking is required.
13212 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
13213 llvm::SmallVector<FieldDecl*, 4> Fields;
13214 Expr *Base = E;
13215 bool ReferenceField = false;
13216
13217 // Get the field members used.
13218 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13219 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
13220 if (!FD)
13221 return false;
13222 Fields.push_back(Elt: FD);
13223 if (FD->getType()->isReferenceType())
13224 ReferenceField = true;
13225 Base = ME->getBase()->IgnoreParenImpCasts();
13226 }
13227
13228 // Keep checking only if the base Decl is the same.
13229 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base);
13230 if (!DRE || DRE->getDecl() != OrigDecl)
13231 return false;
13232
13233 // A reference field can be bound to an unininitialized field.
13234 if (CheckReference && !ReferenceField)
13235 return true;
13236
13237 // Convert FieldDecls to their index number.
13238 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
13239 for (const FieldDecl *I : llvm::reverse(C&: Fields))
13240 UsedFieldIndex.push_back(Elt: I->getFieldIndex());
13241
13242 // See if a warning is needed by checking the first difference in index
13243 // numbers. If field being used has index less than the field being
13244 // initialized, then the use is safe.
13245 for (auto UsedIter = UsedFieldIndex.begin(),
13246 UsedEnd = UsedFieldIndex.end(),
13247 OrigIter = InitFieldIndex.begin(),
13248 OrigEnd = InitFieldIndex.end();
13249 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
13250 if (*UsedIter < *OrigIter)
13251 return true;
13252 if (*UsedIter > *OrigIter)
13253 break;
13254 }
13255
13256 // TODO: Add a different warning which will print the field names.
13257 HandleDeclRefExpr(DRE);
13258 return true;
13259 }
13260
13261 // For most expressions, the cast is directly above the DeclRefExpr.
13262 // For conditional operators, the cast can be outside the conditional
13263 // operator if both expressions are DeclRefExpr's.
13264 void HandleValue(Expr *E) {
13265 E = E->IgnoreParens();
13266 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Val: E)) {
13267 HandleDeclRefExpr(DRE);
13268 return;
13269 }
13270
13271 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
13272 Visit(S: CO->getCond());
13273 HandleValue(E: CO->getTrueExpr());
13274 HandleValue(E: CO->getFalseExpr());
13275 return;
13276 }
13277
13278 if (BinaryConditionalOperator *BCO =
13279 dyn_cast<BinaryConditionalOperator>(Val: E)) {
13280 Visit(S: BCO->getCond());
13281 HandleValue(E: BCO->getFalseExpr());
13282 return;
13283 }
13284
13285 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
13286 if (Expr *SE = OVE->getSourceExpr())
13287 HandleValue(E: SE);
13288 return;
13289 }
13290
13291 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
13292 if (BO->getOpcode() == BO_Comma) {
13293 Visit(S: BO->getLHS());
13294 HandleValue(E: BO->getRHS());
13295 return;
13296 }
13297 }
13298
13299 if (isa<MemberExpr>(Val: E)) {
13300 if (isInitList) {
13301 if (CheckInitListMemberExpr(E: cast<MemberExpr>(Val: E),
13302 CheckReference: false /*CheckReference*/))
13303 return;
13304 }
13305
13306 Expr *Base = E->IgnoreParenImpCasts();
13307 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13308 // Check for static member variables and don't warn on them.
13309 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13310 return;
13311 Base = ME->getBase()->IgnoreParenImpCasts();
13312 }
13313 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base))
13314 HandleDeclRefExpr(DRE);
13315 return;
13316 }
13317
13318 Visit(S: E);
13319 }
13320
13321 // Reference types not handled in HandleValue are handled here since all
13322 // uses of references are bad, not just r-value uses.
13323 void VisitDeclRefExpr(DeclRefExpr *E) {
13324 if (isReferenceType)
13325 HandleDeclRefExpr(DRE: E);
13326 }
13327
13328 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13329 if (E->getCastKind() == CK_LValueToRValue) {
13330 HandleValue(E: E->getSubExpr());
13331 return;
13332 }
13333
13334 Inherited::VisitImplicitCastExpr(S: E);
13335 }
13336
13337 void VisitMemberExpr(MemberExpr *E) {
13338 if (isInitList) {
13339 if (CheckInitListMemberExpr(E, CheckReference: true /*CheckReference*/))
13340 return;
13341 }
13342
13343 // Don't warn on arrays since they can be treated as pointers.
13344 if (E->getType()->canDecayToPointerType()) return;
13345
13346 // Warn when a non-static method call is followed by non-static member
13347 // field accesses, which is followed by a DeclRefExpr.
13348 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl());
13349 bool Warn = (MD && !MD->isStatic());
13350 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13351 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13352 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13353 Warn = false;
13354 Base = ME->getBase()->IgnoreParenImpCasts();
13355 }
13356
13357 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base)) {
13358 if (Warn)
13359 HandleDeclRefExpr(DRE);
13360 return;
13361 }
13362
13363 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13364 // Visit that expression.
13365 Visit(S: Base);
13366 }
13367
13368 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13369 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13370 Expr *Callee = E->getCallee();
13371
13372 if (isa<UnresolvedLookupExpr>(Val: Callee))
13373 return Inherited::VisitCXXOperatorCallExpr(S: E);
13374
13375 Visit(S: Callee);
13376 for (auto Arg: E->arguments())
13377 HandleValue(E: Arg->IgnoreParenImpCasts());
13378 }
13379
13380 void VisitLambdaExpr(LambdaExpr *E) {
13381 if (!isInCXXOperatorCall) {
13382 Inherited::VisitLambdaExpr(LE: E);
13383 return;
13384 }
13385
13386 for (Expr *Init : E->capture_inits())
13387 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: Init))
13388 HandleDeclRefExpr(DRE);
13389 else if (Init)
13390 Visit(S: Init);
13391 }
13392
13393 void VisitUnaryOperator(UnaryOperator *E) {
13394 // For POD record types, addresses of its own members are well-defined.
13395 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13396 isa<MemberExpr>(Val: E->getSubExpr()->IgnoreParens())) {
13397 if (!isPODType)
13398 HandleValue(E: E->getSubExpr());
13399 return;
13400 }
13401
13402 if (E->isIncrementDecrementOp()) {
13403 HandleValue(E: E->getSubExpr());
13404 return;
13405 }
13406
13407 Inherited::VisitUnaryOperator(S: E);
13408 }
13409
13410 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13411
13412 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13413 if (E->getConstructor()->isCopyConstructor()) {
13414 Expr *ArgExpr = E->getArg(Arg: 0);
13415 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
13416 if (ILE->getNumInits() == 1)
13417 ArgExpr = ILE->getInit(Init: 0);
13418 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
13419 if (ICE->getCastKind() == CK_NoOp)
13420 ArgExpr = ICE->getSubExpr();
13421 HandleValue(E: ArgExpr);
13422 return;
13423 }
13424 Inherited::VisitCXXConstructExpr(S: E);
13425 }
13426
13427 void VisitCallExpr(CallExpr *E) {
13428 // Treat std::move as a use.
13429 if (E->isCallToStdMove()) {
13430 HandleValue(E: E->getArg(Arg: 0));
13431 return;
13432 }
13433
13434 Inherited::VisitCallExpr(CE: E);
13435 }
13436
13437 void VisitBinaryOperator(BinaryOperator *E) {
13438 if (E->isCompoundAssignmentOp()) {
13439 HandleValue(E: E->getLHS());
13440 Visit(S: E->getRHS());
13441 return;
13442 }
13443
13444 Inherited::VisitBinaryOperator(S: E);
13445 }
13446
13447 // A custom visitor for BinaryConditionalOperator is needed because the
13448 // regular visitor would check the condition and true expression separately
13449 // but both point to the same place giving duplicate diagnostics.
13450 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13451 Visit(S: E->getCond());
13452 Visit(S: E->getFalseExpr());
13453 }
13454
13455 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13456 Decl* ReferenceDecl = DRE->getDecl();
13457 if (OrigDecl != ReferenceDecl) return;
13458 unsigned diag;
13459 if (isReferenceType) {
13460 diag = diag::warn_uninit_self_reference_in_reference_init;
13461 } else if (cast<VarDecl>(Val: OrigDecl)->isStaticLocal()) {
13462 diag = diag::warn_static_self_reference_in_init;
13463 } else if (isa<TranslationUnitDecl>(Val: OrigDecl->getDeclContext()) ||
13464 isa<NamespaceDecl>(Val: OrigDecl->getDeclContext()) ||
13465 DRE->getDecl()->getType()->isRecordType()) {
13466 diag = diag::warn_uninit_self_reference_in_init;
13467 } else {
13468 // Local variables will be handled by the CFG analysis.
13469 return;
13470 }
13471
13472 S.DiagRuntimeBehavior(Loc: DRE->getBeginLoc(), Statement: DRE,
13473 PD: S.PDiag(DiagID: diag)
13474 << DRE->getDecl() << OrigDecl->getLocation()
13475 << DRE->getSourceRange());
13476 }
13477 };
13478
13479 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13480 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13481 bool DirectInit) {
13482 // Parameters arguments are occassionially constructed with itself,
13483 // for instance, in recursive functions. Skip them.
13484 if (isa<ParmVarDecl>(Val: OrigDecl))
13485 return;
13486
13487 // Skip checking for file-scope constexpr variables - constant evaluation
13488 // will produce appropriate errors without needing runtime diagnostics.
13489 // Local constexpr should still emit runtime warnings.
13490 if (auto *VD = dyn_cast<VarDecl>(Val: OrigDecl);
13491 VD && VD->isConstexpr() && VD->isFileVarDecl())
13492 return;
13493
13494 E = E->IgnoreParens();
13495
13496 // Skip checking T a = a where T is not a record or reference type.
13497 // Doing so is a way to silence uninitialized warnings.
13498 if (!DirectInit && !cast<VarDecl>(Val: OrigDecl)->getType()->isRecordType())
13499 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
13500 if (ICE->getCastKind() == CK_LValueToRValue)
13501 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ICE->getSubExpr()))
13502 if (DRE->getDecl() == OrigDecl)
13503 return;
13504
13505 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13506 }
13507} // end anonymous namespace
13508
13509namespace {
13510 // Simple wrapper to add the name of a variable or (if no variable is
13511 // available) a DeclarationName into a diagnostic.
13512 struct VarDeclOrName {
13513 VarDecl *VDecl;
13514 DeclarationName Name;
13515
13516 friend const Sema::SemaDiagnosticBuilder &
13517 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13518 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13519 }
13520 };
13521} // end anonymous namespace
13522
13523QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
13524 DeclarationName Name, QualType Type,
13525 TypeSourceInfo *TSI,
13526 SourceRange Range, bool DirectInit,
13527 Expr *Init) {
13528 bool IsInitCapture = !VDecl;
13529 assert((!VDecl || !VDecl->isInitCapture()) &&
13530 "init captures are expected to be deduced prior to initialization");
13531
13532 VarDeclOrName VN{.VDecl: VDecl, .Name: Name};
13533
13534 DeducedType *Deduced = Type->getContainedDeducedType();
13535 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13536
13537 // Diagnose auto array declarations in C23, unless it's a supported extension.
13538 if (getLangOpts().C23 && Type->isArrayType() &&
13539 !isa_and_present<StringLiteral, InitListExpr>(Val: Init)) {
13540 Diag(Loc: Range.getBegin(), DiagID: diag::err_auto_not_allowed)
13541 << (int)Deduced->getContainedAutoType()->getKeyword()
13542 << /*in array decl*/ 23 << Range;
13543 return QualType();
13544 }
13545
13546 // C++11 [dcl.spec.auto]p3
13547 if (!Init) {
13548 assert(VDecl && "no init for init capture deduction?");
13549
13550 // Except for class argument deduction, and then for an initializing
13551 // declaration only, i.e. no static at class scope or extern.
13552 if (!isa<DeducedTemplateSpecializationType>(Val: Deduced) ||
13553 VDecl->hasExternalStorage() ||
13554 VDecl->isStaticDataMember()) {
13555 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_auto_var_requires_init)
13556 << VDecl->getDeclName() << Type;
13557 return QualType();
13558 }
13559 }
13560
13561 ArrayRef<Expr*> DeduceInits;
13562 if (Init)
13563 DeduceInits = Init;
13564
13565 auto *PL = dyn_cast_if_present<ParenListExpr>(Val: Init);
13566 if (DirectInit && PL)
13567 DeduceInits = PL->exprs();
13568
13569 if (isa<DeducedTemplateSpecializationType>(Val: Deduced)) {
13570 assert(VDecl && "non-auto type for init capture deduction?");
13571 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13572 InitializationKind Kind = InitializationKind::CreateForInit(
13573 Loc: VDecl->getLocation(), DirectInit, Init);
13574 // FIXME: Initialization should not be taking a mutable list of inits.
13575 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13576 return DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind,
13577 Init: InitsCopy);
13578 }
13579
13580 if (DirectInit) {
13581 if (auto *IL = dyn_cast<InitListExpr>(Val: Init))
13582 DeduceInits = IL->inits();
13583 }
13584
13585 // Deduction only works if we have exactly one source expression.
13586 if (DeduceInits.empty()) {
13587 // It isn't possible to write this directly, but it is possible to
13588 // end up in this situation with "auto x(some_pack...);"
13589 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13590 ? diag::err_init_capture_no_expression
13591 : diag::err_auto_var_init_no_expression)
13592 << VN << Type << Range;
13593 return QualType();
13594 }
13595
13596 if (DeduceInits.size() > 1) {
13597 Diag(Loc: DeduceInits[1]->getBeginLoc(),
13598 DiagID: IsInitCapture ? diag::err_init_capture_multiple_expressions
13599 : diag::err_auto_var_init_multiple_expressions)
13600 << VN << Type << Range;
13601 return QualType();
13602 }
13603
13604 Expr *DeduceInit = DeduceInits[0];
13605 if (DirectInit && isa<InitListExpr>(Val: DeduceInit)) {
13606 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13607 ? diag::err_init_capture_paren_braces
13608 : diag::err_auto_var_init_paren_braces)
13609 << isa<InitListExpr>(Val: Init) << VN << Type << Range;
13610 return QualType();
13611 }
13612
13613 // Expressions default to 'id' when we're in a debugger.
13614 bool DefaultedAnyToId = false;
13615 if (getLangOpts().DebuggerCastResultToId &&
13616 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13617 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13618 if (Result.isInvalid()) {
13619 return QualType();
13620 }
13621 Init = Result.get();
13622 DefaultedAnyToId = true;
13623 }
13624
13625 // C++ [dcl.decomp]p1:
13626 // If the assignment-expression [...] has array type A and no ref-qualifier
13627 // is present, e has type cv A
13628 if (VDecl && isa<DecompositionDecl>(Val: VDecl) &&
13629 Context.hasSameUnqualifiedType(T1: Type, T2: Context.getAutoDeductType()) &&
13630 DeduceInit->getType()->isConstantArrayType())
13631 return Context.getQualifiedType(T: DeduceInit->getType(),
13632 Qs: Type.getQualifiers());
13633
13634 QualType DeducedType;
13635 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13636 TemplateDeductionResult Result =
13637 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeduceInit, Result&: DeducedType, Info);
13638 if (Result != TemplateDeductionResult::Success &&
13639 Result != TemplateDeductionResult::AlreadyDiagnosed) {
13640 if (!IsInitCapture)
13641 DiagnoseAutoDeductionFailure(VDecl, Init: DeduceInit);
13642 else if (isa<InitListExpr>(Val: Init))
13643 Diag(Loc: Range.getBegin(),
13644 DiagID: diag::err_init_capture_deduction_failure_from_init_list)
13645 << VN
13646 << (DeduceInit->getType().isNull() ? TSI->getType()
13647 : DeduceInit->getType())
13648 << DeduceInit->getSourceRange();
13649 else
13650 Diag(Loc: Range.getBegin(), DiagID: diag::err_init_capture_deduction_failure)
13651 << VN << TSI->getType()
13652 << (DeduceInit->getType().isNull() ? TSI->getType()
13653 : DeduceInit->getType())
13654 << DeduceInit->getSourceRange();
13655 }
13656
13657 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13658 // 'id' instead of a specific object type prevents most of our usual
13659 // checks.
13660 // We only want to warn outside of template instantiations, though:
13661 // inside a template, the 'id' could have come from a parameter.
13662 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13663 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13664 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13665 Diag(Loc, DiagID: diag::warn_auto_var_is_id) << VN << Range;
13666 }
13667
13668 return DeducedType;
13669}
13670
13671bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13672 Expr *Init) {
13673 assert(!Init || !Init->containsErrors());
13674 QualType DeducedType = deduceVarTypeFromInitializer(
13675 VDecl, Name: VDecl->getDeclName(), Type: VDecl->getType(), TSI: VDecl->getTypeSourceInfo(),
13676 Range: VDecl->getSourceRange(), DirectInit, Init);
13677 if (DeducedType.isNull()) {
13678 VDecl->setInvalidDecl();
13679 return true;
13680 }
13681
13682 VDecl->setType(DeducedType);
13683 assert(VDecl->isLinkageValid());
13684
13685 // In ARC, infer lifetime.
13686 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: VDecl))
13687 VDecl->setInvalidDecl();
13688
13689 if (getLangOpts().OpenCL)
13690 deduceOpenCLAddressSpace(Var: VDecl);
13691
13692 if (getLangOpts().HLSL)
13693 HLSL().deduceAddressSpace(Decl: VDecl);
13694
13695 // If this is a redeclaration, check that the type we just deduced matches
13696 // the previously declared type.
13697 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13698 // We never need to merge the type, because we cannot form an incomplete
13699 // array of auto, nor deduce such a type.
13700 MergeVarDeclTypes(New: VDecl, Old, /*MergeTypeWithPrevious*/ MergeTypeWithOld: false);
13701 }
13702
13703 // Check the deduced type is valid for a variable declaration.
13704 CheckVariableDeclarationType(NewVD: VDecl);
13705 return VDecl->isInvalidDecl();
13706}
13707
13708void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13709 SourceLocation Loc) {
13710 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Init))
13711 Init = EWC->getSubExpr();
13712
13713 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init))
13714 Init = CE->getSubExpr();
13715
13716 QualType InitType = Init->getType();
13717 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13718 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13719 "shouldn't be called if type doesn't have a non-trivial C struct");
13720 if (auto *ILE = dyn_cast<InitListExpr>(Val: Init)) {
13721 for (auto *I : ILE->inits()) {
13722 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13723 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13724 continue;
13725 SourceLocation SL = I->getExprLoc();
13726 checkNonTrivialCUnionInInitializer(Init: I, Loc: SL.isValid() ? SL : Loc);
13727 }
13728 return;
13729 }
13730
13731 if (isa<ImplicitValueInitExpr>(Val: Init)) {
13732 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13733 checkNonTrivialCUnion(QT: InitType, Loc,
13734 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
13735 NonTrivialKind: NTCUK_Init);
13736 } else {
13737 // Assume all other explicit initializers involving copying some existing
13738 // object.
13739 // TODO: ignore any explicit initializers where we can guarantee
13740 // copy-elision.
13741 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13742 checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NonTrivialCUnionContext::CopyInit,
13743 NonTrivialKind: NTCUK_Copy);
13744 }
13745}
13746
13747namespace {
13748
13749bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13750 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13751 // in the source code or implicitly by the compiler if it is in a union
13752 // defined in a system header and has non-trivial ObjC ownership
13753 // qualifications. We don't want those fields to participate in determining
13754 // whether the containing union is non-trivial.
13755 return FD->hasAttr<UnavailableAttr>();
13756}
13757
13758struct DiagNonTrivalCUnionDefaultInitializeVisitor
13759 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13760 void> {
13761 using Super =
13762 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13763 void>;
13764
13765 DiagNonTrivalCUnionDefaultInitializeVisitor(
13766 QualType OrigTy, SourceLocation OrigLoc,
13767 NonTrivialCUnionContext UseContext, Sema &S)
13768 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13769
13770 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13771 const FieldDecl *FD, bool InNonTrivialUnion) {
13772 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13773 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13774 Args&: InNonTrivialUnion);
13775 return Super::visitWithKind(PDIK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13776 }
13777
13778 void visitARCStrong(QualType QT, const FieldDecl *FD,
13779 bool InNonTrivialUnion) {
13780 if (InNonTrivialUnion)
13781 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13782 << 1 << 0 << QT << FD->getName();
13783 }
13784
13785 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13786 if (InNonTrivialUnion)
13787 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13788 << 1 << 0 << QT << FD->getName();
13789 }
13790
13791 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13792 const auto *RD = QT->castAsRecordDecl();
13793 if (RD->isUnion()) {
13794 if (OrigLoc.isValid()) {
13795 bool IsUnion = false;
13796 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13797 IsUnion = OrigRD->isUnion();
13798 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13799 << 0 << OrigTy << IsUnion << UseContext;
13800 // Reset OrigLoc so that this diagnostic is emitted only once.
13801 OrigLoc = SourceLocation();
13802 }
13803 InNonTrivialUnion = true;
13804 }
13805
13806 if (InNonTrivialUnion)
13807 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13808 << 0 << 0 << QT.getUnqualifiedType() << "";
13809
13810 for (const FieldDecl *FD : RD->fields())
13811 if (!shouldIgnoreForRecordTriviality(FD))
13812 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13813 }
13814
13815 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13816
13817 // The non-trivial C union type or the struct/union type that contains a
13818 // non-trivial C union.
13819 QualType OrigTy;
13820 SourceLocation OrigLoc;
13821 NonTrivialCUnionContext UseContext;
13822 Sema &S;
13823};
13824
13825struct DiagNonTrivalCUnionDestructedTypeVisitor
13826 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13827 using Super =
13828 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13829
13830 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13831 SourceLocation OrigLoc,
13832 NonTrivialCUnionContext UseContext,
13833 Sema &S)
13834 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13835
13836 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13837 const FieldDecl *FD, bool InNonTrivialUnion) {
13838 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13839 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13840 Args&: InNonTrivialUnion);
13841 return Super::visitWithKind(DK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13842 }
13843
13844 void visitARCStrong(QualType QT, const FieldDecl *FD,
13845 bool InNonTrivialUnion) {
13846 if (InNonTrivialUnion)
13847 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13848 << 1 << 1 << QT << FD->getName();
13849 }
13850
13851 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13852 if (InNonTrivialUnion)
13853 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13854 << 1 << 1 << QT << FD->getName();
13855 }
13856
13857 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13858 const auto *RD = QT->castAsRecordDecl();
13859 if (RD->isUnion()) {
13860 if (OrigLoc.isValid()) {
13861 bool IsUnion = false;
13862 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13863 IsUnion = OrigRD->isUnion();
13864 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13865 << 1 << OrigTy << IsUnion << UseContext;
13866 // Reset OrigLoc so that this diagnostic is emitted only once.
13867 OrigLoc = SourceLocation();
13868 }
13869 InNonTrivialUnion = true;
13870 }
13871
13872 if (InNonTrivialUnion)
13873 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13874 << 0 << 1 << QT.getUnqualifiedType() << "";
13875
13876 for (const FieldDecl *FD : RD->fields())
13877 if (!shouldIgnoreForRecordTriviality(FD))
13878 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13879 }
13880
13881 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13882 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13883 bool InNonTrivialUnion) {}
13884
13885 // The non-trivial C union type or the struct/union type that contains a
13886 // non-trivial C union.
13887 QualType OrigTy;
13888 SourceLocation OrigLoc;
13889 NonTrivialCUnionContext UseContext;
13890 Sema &S;
13891};
13892
13893struct DiagNonTrivalCUnionCopyVisitor
13894 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13895 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13896
13897 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13898 NonTrivialCUnionContext UseContext, Sema &S)
13899 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13900
13901 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13902 const FieldDecl *FD, bool InNonTrivialUnion) {
13903 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13904 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13905 Args&: InNonTrivialUnion);
13906 return Super::visitWithKind(PCK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13907 }
13908
13909 void visitARCStrong(QualType QT, const FieldDecl *FD,
13910 bool InNonTrivialUnion) {
13911 if (InNonTrivialUnion)
13912 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13913 << 1 << 2 << QT << FD->getName();
13914 }
13915
13916 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13917 if (InNonTrivialUnion)
13918 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13919 << 1 << 2 << QT << FD->getName();
13920 }
13921
13922 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13923 const auto *RD = QT->castAsRecordDecl();
13924 if (RD->isUnion()) {
13925 if (OrigLoc.isValid()) {
13926 bool IsUnion = false;
13927 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13928 IsUnion = OrigRD->isUnion();
13929 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13930 << 2 << OrigTy << IsUnion << UseContext;
13931 // Reset OrigLoc so that this diagnostic is emitted only once.
13932 OrigLoc = SourceLocation();
13933 }
13934 InNonTrivialUnion = true;
13935 }
13936
13937 if (InNonTrivialUnion)
13938 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13939 << 0 << 2 << QT.getUnqualifiedType() << "";
13940
13941 for (const FieldDecl *FD : RD->fields())
13942 if (!shouldIgnoreForRecordTriviality(FD))
13943 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13944 }
13945
13946 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13947 if (InNonTrivialUnion)
13948 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13949 << 1 << 2 << QT << FD->getName();
13950 }
13951
13952 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13953 const FieldDecl *FD, bool InNonTrivialUnion) {}
13954 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13955 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13956 bool InNonTrivialUnion) {}
13957
13958 // The non-trivial C union type or the struct/union type that contains a
13959 // non-trivial C union.
13960 QualType OrigTy;
13961 SourceLocation OrigLoc;
13962 NonTrivialCUnionContext UseContext;
13963 Sema &S;
13964};
13965
13966} // namespace
13967
13968void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13969 NonTrivialCUnionContext UseContext,
13970 unsigned NonTrivialKind) {
13971 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13972 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13973 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13974 "shouldn't be called if type doesn't have a non-trivial C union");
13975
13976 if ((NonTrivialKind & NTCUK_Init) &&
13977 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13978 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13979 .visit(FT: QT, Args: nullptr, Args: false);
13980 if ((NonTrivialKind & NTCUK_Destruct) &&
13981 QT.hasNonTrivialToPrimitiveDestructCUnion())
13982 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13983 .visit(FT: QT, Args: nullptr, Args: false);
13984 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13985 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13986 .visit(FT: QT, Args: nullptr, Args: false);
13987}
13988
13989bool Sema::GloballyUniqueObjectMightBeAccidentallyDuplicated(
13990 const VarDecl *Dcl) {
13991 if (!getLangOpts().CPlusPlus)
13992 return false;
13993
13994 // We only need to warn if the definition is in a header file, so wait to
13995 // diagnose until we've seen the definition.
13996 if (!Dcl->isThisDeclarationADefinition())
13997 return false;
13998
13999 // If an object is defined in a source file, its definition can't get
14000 // duplicated since it will never appear in more than one TU.
14001 if (Dcl->getASTContext().getSourceManager().isInMainFile(Loc: Dcl->getLocation()))
14002 return false;
14003
14004 // If the variable we're looking at is a static local, then we actually care
14005 // about the properties of the function containing it.
14006 const ValueDecl *Target = Dcl;
14007 // VarDecls and FunctionDecls have different functions for checking
14008 // inline-ness, and whether they were originally templated, so we have to
14009 // call the appropriate functions manually.
14010 bool TargetIsInline = Dcl->isInline();
14011 bool TargetWasTemplated =
14012 Dcl->getTemplateSpecializationKind() != TSK_Undeclared;
14013
14014 // Update the Target and TargetIsInline property if necessary
14015 if (Dcl->isStaticLocal()) {
14016 const DeclContext *Ctx = Dcl->getDeclContext();
14017 if (!Ctx)
14018 return false;
14019
14020 const FunctionDecl *FunDcl =
14021 dyn_cast_if_present<FunctionDecl>(Val: Ctx->getNonClosureAncestor());
14022 if (!FunDcl)
14023 return false;
14024
14025 Target = FunDcl;
14026 // IsInlined() checks for the C++ inline property
14027 TargetIsInline = FunDcl->isInlined();
14028 TargetWasTemplated =
14029 FunDcl->getTemplateSpecializationKind() != TSK_Undeclared;
14030 }
14031
14032 // Non-inline functions/variables can only legally appear in one TU
14033 // unless they were part of a template. Unfortunately, making complex
14034 // template instantiations visible is infeasible in practice, since
14035 // everything the template depends on also has to be visible. To avoid
14036 // giving impractical-to-fix warnings, don't warn if we're inside
14037 // something that was templated, even on inline stuff.
14038 if (!TargetIsInline || TargetWasTemplated)
14039 return false;
14040
14041 // If the object isn't hidden, the dynamic linker will prevent duplication.
14042 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
14043
14044 // The target is "hidden" (from the dynamic linker) if:
14045 // 1. On posix, it has hidden visibility, or
14046 // 2. On windows, it has no import/export annotation, and neither does the
14047 // class which directly contains it.
14048 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
14049 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
14050 return false;
14051
14052 // If the variable isn't directly annotated, check to see if it's a member
14053 // of an annotated class.
14054 const CXXRecordDecl *Ctx =
14055 dyn_cast<CXXRecordDecl>(Val: Target->getDeclContext());
14056 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
14057 return false;
14058
14059 } else if (Lnk.getVisibility() != HiddenVisibility) {
14060 // Posix case
14061 return false;
14062 }
14063
14064 // If the obj doesn't have external linkage, it's supposed to be duplicated.
14065 if (!isExternalFormalLinkage(L: Lnk.getLinkage()))
14066 return false;
14067
14068 return true;
14069}
14070
14071// Determine whether the object seems mutable for the purpose of diagnosing
14072// possible unique object duplication, i.e. non-const-qualified, and
14073// not an always-constant type like a function.
14074// Not perfect: doesn't account for mutable members, for example, or
14075// elements of container types.
14076// For nested pointers, any individual level being non-const is sufficient.
14077static bool looksMutable(QualType T, const ASTContext &Ctx) {
14078 T = T.getNonReferenceType();
14079 if (T->isFunctionType())
14080 return false;
14081 if (!T.isConstant(Ctx))
14082 return true;
14083 if (T->isPointerType())
14084 return looksMutable(T: T->getPointeeType(), Ctx);
14085 return false;
14086}
14087
14088void Sema::DiagnoseUniqueObjectDuplication(const VarDecl *VD) {
14089 // If this object has external linkage and hidden visibility, it might be
14090 // duplicated when built into a shared library, which causes problems if it's
14091 // mutable (since the copies won't be in sync) or its initialization has side
14092 // effects (since it will run once per copy instead of once globally).
14093
14094 // Don't diagnose if we're inside a template, because it's not practical to
14095 // fix the warning in most cases.
14096 if (!VD->isTemplated() &&
14097 GloballyUniqueObjectMightBeAccidentallyDuplicated(Dcl: VD)) {
14098
14099 QualType Type = VD->getType();
14100 if (looksMutable(T: Type, Ctx: VD->getASTContext())) {
14101 Diag(Loc: VD->getLocation(), DiagID: diag::warn_possible_object_duplication_mutable)
14102 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
14103 }
14104
14105 // To keep false positives low, only warn if we're certain that the
14106 // initializer has side effects. Don't warn on operator new, since a mutable
14107 // pointer will trigger the previous warning, and an immutable pointer
14108 // getting duplicated just results in a little extra memory usage.
14109 const Expr *Init = VD->getAnyInitializer();
14110 if (Init &&
14111 Init->HasSideEffects(Ctx: VD->getASTContext(),
14112 /*IncludePossibleEffects=*/false) &&
14113 !isa<CXXNewExpr>(Val: Init->IgnoreParenImpCasts())) {
14114 Diag(Loc: Init->getExprLoc(), DiagID: diag::warn_possible_object_duplication_init)
14115 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
14116 }
14117 }
14118}
14119
14120void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
14121 llvm::scope_exit ResetDeclForInitializer([this]() {
14122 if (!this->ExprEvalContexts.empty())
14123 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
14124 });
14125
14126 // If there is no declaration, there was an error parsing it. Just ignore
14127 // the initializer.
14128 if (!RealDecl) {
14129 return;
14130 }
14131
14132 if (auto *Method = dyn_cast<CXXMethodDecl>(Val: RealDecl)) {
14133 if (!Method->isInvalidDecl()) {
14134 // Pure-specifiers are handled in ActOnPureSpecifier.
14135 Diag(Loc: Method->getLocation(), DiagID: diag::err_member_function_initialization)
14136 << Method->getDeclName() << Init->getSourceRange();
14137 Method->setInvalidDecl();
14138 }
14139 return;
14140 }
14141
14142 VarDecl *VDecl = dyn_cast<VarDecl>(Val: RealDecl);
14143 if (!VDecl) {
14144 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
14145 Diag(Loc: RealDecl->getLocation(), DiagID: diag::err_illegal_initializer);
14146 RealDecl->setInvalidDecl();
14147 return;
14148 }
14149
14150 if (VDecl->isInvalidDecl()) {
14151 ExprResult Recovery =
14152 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init});
14153 if (Expr *E = Recovery.get())
14154 VDecl->setInit(E);
14155 return;
14156 }
14157
14158 // __amdgpu_feature_predicate_t cannot be initialised
14159 if (VDecl->getType().getDesugaredType(Context) ==
14160 Context.AMDGPUFeaturePredicateTy) {
14161 Diag(Loc: VDecl->getLocation(),
14162 DiagID: diag::err_amdgcn_predicate_type_is_not_constructible)
14163 << VDecl;
14164 VDecl->setInvalidDecl();
14165 return;
14166 }
14167
14168 // WebAssembly tables can't be used to initialise a variable.
14169 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
14170 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_wasm_table_art) << 0;
14171 VDecl->setInvalidDecl();
14172 return;
14173 }
14174
14175 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
14176 if (VDecl->getType()->isUndeducedType()) {
14177 if (Init->containsErrors()) {
14178 // Invalidate the decl as we don't know the type for recovery-expr yet.
14179 RealDecl->setInvalidDecl();
14180 VDecl->setInit(Init);
14181 return;
14182 }
14183
14184 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) {
14185 assert(VDecl->isInvalidDecl() &&
14186 "decl should be invalidated when deduce fails");
14187 if (auto *RecoveryExpr =
14188 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init})
14189 .get())
14190 VDecl->setInit(RecoveryExpr);
14191 return;
14192 }
14193 }
14194
14195 this->CheckAttributesOnDeducedType(D: RealDecl);
14196
14197 // we don't initialize groupshared variables so warn and return
14198 if (VDecl->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
14199 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_hlsl_groupshared_init);
14200 return;
14201 }
14202
14203 // dllimport cannot be used on variable definitions.
14204 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
14205 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_attribute_dllimport_data_definition);
14206 VDecl->setInvalidDecl();
14207 return;
14208 }
14209
14210 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
14211 // the identifier has external or internal linkage, the declaration shall
14212 // have no initializer for the identifier.
14213 // C++14 [dcl.init]p5 is the same restriction for C++.
14214 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
14215 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_block_extern_cant_init);
14216 VDecl->setInvalidDecl();
14217 return;
14218 }
14219
14220 if (!VDecl->getType()->isDependentType()) {
14221 // A definition must end up with a complete type, which means it must be
14222 // complete with the restriction that an array type might be completed by
14223 // the initializer; note that later code assumes this restriction.
14224 QualType BaseDeclType = VDecl->getType();
14225 if (const ArrayType *Array = Context.getAsIncompleteArrayType(T: BaseDeclType))
14226 BaseDeclType = Array->getElementType();
14227 if (RequireCompleteType(Loc: VDecl->getLocation(), T: BaseDeclType,
14228 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14229 RealDecl->setInvalidDecl();
14230 return;
14231 }
14232
14233 // The variable can not have an abstract class type.
14234 if (RequireNonAbstractType(Loc: VDecl->getLocation(), T: VDecl->getType(),
14235 DiagID: diag::err_abstract_type_in_decl,
14236 Args: AbstractVariableType))
14237 VDecl->setInvalidDecl();
14238 }
14239
14240 // C++ [module.import/6]
14241 // ...
14242 // A header unit shall not contain a definition of a non-inline function or
14243 // variable whose name has external linkage.
14244 //
14245 // We choose to allow weak & selectany definitions, as they are common in
14246 // headers, and have semantics similar to inline definitions which are allowed
14247 // in header units.
14248 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
14249 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
14250 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
14251 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(Val: VDecl) &&
14252 !VDecl->getInstantiatedFromStaticDataMember() &&
14253 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
14254 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
14255 VDecl->setInvalidDecl();
14256 }
14257
14258 // If adding the initializer will turn this declaration into a definition,
14259 // and we already have a definition for this variable, diagnose or otherwise
14260 // handle the situation.
14261 if (VarDecl *Def = VDecl->getDefinition())
14262 if (Def != VDecl &&
14263 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
14264 !VDecl->isThisDeclarationADemotedDefinition() &&
14265 checkVarDeclRedefinition(Old: Def, New: VDecl))
14266 return;
14267
14268 if (getLangOpts().CPlusPlus) {
14269 // C++ [class.static.data]p4
14270 // If a static data member is of const integral or const
14271 // enumeration type, its declaration in the class definition can
14272 // specify a constant-initializer which shall be an integral
14273 // constant expression (5.19). In that case, the member can appear
14274 // in integral constant expressions. The member shall still be
14275 // defined in a namespace scope if it is used in the program and the
14276 // namespace scope definition shall not contain an initializer.
14277 //
14278 // We already performed a redefinition check above, but for static
14279 // data members we also need to check whether there was an in-class
14280 // declaration with an initializer.
14281 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
14282 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_static_data_member_reinitialization)
14283 << VDecl->getDeclName();
14284 Diag(Loc: VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
14285 DiagID: diag::note_previous_initializer)
14286 << 0;
14287 return;
14288 }
14289
14290 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer)) {
14291 VDecl->setInvalidDecl();
14292 return;
14293 }
14294 }
14295
14296 // If the variable has an initializer and local storage, check whether
14297 // anything jumps over the initialization.
14298 if (VDecl->hasLocalStorage())
14299 setFunctionHasBranchProtectedScope();
14300
14301 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
14302 // a kernel function cannot be initialized."
14303 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
14304 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_local_cant_init);
14305 VDecl->setInvalidDecl();
14306 return;
14307 }
14308
14309 // The LoaderUninitialized attribute acts as a definition (of undef).
14310 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14311 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_loader_uninitialized_cant_init);
14312 VDecl->setInvalidDecl();
14313 return;
14314 }
14315
14316 if (getLangOpts().HLSL)
14317 if (!HLSL().handleInitialization(VDecl, Init))
14318 return;
14319
14320 // Get the decls type and save a reference for later, since
14321 // CheckInitializerTypes may change it.
14322 QualType DclT = VDecl->getType(), SavT = DclT;
14323
14324 // Expressions default to 'id' when we're in a debugger
14325 // and we are assigning it to a variable of Objective-C pointer type.
14326 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14327 Init->getType() == Context.UnknownAnyTy) {
14328 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
14329 if (!Result.isUsable()) {
14330 VDecl->setInvalidDecl();
14331 return;
14332 }
14333 Init = Result.get();
14334 }
14335
14336 // Perform the initialization.
14337 bool InitializedFromParenListExpr = false;
14338 bool IsParenListInit = false;
14339 if (!VDecl->isInvalidDecl()) {
14340 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
14341 InitializationKind Kind = InitializationKind::CreateForInit(
14342 Loc: VDecl->getLocation(), DirectInit, Init);
14343
14344 MultiExprArg Args = Init;
14345 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Val: Init)) {
14346 Args =
14347 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14348 InitializedFromParenListExpr = true;
14349 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Val: Init)) {
14350 Args = CXXDirectInit->getInitExprs();
14351 InitializedFromParenListExpr = true;
14352 }
14353
14354 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14355 /*TopLevelOfInitList=*/false,
14356 /*TreatUnavailableAsInvalid=*/false);
14357 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args, ResultType: &DclT);
14358 if (!Result.isUsable()) {
14359 // If the provided initializer fails to initialize the var decl,
14360 // we attach a recovery expr for better recovery.
14361 auto RecoveryExpr =
14362 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: Args);
14363 if (RecoveryExpr.get())
14364 VDecl->setInit(RecoveryExpr.get());
14365 // In general, for error recovery purposes, the initializer doesn't play
14366 // part in the valid bit of the declaration. There are a few exceptions:
14367 // 1) if the var decl has a deduced auto type, and the type cannot be
14368 // deduced by an invalid initializer;
14369 // 2) if the var decl is a decomposition decl with a non-deduced type,
14370 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14371 // Case 1) was already handled elsewhere.
14372 if (isa<DecompositionDecl>(Val: VDecl)) // Case 2)
14373 VDecl->setInvalidDecl();
14374 return;
14375 }
14376
14377 Init = Result.getAs<Expr>();
14378 IsParenListInit = !InitSeq.steps().empty() &&
14379 InitSeq.step_begin()->Kind ==
14380 InitializationSequence::SK_ParenthesizedListInit;
14381 QualType VDeclType = VDecl->getType();
14382 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14383 !VDeclType->isDependentType() &&
14384 Context.getAsIncompleteArrayType(T: VDeclType) &&
14385 Context.getAsIncompleteArrayType(T: Init->getType())) {
14386 // Bail out if it is not possible to deduce array size from the
14387 // initializer.
14388 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
14389 << VDeclType;
14390 VDecl->setInvalidDecl();
14391 return;
14392 }
14393 }
14394
14395 // Check for self-references within variable initializers.
14396 // Variables declared within a function/method body (except for references)
14397 // are handled by a dataflow analysis.
14398 // This is undefined behavior in C++, but valid in C.
14399 if (getLangOpts().CPlusPlus)
14400 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14401 VDecl->getType()->isReferenceType())
14402 CheckSelfReference(S&: *this, OrigDecl: RealDecl, E: Init, DirectInit);
14403
14404 // If the type changed, it means we had an incomplete type that was
14405 // completed by the initializer. For example:
14406 // int ary[] = { 1, 3, 5 };
14407 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14408 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14409 VDecl->setType(DclT);
14410
14411 if (!VDecl->isInvalidDecl()) {
14412 checkUnsafeAssigns(Loc: VDecl->getLocation(), LHS: VDecl->getType(), RHS: Init);
14413
14414 if (VDecl->hasAttr<BlocksAttr>())
14415 ObjC().checkRetainCycles(Var: VDecl, Init);
14416
14417 // It is safe to assign a weak reference into a strong variable.
14418 // Although this code can still have problems:
14419 // id x = self.weakProp;
14420 // id y = self.weakProp;
14421 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14422 // paths through the function. This should be revisited if
14423 // -Wrepeated-use-of-weak is made flow-sensitive.
14424 if (FunctionScopeInfo *FSI = getCurFunction())
14425 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14426 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
14427 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14428 Loc: Init->getBeginLoc()))
14429 FSI->markSafeWeakUse(E: Init);
14430 }
14431
14432 // The initialization is usually a full-expression.
14433 //
14434 // FIXME: If this is a braced initialization of an aggregate, it is not
14435 // an expression, and each individual field initializer is a separate
14436 // full-expression. For instance, in:
14437 //
14438 // struct Temp { ~Temp(); };
14439 // struct S { S(Temp); };
14440 // struct T { S a, b; } t = { Temp(), Temp() }
14441 //
14442 // we should destroy the first Temp before constructing the second.
14443
14444 // Set context flag for OverflowBehaviorType initialization analysis
14445 llvm::SaveAndRestore OBTAssignmentContext(InOverflowBehaviorAssignmentContext,
14446 true);
14447 ExprResult Result =
14448 ActOnFinishFullExpr(Expr: Init, CC: VDecl->getLocation(),
14449 /*DiscardedValue*/ false, IsConstexpr: VDecl->isConstexpr());
14450 if (!Result.isUsable()) {
14451 VDecl->setInvalidDecl();
14452 return;
14453 }
14454 Init = Result.get();
14455
14456 // Attach the initializer to the decl.
14457 VDecl->setInit(Init);
14458
14459 if (VDecl->isLocalVarDecl()) {
14460 // Don't check the initializer if the declaration is malformed.
14461 if (VDecl->isInvalidDecl()) {
14462 // do nothing
14463
14464 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14465 // This is true even in C++ for OpenCL.
14466 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14467 CheckForConstantInitializer(Init);
14468
14469 // Otherwise, C++ does not restrict the initializer.
14470 } else if (getLangOpts().CPlusPlus) {
14471 // do nothing
14472
14473 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14474 // static storage duration shall be constant expressions or string literals.
14475 } else if (VDecl->getStorageClass() == SC_Static) {
14476 // Avoid evaluating the initializer twice for constexpr variables. It will
14477 // be evaluated later.
14478 if (!VDecl->isConstexpr())
14479 CheckForConstantInitializer(Init);
14480
14481 // C89 is stricter than C99 for aggregate initializers.
14482 // C89 6.5.7p3: All the expressions [...] in an initializer list
14483 // for an object that has aggregate or union type shall be
14484 // constant expressions.
14485 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14486 isa<InitListExpr>(Val: Init)) {
14487 CheckForConstantInitializer(Init, DiagID: diag::ext_aggregate_init_not_constant);
14488 }
14489
14490 if (auto *E = dyn_cast<ExprWithCleanups>(Val: Init))
14491 if (auto *BE = dyn_cast<BlockExpr>(Val: E->getSubExpr()->IgnoreParens()))
14492 if (VDecl->hasLocalStorage())
14493 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14494 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14495 VDecl->getLexicalDeclContext()->isRecord()) {
14496 // This is an in-class initialization for a static data member, e.g.,
14497 //
14498 // struct S {
14499 // static const int value = 17;
14500 // };
14501
14502 // C++ [class.mem]p4:
14503 // A member-declarator can contain a constant-initializer only
14504 // if it declares a static member (9.4) of const integral or
14505 // const enumeration type, see 9.4.2.
14506 //
14507 // C++11 [class.static.data]p3:
14508 // If a non-volatile non-inline const static data member is of integral
14509 // or enumeration type, its declaration in the class definition can
14510 // specify a brace-or-equal-initializer in which every initializer-clause
14511 // that is an assignment-expression is a constant expression. A static
14512 // data member of literal type can be declared in the class definition
14513 // with the constexpr specifier; if so, its declaration shall specify a
14514 // brace-or-equal-initializer in which every initializer-clause that is
14515 // an assignment-expression is a constant expression.
14516
14517 // Do nothing on dependent types.
14518 if (DclT->isDependentType()) {
14519
14520 // Allow any 'static constexpr' members, whether or not they are of literal
14521 // type. We separately check that every constexpr variable is of literal
14522 // type.
14523 } else if (VDecl->isConstexpr()) {
14524
14525 // Require constness.
14526 } else if (!DclT.isConstQualified()) {
14527 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_non_const)
14528 << Init->getSourceRange();
14529 VDecl->setInvalidDecl();
14530
14531 // We allow integer constant expressions in all cases.
14532 } else if (DclT->isIntegralOrEnumerationType()) {
14533 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
14534 // In C++11, a non-constexpr const static data member with an
14535 // in-class initializer cannot be volatile.
14536 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_volatile);
14537
14538 // We allow foldable floating-point constants as an extension.
14539 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14540 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14541 // it anyway and provide a fixit to add the 'constexpr'.
14542 if (getLangOpts().CPlusPlus11) {
14543 Diag(Loc: VDecl->getLocation(),
14544 DiagID: diag::ext_in_class_initializer_float_type_cxx11)
14545 << DclT << Init->getSourceRange();
14546 Diag(Loc: VDecl->getBeginLoc(),
14547 DiagID: diag::note_in_class_initializer_float_type_cxx11)
14548 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14549 } else {
14550 Diag(Loc: VDecl->getLocation(), DiagID: diag::ext_in_class_initializer_float_type)
14551 << DclT << Init->getSourceRange();
14552
14553 if (!Init->isValueDependent() && !Init->isEvaluatable(Ctx: Context)) {
14554 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_in_class_initializer_non_constant)
14555 << Init->getSourceRange();
14556 VDecl->setInvalidDecl();
14557 }
14558 }
14559
14560 // Suggest adding 'constexpr' in C++11 for literal types.
14561 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Ctx: Context)) {
14562 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_literal_type)
14563 << DclT << Init->getSourceRange()
14564 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14565 VDecl->setConstexpr(true);
14566
14567 } else {
14568 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_bad_type)
14569 << DclT << Init->getSourceRange();
14570 VDecl->setInvalidDecl();
14571 }
14572 } else if (VDecl->isFileVarDecl()) {
14573 // In C, extern is typically used to avoid tentative definitions when
14574 // declaring variables in headers, but adding an initializer makes it a
14575 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14576 // In C++, extern is often used to give implicitly static const variables
14577 // external linkage, so don't warn in that case. If selectany is present,
14578 // this might be header code intended for C and C++ inclusion, so apply the
14579 // C++ rules.
14580 if (VDecl->getStorageClass() == SC_Extern &&
14581 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14582 !Context.getBaseElementType(QT: VDecl->getType()).isConstQualified()) &&
14583 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14584 !isTemplateInstantiation(Kind: VDecl->getTemplateSpecializationKind()))
14585 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_extern_init);
14586
14587 // In Microsoft C++ mode, a const variable defined in namespace scope has
14588 // external linkage by default if the variable is declared with
14589 // __declspec(dllexport).
14590 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14591 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
14592 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14593 VDecl->setStorageClass(SC_Extern);
14594
14595 // C99 6.7.8p4. All file scoped initializers need to be constant.
14596 // Avoid duplicate diagnostics for constexpr variables.
14597 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14598 !VDecl->isConstexpr())
14599 CheckForConstantInitializer(Init);
14600 }
14601
14602 QualType InitType = Init->getType();
14603 if (!InitType.isNull() &&
14604 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
14605 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
14606 checkNonTrivialCUnionInInitializer(Init, Loc: Init->getExprLoc());
14607
14608 // We will represent direct-initialization similarly to copy-initialization:
14609 // int x(1); -as-> int x = 1;
14610 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14611 //
14612 // Clients that want to distinguish between the two forms, can check for
14613 // direct initializer using VarDecl::getInitStyle().
14614 // A major benefit is that clients that don't particularly care about which
14615 // exactly form was it (like the CodeGen) can handle both cases without
14616 // special case code.
14617
14618 // C++ 8.5p11:
14619 // The form of initialization (using parentheses or '=') matters
14620 // when the entity being initialized has class type.
14621 if (InitializedFromParenListExpr) {
14622 assert(DirectInit && "Call-style initializer must be direct init.");
14623 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14624 : VarDecl::CallInit);
14625 } else if (DirectInit) {
14626 // This must be list-initialization. No other way is direct-initialization.
14627 VDecl->setInitStyle(VarDecl::ListInit);
14628 }
14629
14630 if (LangOpts.OpenMP &&
14631 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14632 VDecl->isFileVarDecl())
14633 DeclsToCheckForDeferredDiags.insert(X: VDecl);
14634 CheckCompleteVariableDeclaration(VD: VDecl);
14635
14636 if (LangOpts.OpenACC && !InitType.isNull())
14637 OpenACC().ActOnVariableInit(VD: VDecl, InitType);
14638}
14639
14640void Sema::ActOnInitializerError(Decl *D) {
14641 // Our main concern here is re-establishing invariants like "a
14642 // variable's type is either dependent or complete".
14643 if (!D || D->isInvalidDecl()) return;
14644
14645 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14646 if (!VD) return;
14647
14648 // Bindings are not usable if we can't make sense of the initializer.
14649 if (auto *DD = dyn_cast<DecompositionDecl>(Val: D))
14650 for (auto *BD : DD->bindings())
14651 BD->setInvalidDecl();
14652
14653 // Auto types are meaningless if we can't make sense of the initializer.
14654 if (VD->getType()->isUndeducedType()) {
14655 D->setInvalidDecl();
14656 return;
14657 }
14658
14659 QualType Ty = VD->getType();
14660 if (Ty->isDependentType()) return;
14661
14662 // Require a complete type.
14663 if (RequireCompleteType(Loc: VD->getLocation(),
14664 T: Context.getBaseElementType(QT: Ty),
14665 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14666 VD->setInvalidDecl();
14667 return;
14668 }
14669
14670 // Require a non-abstract type.
14671 if (RequireNonAbstractType(Loc: VD->getLocation(), T: Ty,
14672 DiagID: diag::err_abstract_type_in_decl,
14673 Args: AbstractVariableType)) {
14674 VD->setInvalidDecl();
14675 return;
14676 }
14677
14678 // Don't bother complaining about constructors or destructors,
14679 // though.
14680}
14681
14682void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
14683 // If there is no declaration, there was an error parsing it. Just ignore it.
14684 if (!RealDecl)
14685 return;
14686
14687 if (VarDecl *Var = dyn_cast<VarDecl>(Val: RealDecl)) {
14688 QualType Type = Var->getType();
14689
14690 if (Type.getDesugaredType(Context) == Context.AMDGPUFeaturePredicateTy) {
14691 Diag(Loc: Var->getLocation(),
14692 DiagID: diag::err_amdgcn_predicate_type_is_not_constructible)
14693 << Var;
14694 Var->setInvalidDecl();
14695 return;
14696 }
14697 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14698 if (isa<DecompositionDecl>(Val: RealDecl)) {
14699 // Point the caret to the token immediately after the closing bracket if
14700 // it can be found; otherwise fall back to the declaration's location.
14701 SourceLocation Loc = Var->getLocation();
14702 SourceLocation RSquareLoc =
14703 dyn_cast<DecompositionDecl>(Val: RealDecl)->getRSquareLoc();
14704 if (std::optional<Token> Next = Lexer::findNextToken(
14705 Loc: RSquareLoc, SM: PP.getSourceManager(), LangOpts: PP.getLangOpts()))
14706 Loc = Next->getLocation();
14707 Diag(Loc, DiagID: diag::err_decomp_decl_requires_init) << Var;
14708 Var->setInvalidDecl();
14709 return;
14710 }
14711
14712 if (Type->isUndeducedType() &&
14713 DeduceVariableDeclarationType(VDecl: Var, DirectInit: false, Init: nullptr))
14714 return;
14715
14716 this->CheckAttributesOnDeducedType(D: RealDecl);
14717
14718 // C++11 [class.static.data]p3: A static data member can be declared with
14719 // the constexpr specifier; if so, its declaration shall specify
14720 // a brace-or-equal-initializer.
14721 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14722 // the definition of a variable [...] or the declaration of a static data
14723 // member.
14724 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14725 !Var->isThisDeclarationADemotedDefinition()) {
14726 if (Var->isStaticDataMember()) {
14727 // C++1z removes the relevant rule; the in-class declaration is always
14728 // a definition there.
14729 if (!getLangOpts().CPlusPlus17 &&
14730 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14731 Diag(Loc: Var->getLocation(),
14732 DiagID: diag::err_constexpr_static_mem_var_requires_init)
14733 << Var;
14734 Var->setInvalidDecl();
14735 return;
14736 }
14737 } else {
14738 Diag(Loc: Var->getLocation(), DiagID: diag::err_invalid_constexpr_var_decl);
14739 Var->setInvalidDecl();
14740 return;
14741 }
14742 }
14743
14744 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14745 // be initialized.
14746 if (!Var->isInvalidDecl() &&
14747 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14748 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14749 bool HasConstExprDefaultConstructor = false;
14750 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14751 for (auto *Ctor : RD->ctors()) {
14752 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14753 Ctor->getMethodQualifiers().getAddressSpace() ==
14754 LangAS::opencl_constant) {
14755 HasConstExprDefaultConstructor = true;
14756 }
14757 }
14758 }
14759 if (!HasConstExprDefaultConstructor) {
14760 Diag(Loc: Var->getLocation(), DiagID: diag::err_opencl_constant_no_init);
14761 Var->setInvalidDecl();
14762 return;
14763 }
14764 }
14765
14766 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14767 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14768 Diag(Loc: Var->getLocation(), DiagID: diag::err_specialization_const);
14769 Var->setInvalidDecl();
14770 return;
14771 }
14772
14773 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14774 if (Var->getStorageClass() == SC_Extern) {
14775 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_extern_decl)
14776 << Var;
14777 Var->setInvalidDecl();
14778 return;
14779 }
14780 if (RequireCompleteType(Loc: Var->getLocation(), T: Var->getType(),
14781 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14782 Var->setInvalidDecl();
14783 return;
14784 }
14785 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14786 if (!RD->hasTrivialDefaultConstructor()) {
14787 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_trivial_ctor);
14788 Var->setInvalidDecl();
14789 return;
14790 }
14791 }
14792 // The declaration is uninitialized, no need for further checks.
14793 return;
14794 }
14795
14796 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14797 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14798 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14799 checkNonTrivialCUnion(QT: Var->getType(), Loc: Var->getLocation(),
14800 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
14801 NonTrivialKind: NTCUK_Init);
14802
14803 switch (DefKind) {
14804 case VarDecl::Definition:
14805 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14806 break;
14807
14808 // We have an out-of-line definition of a static data member
14809 // that has an in-class initializer, so we type-check this like
14810 // a declaration.
14811 //
14812 [[fallthrough]];
14813
14814 case VarDecl::DeclarationOnly:
14815 // It's only a declaration.
14816
14817 // Block scope. C99 6.7p7: If an identifier for an object is
14818 // declared with no linkage (C99 6.2.2p6), the type for the
14819 // object shall be complete.
14820 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14821 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14822 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14823 DiagID: diag::err_typecheck_decl_incomplete_type))
14824 Var->setInvalidDecl();
14825
14826 // Make sure that the type is not abstract.
14827 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14828 RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14829 DiagID: diag::err_abstract_type_in_decl,
14830 Args: AbstractVariableType))
14831 Var->setInvalidDecl();
14832 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14833 Var->getStorageClass() == SC_PrivateExtern) {
14834 Diag(Loc: Var->getLocation(), DiagID: diag::warn_private_extern);
14835 Diag(Loc: Var->getLocation(), DiagID: diag::note_private_extern);
14836 }
14837
14838 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14839 !Var->isInvalidDecl())
14840 ExternalDeclarations.push_back(Elt: Var);
14841
14842 return;
14843
14844 case VarDecl::TentativeDefinition:
14845 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14846 // object that has file scope without an initializer, and without a
14847 // storage-class specifier or with the storage-class specifier "static",
14848 // constitutes a tentative definition. Note: A tentative definition with
14849 // external linkage is valid (C99 6.2.2p5).
14850 if (!Var->isInvalidDecl()) {
14851 if (const IncompleteArrayType *ArrayT
14852 = Context.getAsIncompleteArrayType(T: Type)) {
14853 if (RequireCompleteSizedType(
14854 Loc: Var->getLocation(), T: ArrayT->getElementType(),
14855 DiagID: diag::err_array_incomplete_or_sizeless_type))
14856 Var->setInvalidDecl();
14857 }
14858 if (Var->getStorageClass() == SC_Static) {
14859 // C99 6.9.2p3: If the declaration of an identifier for an object is
14860 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14861 // declared type shall not be an incomplete type.
14862 // NOTE: code such as the following
14863 // static struct s;
14864 // struct s { int a; };
14865 // is accepted by gcc. Hence here we issue a warning instead of
14866 // an error and we do not invalidate the static declaration.
14867 // NOTE: to avoid multiple warnings, only check the first declaration.
14868 if (Var->isFirstDecl())
14869 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14870 DiagID: diag::ext_typecheck_decl_incomplete_type,
14871 Args: Type->isArrayType());
14872 }
14873 }
14874
14875 // Record the tentative definition; we're done.
14876 if (!Var->isInvalidDecl())
14877 TentativeDefinitions.push_back(LocalValue: Var);
14878 return;
14879 }
14880
14881 // Provide a specific diagnostic for uninitialized variable definitions
14882 // with incomplete array type, unless it is a global unbounded HLSL resource
14883 // array.
14884 if (Type->isIncompleteArrayType() &&
14885 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14886 Type->isHLSLResourceRecordArray())) {
14887 if (Var->isConstexpr())
14888 Diag(Loc: Var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
14889 << Var;
14890 else
14891 Diag(Loc: Var->getLocation(),
14892 DiagID: diag::err_typecheck_incomplete_array_needs_initializer);
14893 Var->setInvalidDecl();
14894 return;
14895 }
14896
14897 // Provide a specific diagnostic for uninitialized variable
14898 // definitions with reference type.
14899 if (Type->isReferenceType()) {
14900 Diag(Loc: Var->getLocation(), DiagID: diag::err_reference_var_requires_init)
14901 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14902 return;
14903 }
14904
14905 // Do not attempt to type-check the default initializer for a
14906 // variable with dependent type.
14907 if (Type->isDependentType())
14908 return;
14909
14910 if (Var->isInvalidDecl())
14911 return;
14912
14913 if (!Var->hasAttr<AliasAttr>()) {
14914 if (RequireCompleteType(Loc: Var->getLocation(),
14915 T: Context.getBaseElementType(QT: Type),
14916 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14917 Var->setInvalidDecl();
14918 return;
14919 }
14920 } else {
14921 return;
14922 }
14923
14924 // The variable can not have an abstract class type.
14925 if (RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14926 DiagID: diag::err_abstract_type_in_decl,
14927 Args: AbstractVariableType)) {
14928 Var->setInvalidDecl();
14929 return;
14930 }
14931
14932 // In C, if the definition is const-qualified and has no initializer, it
14933 // is left uninitialized unless it has static or thread storage duration.
14934 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14935 unsigned DiagID = diag::warn_default_init_const_unsafe;
14936 if (Var->getStorageDuration() == SD_Static ||
14937 Var->getStorageDuration() == SD_Thread)
14938 DiagID = diag::warn_default_init_const;
14939
14940 bool EmitCppCompat = !Diags.isIgnored(
14941 DiagID: diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14942 Loc: Var->getLocation());
14943
14944 Diag(Loc: Var->getLocation(), DiagID) << Type << EmitCppCompat;
14945 }
14946
14947 // Check for jumps past the implicit initializer. C++0x
14948 // clarifies that this applies to a "variable with automatic
14949 // storage duration", not a "local variable".
14950 // C++11 [stmt.dcl]p3
14951 // A program that jumps from a point where a variable with automatic
14952 // storage duration is not in scope to a point where it is in scope is
14953 // ill-formed unless the variable has scalar type, class type with a
14954 // trivial default constructor and a trivial destructor, a cv-qualified
14955 // version of one of these types, or an array of one of the preceding
14956 // types and is declared without an initializer.
14957 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14958 if (const auto *CXXRecord =
14959 Context.getBaseElementType(QT: Type)->getAsCXXRecordDecl()) {
14960 // Mark the function (if we're in one) for further checking even if the
14961 // looser rules of C++11 do not require such checks, so that we can
14962 // diagnose incompatibilities with C++98.
14963 if (!CXXRecord->isPOD())
14964 setFunctionHasBranchProtectedScope();
14965 }
14966 }
14967 // In OpenCL, we can't initialize objects in the __local address space,
14968 // even implicitly, so don't synthesize an implicit initializer.
14969 if (getLangOpts().OpenCL &&
14970 Var->getType().getAddressSpace() == LangAS::opencl_local)
14971 return;
14972
14973 // Handle HLSL uninitialized decls
14974 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(D: Var))
14975 return;
14976
14977 // HLSL input & push-constant variables are expected to be externally
14978 // initialized, even when marked `static`.
14979 if (getLangOpts().HLSL &&
14980 hlsl::isInitializedByPipeline(AS: Var->getType().getAddressSpace()))
14981 return;
14982
14983 // C++03 [dcl.init]p9:
14984 // If no initializer is specified for an object, and the
14985 // object is of (possibly cv-qualified) non-POD class type (or
14986 // array thereof), the object shall be default-initialized; if
14987 // the object is of const-qualified type, the underlying class
14988 // type shall have a user-declared default
14989 // constructor. Otherwise, if no initializer is specified for
14990 // a non- static object, the object and its subobjects, if
14991 // any, have an indeterminate initial value); if the object
14992 // or any of its subobjects are of const-qualified type, the
14993 // program is ill-formed.
14994 // C++0x [dcl.init]p11:
14995 // If no initializer is specified for an object, the object is
14996 // default-initialized; [...].
14997 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14998 InitializationKind Kind
14999 = InitializationKind::CreateDefault(InitLoc: Var->getLocation());
15000
15001 InitializationSequence InitSeq(*this, Entity, Kind, {});
15002 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: {});
15003
15004 if (Init.get()) {
15005 Var->setInit(MaybeCreateExprWithCleanups(SubExpr: Init.get()));
15006 // This is important for template substitution.
15007 Var->setInitStyle(VarDecl::CallInit);
15008 } else if (Init.isInvalid()) {
15009 // If default-init fails, attach a recovery-expr initializer to track
15010 // that initialization was attempted and failed.
15011 auto RecoveryExpr =
15012 CreateRecoveryExpr(Begin: Var->getLocation(), End: Var->getLocation(), SubExprs: {});
15013 if (RecoveryExpr.get())
15014 Var->setInit(RecoveryExpr.get());
15015 }
15016
15017 CheckCompleteVariableDeclaration(VD: Var);
15018 }
15019}
15020
15021void Sema::ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt) {
15022 // If there is no declaration, there was an error parsing it. Ignore it.
15023 if (!D)
15024 return;
15025
15026 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
15027 if (!VD) {
15028 Diag(Loc: D->getLocation(), DiagID: diag::err_for_range_decl_must_be_var)
15029 << InExpansionStmt;
15030 D->setInvalidDecl();
15031 return;
15032 }
15033
15034 VD->setCXXForRangeDecl(true);
15035
15036 // for-range-declaration cannot be given a storage class specifier.
15037 int Error = -1;
15038 switch (VD->getStorageClass()) {
15039 case SC_None:
15040 break;
15041 case SC_Extern:
15042 Error = 0;
15043 break;
15044 case SC_Static:
15045 Error = 1;
15046 break;
15047 case SC_PrivateExtern:
15048 Error = 2;
15049 break;
15050 case SC_Auto:
15051 Error = 3;
15052 break;
15053 case SC_Register:
15054 Error = 4;
15055 break;
15056 }
15057
15058 // for-range-declaration cannot be given a storage class specifier con't.
15059 switch (VD->getTSCSpec()) {
15060 case TSCS_thread_local:
15061 Error = 6;
15062 break;
15063 case TSCS___thread:
15064 case TSCS__Thread_local:
15065 case TSCS_unspecified:
15066 break;
15067 }
15068
15069 if (Error != -1) {
15070 Diag(Loc: VD->getOuterLocStart(), DiagID: diag::err_for_range_storage_class)
15071 << InExpansionStmt << VD << Error;
15072 D->setInvalidDecl();
15073 }
15074}
15075
15076StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
15077 IdentifierInfo *Ident,
15078 ParsedAttributes &Attrs) {
15079 // C++1y [stmt.iter]p1:
15080 // A range-based for statement of the form
15081 // for ( for-range-identifier : for-range-initializer ) statement
15082 // is equivalent to
15083 // for ( auto&& for-range-identifier : for-range-initializer ) statement
15084 DeclSpec DS(Attrs.getPool().getFactory());
15085
15086 const char *PrevSpec;
15087 unsigned DiagID;
15088 DS.SetTypeSpecType(T: DeclSpec::TST_auto, Loc: IdentLoc, PrevSpec, DiagID,
15089 Policy: getPrintingPolicy());
15090
15091 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
15092 D.SetIdentifier(Id: Ident, IdLoc: IdentLoc);
15093 D.takeAttributesAppending(attrs&: Attrs);
15094
15095 D.AddTypeInfo(TI: DeclaratorChunk::getReference(TypeQuals: 0, Loc: IdentLoc, /*lvalue*/ false),
15096 EndLoc: IdentLoc);
15097 Decl *Var = ActOnDeclarator(S, D);
15098 cast<VarDecl>(Val: Var)->setCXXForRangeDecl(true);
15099 FinalizeDeclaration(D: Var);
15100 return ActOnDeclStmt(Decl: FinalizeDeclaratorGroup(S, DS, Group: Var), StartLoc: IdentLoc,
15101 EndLoc: Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
15102 : IdentLoc);
15103}
15104
15105void Sema::addLifetimeBoundToImplicitThis(CXXMethodDecl *MD) {
15106 if (!MD || lifetimes::implicitObjectParamIsLifetimeBound(FD: MD))
15107 return;
15108 auto *Attr = LifetimeBoundAttr::CreateImplicit(Ctx&: Context, Range: MD->getLocation());
15109 QualType MethodType = MD->getType();
15110 QualType AttributedType =
15111 Context.getAttributedType(attr: Attr, modifiedType: MethodType, equivalentType: MethodType);
15112 TypeLocBuilder TLB;
15113 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
15114 TLB.pushFullCopy(L: TSI->getTypeLoc());
15115 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(T: AttributedType);
15116 TyLoc.setAttr(Attr);
15117 MD->setType(AttributedType);
15118 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, T: AttributedType));
15119}
15120
15121void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
15122 if (var->isInvalidDecl()) return;
15123
15124 CUDA().MaybeAddConstantAttr(VD: var);
15125
15126 if (getLangOpts().OpenCL) {
15127 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
15128 // initialiser
15129 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
15130 !var->hasInit()) {
15131 Diag(Loc: var->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
15132 << 1 /*Init*/;
15133 var->setInvalidDecl();
15134 return;
15135 }
15136 }
15137
15138 // In Objective-C, don't allow jumps past the implicit initialization of a
15139 // local retaining variable.
15140 if (getLangOpts().ObjC &&
15141 var->hasLocalStorage()) {
15142 switch (var->getType().getObjCLifetime()) {
15143 case Qualifiers::OCL_None:
15144 case Qualifiers::OCL_ExplicitNone:
15145 case Qualifiers::OCL_Autoreleasing:
15146 break;
15147
15148 case Qualifiers::OCL_Weak:
15149 case Qualifiers::OCL_Strong:
15150 setFunctionHasBranchProtectedScope();
15151 break;
15152 }
15153 }
15154
15155 if (var->hasLocalStorage() &&
15156 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
15157 setFunctionHasBranchProtectedScope();
15158
15159 // Warn about externally-visible variables being defined without a
15160 // prior declaration. We only want to do this for global
15161 // declarations, but we also specifically need to avoid doing it for
15162 // class members because the linkage of an anonymous class can
15163 // change if it's later given a typedef name.
15164 if (var->isThisDeclarationADefinition() &&
15165 var->getDeclContext()->getRedeclContext()->isFileContext() &&
15166 var->isExternallyVisible() && var->hasLinkage() &&
15167 !var->isInline() && !var->getDescribedVarTemplate() &&
15168 var->getStorageClass() != SC_Register &&
15169 !isa<VarTemplatePartialSpecializationDecl>(Val: var) &&
15170 !isTemplateInstantiation(Kind: var->getTemplateSpecializationKind()) &&
15171 !getDiagnostics().isIgnored(DiagID: diag::warn_missing_variable_declarations,
15172 Loc: var->getLocation())) {
15173 // Find a previous declaration that's not a definition.
15174 VarDecl *prev = var->getPreviousDecl();
15175 while (prev && prev->isThisDeclarationADefinition())
15176 prev = prev->getPreviousDecl();
15177
15178 if (!prev) {
15179 Diag(Loc: var->getLocation(), DiagID: diag::warn_missing_variable_declarations) << var;
15180 Diag(Loc: var->getTypeSpecStartLoc(), DiagID: diag::note_static_for_internal_linkage)
15181 << /* variable */ 0;
15182 }
15183 }
15184
15185 // Cache the result of checking for constant initialization.
15186 std::optional<bool> CacheHasConstInit;
15187 const Expr *CacheCulprit = nullptr;
15188 auto checkConstInit = [&]() mutable {
15189 const Expr *Init = var->getInit();
15190 if (Init->isInstantiationDependent())
15191 return true;
15192
15193 if (!CacheHasConstInit)
15194 CacheHasConstInit = var->getInit()->isConstantInitializer(
15195 Ctx&: Context, ForRef: var->getType()->isReferenceType(), Culprit: &CacheCulprit);
15196 return *CacheHasConstInit;
15197 };
15198
15199 if (var->getTLSKind() == VarDecl::TLS_Static) {
15200 if (var->getType().isDestructedType()) {
15201 // GNU C++98 edits for __thread, [basic.start.term]p3:
15202 // The type of an object with thread storage duration shall not
15203 // have a non-trivial destructor.
15204 Diag(Loc: var->getLocation(), DiagID: diag::err_thread_nontrivial_dtor);
15205 if (getLangOpts().CPlusPlus11)
15206 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
15207 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
15208 if (!checkConstInit()) {
15209 // GNU C++98 edits for __thread, [basic.start.init]p4:
15210 // An object of thread storage duration shall not require dynamic
15211 // initialization.
15212 // FIXME: Need strict checking here.
15213 Diag(Loc: CacheCulprit->getExprLoc(), DiagID: diag::err_thread_dynamic_init)
15214 << CacheCulprit->getSourceRange();
15215 if (getLangOpts().CPlusPlus11)
15216 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
15217 }
15218 }
15219 }
15220
15221
15222 if (!var->getType()->isStructureType() && var->hasInit() &&
15223 isa<InitListExpr>(Val: var->getInit())) {
15224 const auto *ILE = cast<InitListExpr>(Val: var->getInit());
15225 unsigned NumInits = ILE->getNumInits();
15226 if (NumInits > 2)
15227 for (unsigned I = 0; I < NumInits; ++I) {
15228 const auto *Init = ILE->getInit(Init: I);
15229 if (!Init)
15230 break;
15231 const auto *SL = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
15232 if (!SL)
15233 break;
15234
15235 unsigned NumConcat = SL->getNumConcatenated();
15236 // Diagnose missing comma in string array initialization.
15237 // Do not warn when all the elements in the initializer are concatenated
15238 // together. Do not warn for macros too.
15239 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
15240 bool OnlyOneMissingComma = true;
15241 for (unsigned J = I + 1; J < NumInits; ++J) {
15242 const auto *Init = ILE->getInit(Init: J);
15243 if (!Init)
15244 break;
15245 const auto *SLJ = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
15246 if (!SLJ || SLJ->getNumConcatenated() > 1) {
15247 OnlyOneMissingComma = false;
15248 break;
15249 }
15250 }
15251
15252 if (OnlyOneMissingComma) {
15253 SmallVector<FixItHint, 1> Hints;
15254 for (unsigned i = 0; i < NumConcat - 1; ++i)
15255 Hints.push_back(Elt: FixItHint::CreateInsertion(
15256 InsertionLoc: PP.getLocForEndOfToken(Loc: SL->getStrTokenLoc(TokNum: i)), Code: ","));
15257
15258 Diag(Loc: SL->getStrTokenLoc(TokNum: 1),
15259 DiagID: diag::warn_concatenated_literal_array_init)
15260 << Hints;
15261 Diag(Loc: SL->getBeginLoc(),
15262 DiagID: diag::note_concatenated_string_literal_silence);
15263 }
15264 // In any case, stop now.
15265 break;
15266 }
15267 }
15268 }
15269
15270
15271 QualType type = var->getType();
15272
15273 if (var->hasAttr<BlocksAttr>())
15274 getCurFunction()->addByrefBlockVar(VD: var);
15275
15276 Expr *Init = var->getInit();
15277 bool GlobalStorage = var->hasGlobalStorage();
15278 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
15279 QualType baseType = Context.getBaseElementType(QT: type);
15280 bool HasConstInit = true;
15281
15282 if (getLangOpts().C23 && var->isConstexpr() && !Init)
15283 Diag(Loc: var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
15284 << var;
15285
15286 // Check whether the initializer is sufficiently constant.
15287 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
15288 !type->isDependentType() && Init && !Init->isValueDependent() &&
15289 (GlobalStorage || var->isConstexpr() ||
15290 var->mightBeUsableInConstantExpressions(C: Context))) {
15291 // If this variable might have a constant initializer or might be usable in
15292 // constant expressions, check whether or not it actually is now. We can't
15293 // do this lazily, because the result might depend on things that change
15294 // later, such as which constexpr functions happen to be defined.
15295 SmallVector<PartialDiagnosticAt, 8> Notes;
15296 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
15297 // Prior to C++11, in contexts where a constant initializer is required,
15298 // the set of valid constant initializers is described by syntactic rules
15299 // in [expr.const]p2-6.
15300 // FIXME: Stricter checking for these rules would be useful for constinit /
15301 // -Wglobal-constructors.
15302 HasConstInit = checkConstInit();
15303
15304 // Compute and cache the constant value, and remember that we have a
15305 // constant initializer.
15306 if (HasConstInit) {
15307 if (var->isStaticDataMember() && !var->isInline() &&
15308 var->getLexicalDeclContext()->isRecord() &&
15309 type->isIntegralOrEnumerationType()) {
15310 // In C++98, in-class initialization for a static data member must
15311 // be an integer constant expression.
15312 if (!Init->isIntegerConstantExpr(Ctx: Context)) {
15313 Diag(Loc: Init->getExprLoc(),
15314 DiagID: diag::ext_in_class_initializer_non_constant)
15315 << Init->getSourceRange();
15316 }
15317 }
15318 (void)var->checkForConstantInitialization(Notes);
15319 Notes.clear();
15320 } else if (CacheCulprit) {
15321 Notes.emplace_back(Args: CacheCulprit->getExprLoc(),
15322 Args: PDiag(DiagID: diag::note_invalid_subexpr_in_const_expr));
15323 Notes.back().second << CacheCulprit->getSourceRange();
15324 }
15325 } else {
15326 // Evaluate the initializer to see if it's a constant initializer.
15327 HasConstInit = var->checkForConstantInitialization(Notes);
15328 }
15329
15330 if (HasConstInit) {
15331 // FIXME: Consider replacing the initializer with a ConstantExpr.
15332 } else if (var->isConstexpr()) {
15333 SourceLocation DiagLoc = var->getLocation();
15334 // If the note doesn't add any useful information other than a source
15335 // location, fold it into the primary diagnostic.
15336 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15337 diag::note_invalid_subexpr_in_const_expr) {
15338 DiagLoc = Notes[0].first;
15339 Notes.clear();
15340 }
15341 Diag(Loc: DiagLoc, DiagID: diag::err_constexpr_var_requires_const_init)
15342 << var << Init->getSourceRange();
15343 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15344 Diag(Loc: Notes[I].first, PD: Notes[I].second);
15345 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15346 auto *Attr = var->getAttr<ConstInitAttr>();
15347 Diag(Loc: var->getLocation(), DiagID: diag::err_require_constant_init_failed)
15348 << Init->getSourceRange();
15349 Diag(Loc: Attr->getLocation(), DiagID: diag::note_declared_required_constant_init_here)
15350 << Attr->getRange() << Attr->isConstinit();
15351 for (auto &it : Notes)
15352 Diag(Loc: it.first, PD: it.second);
15353 } else if (var->isStaticDataMember() && !var->isInline() &&
15354 var->getLexicalDeclContext()->isRecord()) {
15355 Diag(Loc: var->getLocation(), DiagID: diag::err_in_class_initializer_non_constant)
15356 << Init->getSourceRange();
15357 for (auto &it : Notes)
15358 Diag(Loc: it.first, PD: it.second);
15359 var->setInvalidDecl();
15360 } else if (IsGlobal &&
15361 !getDiagnostics().isIgnored(DiagID: diag::warn_global_constructor,
15362 Loc: var->getLocation())) {
15363 // Warn about globals which don't have a constant initializer. Don't
15364 // warn about globals with a non-trivial destructor because we already
15365 // warned about them.
15366 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15367 if (!(RD && !RD->hasTrivialDestructor())) {
15368 // checkConstInit() here permits trivial default initialization even in
15369 // C++11 onwards, where such an initializer is not a constant initializer
15370 // but nonetheless doesn't require a global constructor.
15371 if (!checkConstInit())
15372 Diag(Loc: var->getLocation(), DiagID: diag::warn_global_constructor)
15373 << Init->getSourceRange();
15374 }
15375 }
15376 }
15377
15378 // Apply section attributes and pragmas to global variables.
15379 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15380 !inTemplateInstantiation()) {
15381 PragmaStack<StringLiteral *> *Stack = nullptr;
15382 int SectionFlags = ASTContext::PSF_Read;
15383 bool MSVCEnv =
15384 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15385 std::optional<QualType::NonConstantStorageReason> Reason;
15386 if (HasConstInit &&
15387 !(Reason = var->getType().isNonConstantStorage(Ctx: Context, ExcludeCtor: true, ExcludeDtor: false))) {
15388 Stack = &ConstSegStack;
15389 } else {
15390 SectionFlags |= ASTContext::PSF_Write;
15391 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15392 }
15393 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15394 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15395 SectionFlags |= ASTContext::PSF_Implicit;
15396 UnifySection(SectionName: SA->getName(), SectionFlags, TheDecl: var);
15397 } else if (Stack->CurrentValue) {
15398 if (Stack != &ConstSegStack && MSVCEnv &&
15399 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15400 var->getType().isConstQualified()) {
15401 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15402 NonConstNonReferenceType) &&
15403 "This case should've already been handled elsewhere");
15404 Diag(Loc: var->getLocation(), DiagID: diag::warn_section_msvc_compat)
15405 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15406 ? QualType::NonConstantStorageReason::NonTrivialCtor
15407 : *Reason);
15408 }
15409 SectionFlags |= ASTContext::PSF_Implicit;
15410 auto SectionName = Stack->CurrentValue->getString();
15411 var->addAttr(A: SectionAttr::CreateImplicit(Ctx&: Context, Name: SectionName,
15412 Range: Stack->CurrentPragmaLocation,
15413 S: SectionAttr::Declspec_allocate));
15414 if (UnifySection(SectionName, SectionFlags, TheDecl: var))
15415 var->dropAttr<SectionAttr>();
15416 }
15417
15418 // Apply the init_seg attribute if this has an initializer. If the
15419 // initializer turns out to not be dynamic, we'll end up ignoring this
15420 // attribute.
15421 if (CurInitSeg && var->getInit())
15422 var->addAttr(A: InitSegAttr::CreateImplicit(Ctx&: Context, Section: CurInitSeg->getString(),
15423 Range: CurInitSegLoc));
15424 }
15425
15426 // All the following checks are C++ only.
15427 if (!getLangOpts().CPlusPlus) {
15428 // If this variable must be emitted, add it as an initializer for the
15429 // current module.
15430 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty())
15431 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15432 return;
15433 }
15434
15435 DiagnoseUniqueObjectDuplication(VD: var);
15436
15437 // Require the destructor.
15438 if (!type->isDependentType())
15439 if (auto *RD = baseType->getAsCXXRecordDecl())
15440 FinalizeVarWithDestructor(VD: var, DeclInit: RD);
15441
15442 // If this variable must be emitted, add it as an initializer for the current
15443 // module. For named modules, discardable inline variables may be deferred
15444 // until they are odr-used. Non-inline variables that must be emitted,
15445 // including those with side-effecting initialization, must still be emitted
15446 // even if they have internal linkage.
15447 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty()) {
15448 GVALinkage Linkage = Context.GetGVALinkageForVariable(VD: var);
15449 if (ModuleScopes.back().Module->isHeaderLikeModule() ||
15450 !isDiscardableGVALinkage(L: Linkage) ||
15451 (Linkage == GVA_Internal && !var->isInline()))
15452 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15453 }
15454
15455 // Build the bindings if this is a structured binding declaration.
15456 if (auto *DD = dyn_cast<DecompositionDecl>(Val: var))
15457 CheckCompleteDecompositionDeclaration(DD);
15458}
15459
15460void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
15461 assert(VD->isStaticLocal());
15462
15463 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15464
15465 // Find outermost function when VD is in lambda function.
15466 while (FD && !getDLLAttr(D: FD) &&
15467 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15468 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15469 FD = dyn_cast_or_null<FunctionDecl>(Val: FD->getParentFunctionOrMethod());
15470 }
15471
15472 if (!FD)
15473 return;
15474
15475 // Static locals inherit dll attributes from their function.
15476 if (Attr *A = getDLLAttr(D: FD)) {
15477 auto *NewAttr = cast<InheritableAttr>(Val: A->clone(C&: getASTContext()));
15478 NewAttr->setInherited(true);
15479 VD->addAttr(A: NewAttr);
15480 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15481 auto *NewAttr = DLLExportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15482 NewAttr->setInherited(true);
15483 VD->addAttr(A: NewAttr);
15484
15485 // Export this function to enforce exporting this static variable even
15486 // if it is not used in this compilation unit.
15487 if (!FD->hasAttr<DLLExportAttr>())
15488 FD->addAttr(A: NewAttr);
15489
15490 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15491 auto *NewAttr = DLLImportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15492 NewAttr->setInherited(true);
15493 VD->addAttr(A: NewAttr);
15494 }
15495}
15496
15497void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
15498 assert(VD->getTLSKind());
15499
15500 // Perform TLS alignment check here after attributes attached to the variable
15501 // which may affect the alignment have been processed. Only perform the check
15502 // if the target has a maximum TLS alignment (zero means no constraints).
15503 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15504 // Protect the check so that it's not performed on dependent types and
15505 // dependent alignments (we can't determine the alignment in that case).
15506 if (!VD->hasDependentAlignment()) {
15507 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(BitSize: MaxAlign);
15508 if (Context.getDeclAlign(D: VD) > MaxAlignChars) {
15509 Diag(Loc: VD->getLocation(), DiagID: diag::err_tls_var_aligned_over_maximum)
15510 << (unsigned)Context.getDeclAlign(D: VD).getQuantity() << VD
15511 << (unsigned)MaxAlignChars.getQuantity();
15512 }
15513 }
15514 }
15515}
15516
15517void Sema::FinalizeDeclaration(Decl *ThisDecl) {
15518 // Note that we are no longer parsing the initializer for this declaration.
15519 ParsingInitForAutoVars.erase(Ptr: ThisDecl);
15520
15521 VarDecl *VD = dyn_cast_or_null<VarDecl>(Val: ThisDecl);
15522 if (!VD)
15523 return;
15524
15525 // Emit any deferred warnings for the variable's initializer, even if the
15526 // variable is invalid
15527 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15528
15529 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15530 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
15531 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15532 if (PragmaClangBSSSection.Valid)
15533 VD->addAttr(A: PragmaClangBSSSectionAttr::CreateImplicit(
15534 Ctx&: Context, Name: PragmaClangBSSSection.SectionName,
15535 Range: PragmaClangBSSSection.PragmaLocation));
15536 if (PragmaClangDataSection.Valid)
15537 VD->addAttr(A: PragmaClangDataSectionAttr::CreateImplicit(
15538 Ctx&: Context, Name: PragmaClangDataSection.SectionName,
15539 Range: PragmaClangDataSection.PragmaLocation));
15540 if (PragmaClangRodataSection.Valid)
15541 VD->addAttr(A: PragmaClangRodataSectionAttr::CreateImplicit(
15542 Ctx&: Context, Name: PragmaClangRodataSection.SectionName,
15543 Range: PragmaClangRodataSection.PragmaLocation));
15544 if (PragmaClangRelroSection.Valid)
15545 VD->addAttr(A: PragmaClangRelroSectionAttr::CreateImplicit(
15546 Ctx&: Context, Name: PragmaClangRelroSection.SectionName,
15547 Range: PragmaClangRelroSection.PragmaLocation));
15548 }
15549
15550 if (auto *DD = dyn_cast<DecompositionDecl>(Val: ThisDecl)) {
15551 for (auto *BD : DD->bindings()) {
15552 FinalizeDeclaration(ThisDecl: BD);
15553 }
15554 }
15555
15556 CheckInvalidBuiltinCountedByRef(E: VD->getInit(),
15557 K: BuiltinCountedByRefKind::Initializer);
15558
15559 checkAttributesAfterMerging(S&: *this, ND&: *VD);
15560
15561 if (VD->isStaticLocal())
15562 CheckStaticLocalForDllExport(VD);
15563
15564 if (VD->getTLSKind())
15565 CheckThreadLocalForLargeAlignment(VD);
15566
15567 // Perform check for initializers of device-side global variables.
15568 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15569 // 7.5). We must also apply the same checks to all __shared__
15570 // variables whether they are local or not. CUDA also allows
15571 // constant initializers for __constant__ and __device__ variables.
15572 if (getLangOpts().CUDA)
15573 CUDA().checkAllowedInitializer(VD);
15574
15575 // Grab the dllimport or dllexport attribute off of the VarDecl.
15576 const InheritableAttr *DLLAttr = getDLLAttr(D: VD);
15577
15578 // Imported static data members cannot be defined out-of-line.
15579 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(Val: DLLAttr)) {
15580 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15581 VD->isThisDeclarationADefinition()) {
15582 // We allow definitions of dllimport class template static data members
15583 // with a warning.
15584 CXXRecordDecl *Context =
15585 cast<CXXRecordDecl>(Val: VD->getFirstDecl()->getDeclContext());
15586 bool IsClassTemplateMember =
15587 isa<ClassTemplatePartialSpecializationDecl>(Val: Context) ||
15588 Context->getDescribedClassTemplate();
15589
15590 Diag(Loc: VD->getLocation(),
15591 DiagID: IsClassTemplateMember
15592 ? diag::warn_attribute_dllimport_static_field_definition
15593 : diag::err_attribute_dllimport_static_field_definition);
15594 Diag(Loc: IA->getLocation(), DiagID: diag::note_attribute);
15595 if (!IsClassTemplateMember)
15596 VD->setInvalidDecl();
15597 }
15598 }
15599
15600 // dllimport/dllexport variables cannot be thread local, their TLS index
15601 // isn't exported with the variable.
15602 if (DLLAttr && VD->getTLSKind()) {
15603 auto *F = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15604 if (F && getDLLAttr(D: F)) {
15605 assert(VD->isStaticLocal());
15606 // But if this is a static local in a dlimport/dllexport function, the
15607 // function will never be inlined, which means the var would never be
15608 // imported, so having it marked import/export is safe.
15609 } else {
15610 Diag(Loc: VD->getLocation(), DiagID: diag::err_attribute_dll_thread_local) << VD
15611 << DLLAttr;
15612 VD->setInvalidDecl();
15613 }
15614 }
15615
15616 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15617 if (!Attr->isInherited() && !Attr->isImplicit() &&
15618 !VD->isThisDeclarationADefinition()) {
15619 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15620 << Attr;
15621 VD->dropAttr<UsedAttr>();
15622 }
15623 }
15624 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15625 if (!Attr->isInherited() && !Attr->isImplicit() &&
15626 !VD->isThisDeclarationADefinition()) {
15627 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15628 << Attr;
15629 VD->dropAttr<RetainAttr>();
15630 }
15631 }
15632
15633 const DeclContext *DC = VD->getDeclContext();
15634 // If there's a #pragma GCC visibility in scope, and this isn't a class
15635 // member, set the visibility of this variable.
15636 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
15637 AddPushedVisibilityAttribute(RD: VD);
15638
15639 // FIXME: Warn on unused var template partial specializations.
15640 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(Val: VD))
15641 MarkUnusedFileScopedDecl(D: VD);
15642
15643 // Now we have parsed the initializer and can update the table of magic
15644 // tag values.
15645 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15646 !VD->getType()->isIntegralOrEnumerationType())
15647 return;
15648
15649 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15650 const Expr *MagicValueExpr = VD->getInit();
15651 if (!MagicValueExpr) {
15652 continue;
15653 }
15654 std::optional<llvm::APSInt> MagicValueInt;
15655 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Ctx: Context))) {
15656 Diag(Loc: I->getRange().getBegin(),
15657 DiagID: diag::err_type_tag_for_datatype_not_ice)
15658 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15659 continue;
15660 }
15661 if (MagicValueInt->getActiveBits() > 64) {
15662 Diag(Loc: I->getRange().getBegin(),
15663 DiagID: diag::err_type_tag_for_datatype_too_large)
15664 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15665 continue;
15666 }
15667 uint64_t MagicValue = MagicValueInt->getZExtValue();
15668 RegisterTypeTagForDatatype(ArgumentKind: I->getArgumentKind(),
15669 MagicValue,
15670 Type: I->getMatchingCType(),
15671 LayoutCompatible: I->getLayoutCompatible(),
15672 MustBeNull: I->getMustBeNull());
15673 }
15674}
15675
15676static bool hasDeducedAuto(DeclaratorDecl *DD) {
15677 auto *VD = dyn_cast<VarDecl>(Val: DD);
15678 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15679}
15680
15681Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
15682 ArrayRef<Decl *> Group) {
15683 SmallVector<Decl*, 8> Decls;
15684
15685 if (DS.isTypeSpecOwned())
15686 Decls.push_back(Elt: DS.getRepAsDecl());
15687
15688 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15689 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15690 bool DiagnosedMultipleDecomps = false;
15691 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15692 bool DiagnosedNonDeducedAuto = false;
15693
15694 for (Decl *D : Group) {
15695 if (!D)
15696 continue;
15697 // Check if the Decl has been declared in '#pragma omp declare target'
15698 // directive and has static storage duration.
15699 if (auto *VD = dyn_cast<VarDecl>(Val: D);
15700 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15701 VD->hasGlobalStorage())
15702 OpenMP().ActOnOpenMPDeclareTargetInitializer(D);
15703 // For declarators, there are some additional syntactic-ish checks we need
15704 // to perform.
15705 if (auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
15706 if (!FirstDeclaratorInGroup)
15707 FirstDeclaratorInGroup = DD;
15708 if (!FirstDecompDeclaratorInGroup)
15709 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(Val: D);
15710 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15711 !hasDeducedAuto(DD))
15712 FirstNonDeducedAutoInGroup = DD;
15713
15714 if (FirstDeclaratorInGroup != DD) {
15715 // A decomposition declaration cannot be combined with any other
15716 // declaration in the same group.
15717 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15718 Diag(Loc: FirstDecompDeclaratorInGroup->getLocation(),
15719 DiagID: diag::err_decomp_decl_not_alone)
15720 << FirstDeclaratorInGroup->getSourceRange()
15721 << DD->getSourceRange();
15722 DiagnosedMultipleDecomps = true;
15723 }
15724
15725 // A declarator that uses 'auto' in any way other than to declare a
15726 // variable with a deduced type cannot be combined with any other
15727 // declarator in the same group.
15728 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15729 Diag(Loc: FirstNonDeducedAutoInGroup->getLocation(),
15730 DiagID: diag::err_auto_non_deduced_not_alone)
15731 << FirstNonDeducedAutoInGroup->getType()
15732 ->hasAutoForTrailingReturnType()
15733 << FirstDeclaratorInGroup->getSourceRange()
15734 << DD->getSourceRange();
15735 DiagnosedNonDeducedAuto = true;
15736 }
15737 }
15738 }
15739
15740 Decls.push_back(Elt: D);
15741 }
15742
15743 if (DeclSpec::isDeclRep(T: DS.getTypeSpecType())) {
15744 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl())) {
15745 handleTagNumbering(Tag, TagScope: S);
15746 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15747 getLangOpts().CPlusPlus)
15748 Context.addDeclaratorForUnnamedTagDecl(TD: Tag, DD: FirstDeclaratorInGroup);
15749 }
15750 }
15751
15752 return BuildDeclaratorGroup(Group: Decls);
15753}
15754
15755Sema::DeclGroupPtrTy
15756Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
15757 // C++14 [dcl.spec.auto]p7: (DR1347)
15758 // If the type that replaces the placeholder type is not the same in each
15759 // deduction, the program is ill-formed.
15760 if (Group.size() > 1) {
15761 QualType Deduced;
15762 VarDecl *DeducedDecl = nullptr;
15763 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15764 VarDecl *D = dyn_cast<VarDecl>(Val: Group[i]);
15765 if (!D || D->isInvalidDecl())
15766 break;
15767 DeducedType *DT = D->getType()->getContainedDeducedType();
15768 if (!DT || DT->getDeducedType().isNull())
15769 continue;
15770 if (Deduced.isNull()) {
15771 Deduced = DT->getDeducedType();
15772 DeducedDecl = D;
15773 } else if (!Context.hasSameType(T1: DT->getDeducedType(), T2: Deduced)) {
15774 auto *AT = dyn_cast<AutoType>(Val: DT);
15775 auto Dia = Diag(Loc: D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15776 DiagID: diag::err_auto_different_deductions)
15777 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15778 << DeducedDecl->getDeclName() << DT->getDeducedType()
15779 << D->getDeclName();
15780 if (DeducedDecl->hasInit())
15781 Dia << DeducedDecl->getInit()->getSourceRange();
15782 if (D->getInit())
15783 Dia << D->getInit()->getSourceRange();
15784 D->setInvalidDecl();
15785 break;
15786 }
15787 }
15788 }
15789
15790 ActOnDocumentableDecls(Group);
15791
15792 return DeclGroupPtrTy::make(
15793 P: DeclGroupRef::Create(C&: Context, Decls: Group.data(), NumDecls: Group.size()));
15794}
15795
15796void Sema::ActOnDocumentableDecl(Decl *D) {
15797 ActOnDocumentableDecls(Group: D);
15798}
15799
15800void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
15801 // Don't parse the comment if Doxygen diagnostics are ignored.
15802 if (Group.empty() || !Group[0])
15803 return;
15804
15805 if (!areDocumentationDiagsEnabled(Loc: Group[0]->getLocation()))
15806 return;
15807
15808 if (Group.size() >= 2) {
15809 // This is a decl group. Normally it will contain only declarations
15810 // produced from declarator list. But in case we have any definitions or
15811 // additional declaration references:
15812 // 'typedef struct S {} S;'
15813 // 'typedef struct S *S;'
15814 // 'struct S *pS;'
15815 // FinalizeDeclaratorGroup adds these as separate declarations.
15816 Decl *MaybeTagDecl = Group[0];
15817 if (MaybeTagDecl && isa<TagDecl>(Val: MaybeTagDecl)) {
15818 Group = Group.slice(N: 1);
15819 }
15820 }
15821
15822 // FIXME: We assume every Decl in the group is in the same file.
15823 // This is false when preprocessor constructs the group from decls in
15824 // different files (e. g. macros or #include).
15825 Context.attachCommentsToJustParsedDecls(Decls: Group, PP: &getPreprocessor());
15826}
15827
15828void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
15829 // Check that there are no default arguments inside the type of this
15830 // parameter.
15831 if (getLangOpts().CPlusPlus)
15832 CheckExtraCXXDefaultArguments(D);
15833
15834 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15835 if (D.getCXXScopeSpec().isSet()) {
15836 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_param_declarator)
15837 << D.getCXXScopeSpec().getRange();
15838 }
15839
15840 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15841 // simple identifier except [...irrelevant cases...].
15842 switch (D.getName().getKind()) {
15843 case UnqualifiedIdKind::IK_Identifier:
15844 break;
15845
15846 case UnqualifiedIdKind::IK_OperatorFunctionId:
15847 case UnqualifiedIdKind::IK_ConversionFunctionId:
15848 case UnqualifiedIdKind::IK_LiteralOperatorId:
15849 case UnqualifiedIdKind::IK_ConstructorName:
15850 case UnqualifiedIdKind::IK_DestructorName:
15851 case UnqualifiedIdKind::IK_ImplicitSelfParam:
15852 case UnqualifiedIdKind::IK_DeductionGuideName:
15853 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name)
15854 << GetNameForDeclarator(D).getName();
15855 break;
15856
15857 case UnqualifiedIdKind::IK_TemplateId:
15858 case UnqualifiedIdKind::IK_ConstructorTemplateId:
15859 // GetNameForDeclarator would not produce a useful name in this case.
15860 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name_template_id);
15861 break;
15862 }
15863}
15864
15865void Sema::warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D) {
15866 // This only matters in C.
15867 if (getLangOpts().CPlusPlus)
15868 return;
15869
15870 // This only matters if the declaration has a type.
15871 const auto *VD = dyn_cast<ValueDecl>(Val: D);
15872 if (!VD)
15873 return;
15874
15875 // Get the type, this only matters for tag types.
15876 QualType QT = VD->getType();
15877 const auto *TD = QT->getAsTagDecl();
15878 if (!TD)
15879 return;
15880
15881 // Check if the tag declaration is lexically declared somewhere different
15882 // from the lexical declaration of the given object, then it will be hidden
15883 // in C++ and we should warn on it.
15884 if (!TD->getLexicalParent()->LexicallyEncloses(DC: D->getLexicalDeclContext())) {
15885 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15886 Diag(Loc: D->getLocation(), DiagID: diag::warn_decl_hidden_in_cpp) << Kind;
15887 Diag(Loc: TD->getLocation(), DiagID: diag::note_declared_at);
15888 }
15889}
15890
15891static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
15892 SourceLocation ExplicitThisLoc) {
15893 if (!ExplicitThisLoc.isValid())
15894 return;
15895 assert(S.getLangOpts().CPlusPlus &&
15896 "explicit parameter in non-cplusplus mode");
15897 if (!S.getLangOpts().CPlusPlus23)
15898 S.Diag(Loc: ExplicitThisLoc, DiagID: diag::err_cxx20_deducing_this)
15899 << P->getSourceRange();
15900
15901 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15902 // parameter pack.
15903 if (P->isParameterPack()) {
15904 S.Diag(Loc: P->getBeginLoc(), DiagID: diag::err_explicit_object_parameter_pack)
15905 << P->getSourceRange();
15906 return;
15907 }
15908 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15909 if (LambdaScopeInfo *LSI = S.getCurLambda())
15910 LSI->ExplicitObjectParameter = P;
15911}
15912
15913Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15914 SourceLocation ExplicitThisLoc) {
15915 const DeclSpec &DS = D.getDeclSpec();
15916
15917 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15918 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15919 // except for the special case of a single unnamed parameter of type void
15920 // with no storage class specifier, no type qualifier, and no following
15921 // ellipsis terminator.
15922 // Clang applies the C2y rules for 'register void' in all C language modes,
15923 // same as GCC, because it's questionable what that could possibly mean.
15924
15925 // C++03 [dcl.stc]p2 also permits 'auto'.
15926 StorageClass SC = SC_None;
15927 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15928 SC = SC_Register;
15929 // In C++11, the 'register' storage class specifier is deprecated.
15930 // In C++17, it is not allowed, but we tolerate it as an extension.
15931 if (getLangOpts().CPlusPlus11) {
15932 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus17
15933 ? diag::ext_register_storage_class
15934 : diag::warn_deprecated_register)
15935 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15936 } else if (!getLangOpts().CPlusPlus &&
15937 DS.getTypeSpecType() == DeclSpec::TST_void &&
15938 D.getNumTypeObjects() == 0) {
15939 Diag(Loc: DS.getStorageClassSpecLoc(),
15940 DiagID: diag::err_invalid_storage_class_in_func_decl)
15941 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15942 D.getMutableDeclSpec().ClearStorageClassSpecs();
15943 }
15944 } else if (getLangOpts().CPlusPlus &&
15945 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
15946 SC = SC_Auto;
15947 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15948 Diag(Loc: DS.getStorageClassSpecLoc(),
15949 DiagID: diag::err_invalid_storage_class_in_func_decl);
15950 D.getMutableDeclSpec().ClearStorageClassSpecs();
15951 }
15952
15953 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15954 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID: diag::err_invalid_thread)
15955 << DeclSpec::getSpecifierName(S: TSCS);
15956 if (DS.isInlineSpecified())
15957 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
15958 << getLangOpts().CPlusPlus17;
15959 if (DS.hasConstexprSpecifier())
15960 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
15961 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15962
15963 DiagnoseFunctionSpecifiers(DS);
15964
15965 CheckFunctionOrTemplateParamDeclarator(S, D);
15966
15967 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
15968 QualType parmDeclType = TInfo->getType();
15969
15970 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15971 const IdentifierInfo *II = D.getIdentifier();
15972 if (II) {
15973 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15974 RedeclarationKind::ForVisibleRedeclaration);
15975 LookupName(R, S);
15976 if (!R.empty()) {
15977 NamedDecl *PrevDecl = *R.begin();
15978 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15979 // Maybe we will complain about the shadowed template parameter.
15980 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
15981 // Just pretend that we didn't see the previous declaration.
15982 PrevDecl = nullptr;
15983 }
15984 if (PrevDecl && S->isDeclScope(D: PrevDecl)) {
15985 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_param_redefinition) << II;
15986 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
15987 // Recover by removing the name
15988 II = nullptr;
15989 D.SetIdentifier(Id: nullptr, IdLoc: D.getIdentifierLoc());
15990 D.setInvalidType(true);
15991 }
15992 }
15993 }
15994
15995 // Incomplete resource arrays are not allowed as function parameters in HLSL
15996 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType()) {
15997 QualType EltTy = Context.getBaseElementType(QT: parmDeclType);
15998 // `isCompleteType` forces completion of the element type so the resource
15999 // check is valid.
16000 if (!EltTy->isDependentType() &&
16001 isCompleteType(Loc: D.getIdentifierLoc(), T: EltTy) &&
16002 parmDeclType->isHLSLResourceRecordArray()) {
16003 Diag(Loc: D.getIdentifierLoc(),
16004 DiagID: diag::err_hlsl_incomplete_resource_array_in_function_param);
16005 D.setInvalidType(true);
16006 }
16007 }
16008
16009 // Temporarily put parameter variables in the translation unit, not
16010 // the enclosing context. This prevents them from accidentally
16011 // looking like class members in C++.
16012 ParmVarDecl *New =
16013 CheckParameter(DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
16014 NameLoc: D.getIdentifierLoc(), Name: II, T: parmDeclType, TSInfo: TInfo, SC);
16015
16016 if (D.isInvalidType())
16017 New->setInvalidDecl();
16018
16019 CheckExplicitObjectParameter(S&: *this, P: New, ExplicitThisLoc);
16020
16021 assert(S->isFunctionPrototypeScope());
16022 assert(S->getFunctionPrototypeDepth() >= 1);
16023 New->setScopeInfo(scopeDepth: S->getFunctionPrototypeDepth() - 1,
16024 parameterIndex: S->getNextFunctionPrototypeIndex());
16025
16026 warnOnCTypeHiddenInCPlusPlus(D: New);
16027
16028 // Add the parameter declaration into this scope.
16029 S->AddDecl(D: New);
16030 if (II)
16031 IdResolver.AddDecl(D: New);
16032
16033 ProcessDeclAttributes(S, D: New, PD: D);
16034
16035 if (D.getDeclSpec().isModulePrivateSpecified())
16036 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_local)
16037 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16038 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
16039
16040 if (New->hasAttr<BlocksAttr>())
16041 Diag(Loc: New->getLocation(), DiagID: diag::err_block_not_allowed_on)
16042 << diag::NotAllowedBlockVarReason::NonlocalVariable;
16043
16044 New->deduceParmAddressSpace(Ctxt: Context);
16045
16046 return New;
16047}
16048
16049ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
16050 SourceLocation Loc,
16051 QualType T) {
16052 /* FIXME: setting StartLoc == Loc.
16053 Would it be worth to modify callers so as to provide proper source
16054 location for the unnamed parameters, embedding the parameter's type? */
16055 ParmVarDecl *Param = ParmVarDecl::Create(C&: Context, DC, StartLoc: Loc, IdLoc: Loc, Id: nullptr,
16056 T, TInfo: Context.getTrivialTypeSourceInfo(T, Loc),
16057 S: SC_None, DefArg: nullptr);
16058 Param->setImplicit();
16059 return Param;
16060}
16061
16062void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
16063 // Don't diagnose unused-parameter errors in template instantiations; we
16064 // will already have done so in the template itself.
16065 if (inTemplateInstantiation())
16066 return;
16067
16068 for (const ParmVarDecl *Parameter : Parameters) {
16069 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
16070 !Parameter->hasAttr<UnusedAttr>() &&
16071 !Parameter->getIdentifier()->isPlaceholder()) {
16072 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_unused_parameter)
16073 << Parameter->getDeclName();
16074 }
16075 }
16076}
16077
16078void Sema::DiagnoseSizeOfParametersAndReturnValue(
16079 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
16080 if (LangOpts.NumLargeByValueCopy == 0) // No check.
16081 return;
16082
16083 // Warn if the return value is pass-by-value and larger than the specified
16084 // threshold.
16085 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
16086 unsigned Size = Context.getTypeSizeInChars(T: ReturnTy).getQuantity();
16087 if (Size > LangOpts.NumLargeByValueCopy)
16088 Diag(Loc: D->getLocation(), DiagID: diag::warn_return_value_size) << D << Size;
16089 }
16090
16091 // Warn if any parameter is pass-by-value and larger than the specified
16092 // threshold.
16093 for (const ParmVarDecl *Parameter : Parameters) {
16094 QualType T = Parameter->getType();
16095 if (T->isDependentType() || !T.isPODType(Context))
16096 continue;
16097 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
16098 if (Size > LangOpts.NumLargeByValueCopy)
16099 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_parameter_size)
16100 << Parameter << Size;
16101 }
16102}
16103
16104ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
16105 SourceLocation NameLoc,
16106 const IdentifierInfo *Name, QualType T,
16107 TypeSourceInfo *TSInfo, StorageClass SC) {
16108 // In ARC, infer a lifetime qualifier for appropriate parameter types.
16109 if (getLangOpts().ObjCAutoRefCount &&
16110 T.getObjCLifetime() == Qualifiers::OCL_None &&
16111 T->isObjCLifetimeType()) {
16112
16113 Qualifiers::ObjCLifetime lifetime;
16114
16115 // Special cases for arrays:
16116 // - if it's const, use __unsafe_unretained
16117 // - otherwise, it's an error
16118 if (T->isArrayType()) {
16119 if (!T.isConstQualified()) {
16120 if (DelayedDiagnostics.shouldDelayDiagnostics())
16121 DelayedDiagnostics.add(
16122 diag: sema::DelayedDiagnostic::makeForbiddenType(
16123 loc: NameLoc, diagnostic: diag::err_arc_array_param_no_ownership, type: T, argument: false));
16124 else
16125 Diag(Loc: NameLoc, DiagID: diag::err_arc_array_param_no_ownership)
16126 << TSInfo->getTypeLoc().getSourceRange();
16127 }
16128 lifetime = Qualifiers::OCL_ExplicitNone;
16129 } else {
16130 lifetime = T->getObjCARCImplicitLifetime();
16131 }
16132 T = Context.getLifetimeQualifiedType(type: T, lifetime);
16133 }
16134
16135 if (getLangOpts().OpenCL) {
16136 assert(!isa<DecayedType>(T));
16137 if (T->isArrayType() && !T.hasAddressSpace()) {
16138 QualType ET = Context.getAsArrayType(T)->getElementType();
16139 if (!ET.hasAddressSpace()) {
16140 // Add the private address space to the contents of the pointer when a
16141 // pointer parameter is declared as an array and not declared.
16142 LangAS ImplAS = LangAS::opencl_private;
16143 T = Context.getAddrSpaceQualType(T, AddressSpace: ImplAS);
16144 T = QualType(Context.getAsArrayType(T), 0);
16145 }
16146 }
16147 }
16148
16149 ParmVarDecl *New = ParmVarDecl::Create(C&: Context, DC, StartLoc, IdLoc: NameLoc, Id: Name,
16150 T: Context.getAdjustedParameterType(T),
16151 TInfo: TSInfo, S: SC, DefArg: nullptr);
16152
16153 // Make a note if we created a new pack in the scope of a lambda, so that
16154 // we know that references to that pack must also be expanded within the
16155 // lambda scope.
16156 if (New->isParameterPack())
16157 if (auto *CSI = getEnclosingLambdaOrBlock())
16158 CSI->LocalPacks.push_back(Elt: New);
16159
16160 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
16161 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
16162 checkNonTrivialCUnion(QT: New->getType(), Loc: New->getLocation(),
16163 UseContext: NonTrivialCUnionContext::FunctionParam,
16164 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
16165
16166 // Parameter declarators cannot be interface types. All ObjC objects are
16167 // passed by reference.
16168 if (T->isObjCObjectType()) {
16169 SourceLocation TypeEndLoc =
16170 getLocForEndOfToken(Loc: TSInfo->getTypeLoc().getEndLoc());
16171 Diag(Loc: NameLoc,
16172 DiagID: diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
16173 << FixItHint::CreateInsertion(InsertionLoc: TypeEndLoc, Code: "*");
16174 T = Context.getObjCObjectPointerType(OIT: T);
16175 New->setType(T);
16176 }
16177
16178 // __ptrauth is forbidden on parameters.
16179 if (T.getPointerAuth()) {
16180 Diag(Loc: NameLoc, DiagID: diag::err_ptrauth_qualifier_invalid) << T << 1;
16181 New->setInvalidDecl();
16182 }
16183
16184 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
16185 // duration shall not be qualified by an address-space qualifier."
16186 // Since all parameters have automatic store duration, they can not have
16187 // an address space.
16188 if (T.getAddressSpace() != LangAS::Default &&
16189 // OpenCL allows function arguments declared to be an array of a type
16190 // to be qualified with an address space.
16191 !(getLangOpts().OpenCL &&
16192 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
16193 // WebAssembly allows reference types as parameters. Funcref in particular
16194 // lives in a different address space.
16195 !(T->isFunctionPointerType() &&
16196 T.getAddressSpace() == LangAS::wasm_funcref) &&
16197 // HLSL allows function arguments to be qualified with an address space
16198 // if the groupshared annotation is used.
16199 !(getLangOpts().HLSL &&
16200 T.getAddressSpace() == LangAS::hlsl_groupshared)) {
16201 Diag(Loc: NameLoc, DiagID: diag::err_arg_with_address_space);
16202 New->setInvalidDecl();
16203 }
16204
16205 // PPC MMA non-pointer types are not allowed as function argument types.
16206 if (Context.getTargetInfo().getTriple().isPPC64() &&
16207 PPC().CheckPPCMMAType(Type: New->getOriginalType(), TypeLoc: New->getLocation())) {
16208 New->setInvalidDecl();
16209 }
16210
16211 return New;
16212}
16213
16214void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
16215 SourceLocation LocAfterDecls) {
16216 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
16217
16218 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
16219 // in the declaration list shall have at least one declarator, those
16220 // declarators shall only declare identifiers from the identifier list, and
16221 // every identifier in the identifier list shall be declared.
16222 //
16223 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
16224 // identifiers it names shall be declared in the declaration list."
16225 //
16226 // This is why we only diagnose in C99 and later. Note, the other conditions
16227 // listed are checked elsewhere.
16228 if (!FTI.hasPrototype) {
16229 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
16230 --i;
16231 if (FTI.Params[i].Param == nullptr) {
16232 if (getLangOpts().C99) {
16233 SmallString<256> Code;
16234 llvm::raw_svector_ostream(Code)
16235 << " int " << FTI.Params[i].Ident->getName() << ";\n";
16236 Diag(Loc: FTI.Params[i].IdentLoc, DiagID: diag::ext_param_not_declared)
16237 << FTI.Params[i].Ident
16238 << FixItHint::CreateInsertion(InsertionLoc: LocAfterDecls, Code);
16239 }
16240
16241 // Implicitly declare the argument as type 'int' for lack of a better
16242 // type.
16243 AttributeFactory attrs;
16244 DeclSpec DS(attrs);
16245 const char* PrevSpec; // unused
16246 unsigned DiagID; // unused
16247 DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc: FTI.Params[i].IdentLoc, PrevSpec,
16248 DiagID, Policy: Context.getPrintingPolicy());
16249 // Use the identifier location for the type source range.
16250 DS.SetRangeStart(FTI.Params[i].IdentLoc);
16251 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
16252 Declarator ParamD(DS, ParsedAttributesView::none(),
16253 DeclaratorContext::KNRTypeList);
16254 ParamD.SetIdentifier(Id: FTI.Params[i].Ident, IdLoc: FTI.Params[i].IdentLoc);
16255 FTI.Params[i].Param = ActOnParamDeclarator(S, D&: ParamD);
16256 }
16257 }
16258 }
16259}
16260
16261Decl *
16262Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
16263 MultiTemplateParamsArg TemplateParameterLists,
16264 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
16265 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
16266 assert(D.isFunctionDeclarator() && "Not a function declarator!");
16267 Scope *ParentScope = FnBodyScope->getParent();
16268
16269 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
16270 // we define a non-templated function definition, we will create a declaration
16271 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
16272 // The base function declaration will have the equivalent of an `omp declare
16273 // variant` annotation which specifies the mangled definition as a
16274 // specialization function under the OpenMP context defined as part of the
16275 // `omp begin declare variant`.
16276 SmallVector<FunctionDecl *, 4> Bases;
16277 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
16278 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
16279 S: ParentScope, D, TemplateParameterLists, Bases);
16280
16281 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
16282 Decl *DP = HandleDeclarator(S: ParentScope, D, TemplateParamLists: TemplateParameterLists);
16283 Decl *Dcl = ActOnStartOfFunctionDef(S: FnBodyScope, D: DP, SkipBody, BodyKind);
16284
16285 if (!Bases.empty())
16286 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
16287 Bases);
16288
16289 return Dcl;
16290}
16291
16292void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
16293 Consumer.HandleInlineFunctionDefinition(D);
16294}
16295
16296static bool FindPossiblePrototype(const FunctionDecl *FD,
16297 const FunctionDecl *&PossiblePrototype) {
16298 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
16299 Prev = Prev->getPreviousDecl()) {
16300 // Ignore any declarations that occur in function or method
16301 // scope, because they aren't visible from the header.
16302 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
16303 continue;
16304
16305 PossiblePrototype = Prev;
16306 return Prev->getType()->isFunctionProtoType();
16307 }
16308 return false;
16309}
16310
16311static bool
16312ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
16313 const FunctionDecl *&PossiblePrototype) {
16314 // Don't warn about invalid declarations.
16315 if (FD->isInvalidDecl())
16316 return false;
16317
16318 // Or declarations that aren't global.
16319 if (!FD->isGlobal())
16320 return false;
16321
16322 // Don't warn about C++ member functions.
16323 if (isa<CXXMethodDecl>(Val: FD))
16324 return false;
16325
16326 // Don't warn about 'main'.
16327 if (isa<TranslationUnitDecl>(Val: FD->getDeclContext()->getRedeclContext()))
16328 if (IdentifierInfo *II = FD->getIdentifier())
16329 if (II->isStr(Str: "main") || II->isStr(Str: "efi_main"))
16330 return false;
16331
16332 if (FD->isMSVCRTEntryPoint())
16333 return false;
16334
16335 // Don't warn about inline functions.
16336 if (FD->isInlined())
16337 return false;
16338
16339 // Don't warn about function templates.
16340 if (FD->getDescribedFunctionTemplate())
16341 return false;
16342
16343 // Don't warn about function template specializations.
16344 if (FD->isFunctionTemplateSpecialization())
16345 return false;
16346
16347 // Don't warn for OpenCL kernels.
16348 if (FD->hasAttr<DeviceKernelAttr>())
16349 return false;
16350
16351 // Don't warn on explicitly deleted functions.
16352 if (FD->isDeleted())
16353 return false;
16354
16355 // Don't warn on implicitly local functions (such as having local-typed
16356 // parameters).
16357 if (!FD->isExternallyVisible())
16358 return false;
16359
16360 // If we were able to find a potential prototype, don't warn.
16361 if (FindPossiblePrototype(FD, PossiblePrototype))
16362 return false;
16363
16364 return true;
16365}
16366
16367void
16368Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
16369 const FunctionDecl *EffectiveDefinition,
16370 SkipBodyInfo *SkipBody) {
16371 const FunctionDecl *Definition = EffectiveDefinition;
16372 if (!Definition &&
16373 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16374 return;
16375
16376 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16377 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16378 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16379 // A merged copy of the same function, instantiated as a member of
16380 // the same class, is OK.
16381 if (declaresSameEntity(D1: OrigFD, D2: OrigDef) &&
16382 declaresSameEntity(D1: cast<Decl>(Val: Definition->getLexicalDeclContext()),
16383 D2: cast<Decl>(Val: FD->getLexicalDeclContext())))
16384 return;
16385 }
16386 }
16387 }
16388
16389 if (canRedefineFunction(FD: Definition, LangOpts: getLangOpts()))
16390 return;
16391
16392 // Don't emit an error when this is redefinition of a typo-corrected
16393 // definition.
16394 if (TypoCorrectedFunctionDefinitions.count(Ptr: Definition))
16395 return;
16396
16397 bool DefinitionVisible = false;
16398 if (SkipBody &&
16399 isRedefinitionAllowedFor(D: Definition, NewLoc: FD->getLocation(),
16400 Visible&: DefinitionVisible) &&
16401 (Definition->getFormalLinkage() == Linkage::Internal ||
16402 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16403 !Definition->getTemplateParameterLists().empty())) {
16404 SkipBody->ShouldSkip = true;
16405 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16406 if (!DefinitionVisible) {
16407 if (auto *TD = Definition->getDescribedFunctionTemplate())
16408 makeMergedDefinitionVisible(ND: TD);
16409 makeMergedDefinitionVisible(ND: const_cast<FunctionDecl *>(Definition));
16410 }
16411 return;
16412 }
16413
16414 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16415 Definition->getStorageClass() == SC_Extern)
16416 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition_extern_inline)
16417 << FD << getLangOpts().CPlusPlus;
16418 else
16419 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition) << FD;
16420
16421 Diag(Loc: Definition->getLocation(), DiagID: diag::note_previous_definition);
16422 FD->setInvalidDecl();
16423}
16424
16425LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
16426 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16427
16428 LambdaScopeInfo *LSI = PushLambdaScope();
16429 LSI->CallOperator = CallOperator;
16430 LSI->Lambda = LambdaClass;
16431 LSI->ReturnType = CallOperator->getReturnType();
16432 // When this function is called in situation where the context of the call
16433 // operator is not entered, we set AfterParameterList to false, so that
16434 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16435 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16436 // where we would set the CurContext to the lambda operator before
16437 // substituting into it. In this case the flag needs to be true such that
16438 // tryCaptureVariable can correctly handle potential captures thereof.
16439 LSI->AfterParameterList = CurContext == CallOperator;
16440 LSI->BeforeCompoundStatement = false;
16441
16442 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16443 // used at the point of dealing with potential captures.
16444 //
16445 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16446 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16447 // associated. (Technically, we could recover that list from their
16448 // instantiation patterns, but for now, the GLTemplateParameterList seems
16449 // unnecessary in these cases.)
16450 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16451 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16452 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16453
16454 if (LCD == LCD_None)
16455 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
16456 else if (LCD == LCD_ByCopy)
16457 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
16458 else if (LCD == LCD_ByRef)
16459 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
16460 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16461
16462 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
16463 LSI->Mutable = !CallOperator->isConst();
16464 if (CallOperator->isExplicitObjectMemberFunction())
16465 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(i: 0);
16466
16467 // Add the captures to the LSI so they can be noted as already
16468 // captured within tryCaptureVar.
16469 auto I = LambdaClass->field_begin();
16470 for (const auto &C : LambdaClass->captures()) {
16471 if (C.capturesVariable()) {
16472 ValueDecl *VD = C.getCapturedVar();
16473 if (VD->isInitCapture())
16474 CurrentInstantiationScope->InstantiatedLocal(D: VD, Inst: VD);
16475 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16476 LSI->addCapture(Var: VD, /*IsBlock*/isBlock: false, isByref: ByRef,
16477 /*RefersToEnclosingVariableOrCapture*/isNested: true, Loc: C.getLocation(),
16478 /*EllipsisLoc*/C.isPackExpansion()
16479 ? C.getEllipsisLoc() : SourceLocation(),
16480 CaptureType: I->getType(), /*Invalid*/false);
16481
16482 } else if (C.capturesThis()) {
16483 LSI->addThisCapture(/*Nested*/ isNested: false, Loc: C.getLocation(), CaptureType: I->getType(),
16484 ByCopy: C.getCaptureKind() == LCK_StarThis);
16485 } else {
16486 LSI->addVLATypeCapture(Loc: C.getLocation(), VLAType: I->getCapturedVLAType(),
16487 CaptureType: I->getType());
16488 }
16489 ++I;
16490 }
16491 return LSI;
16492}
16493
16494Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
16495 SkipBodyInfo *SkipBody,
16496 FnBodyKind BodyKind) {
16497 if (!D) {
16498 // Parsing the function declaration failed in some way. Push on a fake scope
16499 // anyway so we can try to parse the function body.
16500 PushFunctionScope();
16501 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16502 return D;
16503 }
16504
16505 FunctionDecl *FD = nullptr;
16506
16507 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D))
16508 FD = FunTmpl->getTemplatedDecl();
16509 else
16510 FD = cast<FunctionDecl>(Val: D);
16511
16512 // Do not push if it is a lambda because one is already pushed when building
16513 // the lambda in ActOnStartOfLambdaDefinition().
16514 if (!isLambdaCallOperator(DC: FD))
16515 PushExpressionEvaluationContextForFunction(NewContext: ExprEvalContexts.back().Context,
16516 FD);
16517
16518 // Check for defining attributes before the check for redefinition.
16519 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16520 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 0;
16521 FD->dropAttr<AliasAttr>();
16522 FD->setInvalidDecl();
16523 }
16524 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16525 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 1;
16526 FD->dropAttr<IFuncAttr>();
16527 FD->setInvalidDecl();
16528 }
16529 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16530 if (Context.getTargetInfo().getTriple().isAArch64() &&
16531 !Context.getTargetInfo().hasFeature(Feature: "fmv") &&
16532 !Attr->isDefaultVersion()) {
16533 // If function multi versioning disabled skip parsing function body
16534 // defined with non-default target_version attribute
16535 if (SkipBody)
16536 SkipBody->ShouldSkip = true;
16537 return nullptr;
16538 }
16539 }
16540
16541 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
16542 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16543 Ctor->isDefaultConstructor() &&
16544 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16545 // If this is an MS ABI dllexport default constructor, instantiate any
16546 // default arguments.
16547 if (DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>())
16548 BuildCtorClosureDefaultArgs(Loc: Attr->getLocation(), Ctor);
16549 }
16550 }
16551
16552 // See if this is a redefinition. If 'will have body' (or similar) is already
16553 // set, then these checks were already performed when it was set.
16554 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16555 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
16556 CheckForFunctionRedefinition(FD, EffectiveDefinition: nullptr, SkipBody);
16557
16558 // If we're skipping the body, we're done. Don't enter the scope.
16559 if (SkipBody && SkipBody->ShouldSkip)
16560 return D;
16561 }
16562
16563 // Mark this function as "will have a body eventually". This lets users to
16564 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16565 // this function.
16566 FD->setWillHaveBody();
16567
16568 // If we are instantiating a generic lambda call operator, push
16569 // a LambdaScopeInfo onto the function stack. But use the information
16570 // that's already been calculated (ActOnLambdaExpr) to prime the current
16571 // LambdaScopeInfo.
16572 // When the template operator is being specialized, the LambdaScopeInfo,
16573 // has to be properly restored so that tryCaptureVariable doesn't try
16574 // and capture any new variables. In addition when calculating potential
16575 // captures during transformation of nested lambdas, it is necessary to
16576 // have the LSI properly restored.
16577 if (isGenericLambdaCallOperatorSpecialization(DC: FD)) {
16578 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16579 // specialized.
16580 if (FD->getTemplateSpecializationInfo()->isExplicitSpecialization()) {
16581 Diag(Loc: FD->getLocation(), DiagID: diag::err_lambda_explicit_temp_spec)
16582 << /*specialization*/ 0;
16583 CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: FD->getParent());
16584 Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here) << RD;
16585
16586 FD->setInvalidDecl();
16587 PushFunctionScope();
16588 } else {
16589 assert(inTemplateInstantiation() &&
16590 "There should be an active template instantiation on the stack "
16591 "when instantiating a generic lambda!");
16592 RebuildLambdaScopeInfo(CallOperator: cast<CXXMethodDecl>(Val: D));
16593 }
16594 } else {
16595 // Enter a new function scope
16596 PushFunctionScope();
16597 }
16598
16599 // Builtin functions cannot be defined.
16600 if (unsigned BuiltinID = FD->getBuiltinID()) {
16601 if (!Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID) &&
16602 !Context.BuiltinInfo.isPredefinedRuntimeFunction(ID: BuiltinID)) {
16603 Diag(Loc: FD->getLocation(), DiagID: diag::err_builtin_definition) << FD;
16604 FD->setInvalidDecl();
16605 }
16606 }
16607
16608 // The return type of a function definition must be complete (C99 6.9.1p3).
16609 // C++23 [dcl.fct.def.general]/p2
16610 // The type of [...] the return for a function definition
16611 // shall not be a (possibly cv-qualified) class type that is incomplete
16612 // or abstract within the function body unless the function is deleted.
16613 QualType ResultType = FD->getReturnType();
16614 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16615 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16616 (RequireCompleteType(Loc: FD->getLocation(), T: ResultType,
16617 DiagID: diag::err_func_def_incomplete_result) ||
16618 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getReturnType(),
16619 DiagID: diag::err_abstract_type_in_decl,
16620 Args: AbstractReturnType)))
16621 FD->setInvalidDecl();
16622
16623 if (FnBodyScope)
16624 PushDeclContext(S: FnBodyScope, DC: FD);
16625
16626 // Check the validity of our function parameters
16627 if (BodyKind != FnBodyKind::Delete)
16628 CheckParmsForFunctionDef(Parameters: FD->parameters(),
16629 /*CheckParameterNames=*/true);
16630
16631 // Add non-parameter declarations already in the function to the current
16632 // scope.
16633 if (FnBodyScope) {
16634 for (Decl *NPD : FD->decls()) {
16635 auto *NonParmDecl = dyn_cast<NamedDecl>(Val: NPD);
16636 if (!NonParmDecl)
16637 continue;
16638 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16639 "parameters should not be in newly created FD yet");
16640
16641 // If the decl has a name, make it accessible in the current scope.
16642 if (NonParmDecl->getDeclName())
16643 PushOnScopeChains(D: NonParmDecl, S: FnBodyScope, /*AddToContext=*/false);
16644
16645 // Similarly, dive into enums and fish their constants out, making them
16646 // accessible in this scope.
16647 if (auto *ED = dyn_cast<EnumDecl>(Val: NonParmDecl)) {
16648 for (auto *EI : ED->enumerators())
16649 PushOnScopeChains(D: EI, S: FnBodyScope, /*AddToContext=*/false);
16650 }
16651 }
16652 }
16653
16654 // Introduce our parameters into the function scope
16655 for (auto *Param : FD->parameters()) {
16656 Param->setOwningFunction(FD);
16657
16658 // If this has an identifier, add it to the scope stack.
16659 if (Param->getIdentifier() && FnBodyScope) {
16660 CheckShadow(S: FnBodyScope, D: Param);
16661
16662 PushOnScopeChains(D: Param, S: FnBodyScope);
16663 }
16664 }
16665
16666 // C++ [module.import/6]
16667 // ...
16668 // A header unit shall not contain a definition of a non-inline function or
16669 // variable whose name has external linkage.
16670 //
16671 // Deleted and Defaulted functions are implicitly inline (but the
16672 // inline state is not set at this point, so check the BodyKind explicitly).
16673 // We choose to allow weak & selectany definitions, as they are common in
16674 // headers, and have semantics similar to inline definitions which are allowed
16675 // in header units.
16676 // FIXME: Consider an alternate location for the test where the inlined()
16677 // state is complete.
16678 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16679 !FD->isInvalidDecl() && !FD->isInlined() &&
16680 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16681 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16682 !FD->isTemplateInstantiation() &&
16683 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16684 assert(FD->isThisDeclarationADefinition());
16685 Diag(Loc: FD->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
16686 FD->setInvalidDecl();
16687 }
16688
16689 // Ensure that the function's exception specification is instantiated.
16690 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16691 ResolveExceptionSpec(Loc: D->getLocation(), FPT);
16692
16693 // dllimport cannot be applied to non-inline function definitions.
16694 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16695 !FD->isTemplateInstantiation()) {
16696 assert(!FD->hasAttr<DLLExportAttr>());
16697 Diag(Loc: FD->getLocation(), DiagID: diag::err_attribute_dllimport_function_definition);
16698 FD->setInvalidDecl();
16699 return D;
16700 }
16701
16702 // Some function attributes (like OptimizeNoneAttr) need actions before
16703 // parsing body started.
16704 applyFunctionAttributesBeforeParsingBody(FD: D);
16705
16706 // We want to attach documentation to original Decl (which might be
16707 // a function template).
16708 ActOnDocumentableDecl(D);
16709 if (getCurLexicalContext()->isObjCContainer() &&
16710 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16711 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16712 Diag(Loc: FD->getLocation(), DiagID: diag::warn_function_def_in_objc_container);
16713
16714 maybeAddDeclWithEffects(D: FD);
16715
16716 if (!FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>() &&
16717 FnBodyScope) {
16718 // An implicit call expression is synthesized for functions declared with
16719 // the sycl_kernel_entry_point attribute. The call may resolve to a
16720 // function template, a member function template, or a call operator
16721 // of a variable template depending on the results of unqualified lookup
16722 // for 'sycl_kernel_launch' from the beginning of the function body.
16723 // Performing that lookup requires the stack of parsing scopes active
16724 // when the definition is parsed and is thus done here; the result is
16725 // cached in FunctionScopeInfo and used to synthesize the (possibly
16726 // unresolved) call expression after the function body has been parsed.
16727 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
16728 if (!SKEPAttr->isInvalidAttr()) {
16729 ExprResult LaunchIdExpr =
16730 SYCL().BuildSYCLKernelLaunchIdExpr(FD, KernelName: SKEPAttr->getKernelName());
16731 // Do not mark 'FD' as invalid if construction of `LaunchIDExpr` produces
16732 // an invalid result. Name lookup failure for 'sycl_kernel_launch' is
16733 // treated as an error in the definition of 'FD'; treating it as an error
16734 // of the declaration would affect overload resolution which would
16735 // potentially result in additional errors. If construction of
16736 // 'LaunchIDExpr' failed, then 'SYCLKernelLaunchIdExpr' will be assigned
16737 // a null pointer value below; that is expected.
16738 getCurFunction()->SYCLKernelLaunchIdExpr = LaunchIdExpr.get();
16739 }
16740 }
16741
16742 return D;
16743}
16744
16745void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {
16746 if (!FD || FD->isInvalidDecl())
16747 return;
16748 if (auto *TD = dyn_cast<FunctionTemplateDecl>(Val: FD))
16749 FD = TD->getTemplatedDecl();
16750 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16751 FPOptionsOverride FPO;
16752 FPO.setDisallowOptimizations();
16753 CurFPFeatures.applyChanges(FPO);
16754 FpPragmaStack.CurrentValue =
16755 CurFPFeatures.getChangesFrom(Base: FPOptions(LangOpts));
16756 }
16757}
16758
16759void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
16760 ReturnStmt **Returns = Scope->Returns.data();
16761
16762 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16763 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16764 if (!NRVOCandidate->isNRVOVariable()) {
16765 Diag(Loc: Returns[I]->getRetValue()->getExprLoc(),
16766 DiagID: diag::warn_not_eliding_copy_on_return);
16767 Returns[I]->setNRVOCandidate(nullptr);
16768 }
16769 }
16770 }
16771}
16772
16773bool Sema::canDelayFunctionBody(const Declarator &D) {
16774 // We can't delay parsing the body of a constexpr function template (yet).
16775 if (D.getDeclSpec().hasConstexprSpecifier())
16776 return false;
16777
16778 // We can't delay parsing the body of a function template with a deduced
16779 // return type (yet).
16780 if (D.getDeclSpec().hasAutoTypeSpec()) {
16781 // If the placeholder introduces a non-deduced trailing return type,
16782 // we can still delay parsing it.
16783 if (D.getNumTypeObjects()) {
16784 const auto &Outer = D.getTypeObject(i: D.getNumTypeObjects() - 1);
16785 if (Outer.Kind == DeclaratorChunk::Function &&
16786 Outer.Fun.hasTrailingReturnType()) {
16787 QualType Ty = GetTypeFromParser(Ty: Outer.Fun.getTrailingReturnType());
16788 return Ty.isNull() || !Ty->isUndeducedType();
16789 }
16790 }
16791 return false;
16792 }
16793
16794 return true;
16795}
16796
16797bool Sema::canSkipFunctionBody(Decl *D) {
16798 // We cannot skip the body of a function (or function template) which is
16799 // constexpr, since we may need to evaluate its body in order to parse the
16800 // rest of the file.
16801 // We cannot skip the body of a function with an undeduced return type,
16802 // because any callers of that function need to know the type.
16803 if (const FunctionDecl *FD = D->getAsFunction()) {
16804 if (FD->isConstexpr())
16805 return false;
16806 // We can't simply call Type::isUndeducedType here, because inside template
16807 // auto can be deduced to a dependent type, which is not considered
16808 // "undeduced".
16809 if (FD->getReturnType()->getContainedDeducedType())
16810 return false;
16811 }
16812 return Consumer.shouldSkipFunctionBody(D);
16813}
16814
16815Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
16816 if (!Decl)
16817 return nullptr;
16818 if (FunctionDecl *FD = Decl->getAsFunction())
16819 FD->setHasSkippedBody();
16820 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: Decl))
16821 MD->setHasSkippedBody();
16822 return Decl;
16823}
16824
16825/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16826/// body.
16827class ExitFunctionBodyRAII {
16828public:
16829 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16830 ~ExitFunctionBodyRAII() {
16831 if (!IsLambda)
16832 S.PopExpressionEvaluationContext();
16833 }
16834
16835private:
16836 Sema &S;
16837 bool IsLambda = false;
16838};
16839
16840static void diagnoseImplicitlyRetainedSelf(Sema &S) {
16841 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16842
16843 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16844 auto [It, Inserted] = EscapeInfo.try_emplace(Key: BD);
16845 if (!Inserted)
16846 return It->second;
16847
16848 bool R = false;
16849 const BlockDecl *CurBD = BD;
16850
16851 do {
16852 R = !CurBD->doesNotEscape();
16853 if (R)
16854 break;
16855 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16856 } while (CurBD);
16857
16858 return It->second = R;
16859 };
16860
16861 // If the location where 'self' is implicitly retained is inside a escaping
16862 // block, emit a diagnostic.
16863 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16864 S.ImplicitlyRetainedSelfLocs)
16865 if (IsOrNestedInEscapingBlock(P.second))
16866 S.Diag(Loc: P.first, DiagID: diag::warn_implicitly_retains_self)
16867 << FixItHint::CreateInsertion(InsertionLoc: P.first, Code: "self->");
16868}
16869
16870static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16871 return isa<CXXMethodDecl>(Val: FD) && FD->param_empty() &&
16872 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16873}
16874
16875bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {
16876 return methodHasName(FD, Name: "get_return_object");
16877}
16878
16879bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {
16880 return FD->isStatic() &&
16881 methodHasName(FD, Name: "get_return_object_on_allocation_failure");
16882}
16883
16884void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
16885 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
16886 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16887 return;
16888 // Allow some_promise_type::get_return_object().
16889 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
16890 return;
16891 if (!FD->hasAttr<CoroWrapperAttr>())
16892 Diag(Loc: FD->getLocation(), DiagID: diag::err_coroutine_return_type) << RD;
16893}
16894
16895Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16896 bool RetainFunctionScopeInfo) {
16897 FunctionScopeInfo *FSI = getCurFunction();
16898 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16899
16900 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16901 FD->addAttr(A: StrictFPAttr::CreateImplicit(Ctx&: Context));
16902
16903 SourceLocation AnalysisLoc;
16904 if (Body)
16905 AnalysisLoc = Body->getEndLoc();
16906 else if (FD)
16907 AnalysisLoc = FD->getEndLoc();
16908 sema::AnalysisBasedWarnings::Policy WP =
16909 AnalysisWarnings.getPolicyInEffectAt(Loc: AnalysisLoc);
16910 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16911
16912 // If we skip function body, we can't tell if a function is a coroutine.
16913 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16914 if (FSI->isCoroutine())
16915 CheckCompletedCoroutineBody(FD, Body);
16916 else
16917 CheckCoroutineWrapper(FD);
16918 }
16919
16920 // Diagnose invalid SYCL kernel entry point function declarations
16921 // and build SYCLKernelCallStmts for valid ones.
16922 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16923 SYCLKernelEntryPointAttr *SKEPAttr =
16924 FD->getAttr<SYCLKernelEntryPointAttr>();
16925 if (FD->isDefaulted()) {
16926 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16927 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16928 SKEPAttr->setInvalidAttr();
16929 } else if (FD->isDeleted()) {
16930 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16931 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16932 SKEPAttr->setInvalidAttr();
16933 } else if (FSI->isCoroutine()) {
16934 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16935 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16936 SKEPAttr->setInvalidAttr();
16937 } else if (Body && isa<CXXTryStmt>(Val: Body)) {
16938 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16939 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16940 SKEPAttr->setInvalidAttr();
16941 }
16942
16943 // Build an unresolved SYCL kernel call statement for a function template,
16944 // validate that a SYCL kernel call statement was instantiated for an
16945 // (implicit or explicit) instantiation of a function template, or otherwise
16946 // build a (resolved) SYCL kernel call statement for a non-templated
16947 // function or an explicit specialization.
16948 if (Body && !SKEPAttr->isInvalidAttr()) {
16949 StmtResult SR;
16950 if (FD->isTemplateInstantiation()) {
16951 // The function body should already be a SYCLKernelCallStmt in this
16952 // case, but might not be if there were previous errors.
16953 SR = Body;
16954 } else if (!getCurFunction()->SYCLKernelLaunchIdExpr) {
16955 // If name lookup for a template named sycl_kernel_launch failed
16956 // earlier, don't try to build a SYCL kernel call statement as that
16957 // would cause additional errors to be issued; just proceed with the
16958 // original function body.
16959 SR = Body;
16960 } else if (FD->isTemplated()) {
16961 SR = SYCL().BuildUnresolvedSYCLKernelCallStmt(
16962 Body: cast<CompoundStmt>(Val: Body), LaunchIdExpr: getCurFunction()->SYCLKernelLaunchIdExpr);
16963 } else {
16964 SR = SYCL().BuildSYCLKernelCallStmt(
16965 FD, Body: cast<CompoundStmt>(Val: Body),
16966 LaunchIdExpr: getCurFunction()->SYCLKernelLaunchIdExpr);
16967 }
16968 // If construction of the replacement body fails, just continue with the
16969 // original function body. An early error return here is not valid; the
16970 // current declaration context and function scopes must be popped before
16971 // returning.
16972 if (SR.isUsable())
16973 Body = SR.get();
16974 }
16975 }
16976
16977 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16978 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16979 if (FD->isDeletedAsWritten())
16980 Diag(Loc: SEAttr->getLocation(),
16981 DiagID: diag::err_sycl_external_invalid_deleted_function)
16982 << SEAttr;
16983 }
16984
16985 {
16986 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16987 // one is already popped when finishing the lambda in BuildLambdaExpr().
16988 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16989 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(DC: FD));
16990 if (FD) {
16991 // The function body and the DefaultedOrDeletedInfo, if present, use
16992 // the same storage; don't overwrite the latter if the former is null
16993 // (the body is initialised to null anyway, so even if the latter isn't
16994 // present, this would still be a no-op).
16995 if (Body)
16996 FD->setBody(Body);
16997 FD->setWillHaveBody(false);
16998
16999 if (getLangOpts().CPlusPlus14) {
17000 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
17001 FD->getReturnType()->isUndeducedType()) {
17002 // For a function with a deduced result type to return void,
17003 // the result type as written must be 'auto' or 'decltype(auto)',
17004 // possibly cv-qualified or constrained, but not ref-qualified.
17005 if (!FD->getReturnType()->getAs<AutoType>()) {
17006 Diag(Loc: dcl->getLocation(), DiagID: diag::err_auto_fn_no_return_but_not_auto)
17007 << FD->getReturnType();
17008 FD->setInvalidDecl();
17009 } else {
17010 // Falling off the end of the function is the same as 'return;'.
17011 Expr *Dummy = nullptr;
17012 if (DeduceFunctionTypeFromReturnExpr(
17013 FD, ReturnLoc: dcl->getLocation(), RetExpr: Dummy,
17014 AT: FD->getReturnType()->getAs<AutoType>()))
17015 FD->setInvalidDecl();
17016 }
17017 }
17018 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(DC: FD)) {
17019 // In C++11, we don't use 'auto' deduction rules for lambda call
17020 // operators because we don't support return type deduction.
17021 auto *LSI = getCurLambda();
17022 if (LSI->HasImplicitReturnType) {
17023 deduceClosureReturnType(CSI&: *LSI);
17024
17025 // C++11 [expr.prim.lambda]p4:
17026 // [...] if there are no return statements in the compound-statement
17027 // [the deduced type is] the type void
17028 QualType RetType =
17029 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
17030
17031 // Update the return type to the deduced type.
17032 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
17033 FD->setType(Context.getFunctionType(ResultTy: RetType, Args: Proto->getParamTypes(),
17034 EPI: Proto->getExtProtoInfo()));
17035 }
17036 }
17037
17038 // If the function implicitly returns zero (like 'main') or is naked,
17039 // don't complain about missing return statements.
17040 // Clang implicitly returns 0 in C89 mode, but that's considered an
17041 // extension. The check is necessary to ensure the expected extension
17042 // warning is emitted in C89 mode.
17043 if ((FD->hasImplicitReturnZero() &&
17044 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
17045 FD->hasAttr<NakedAttr>())
17046 WP.disableCheckFallThrough();
17047
17048 // MSVC permits the use of pure specifier (=0) on function definition,
17049 // defined at class scope, warn about this non-standard construct.
17050 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
17051 !FD->isOutOfLine())
17052 Diag(Loc: FD->getLocation(), DiagID: diag::ext_pure_function_definition);
17053
17054 if (!FD->isInvalidDecl()) {
17055 // Don't diagnose unused parameters of defaulted, deleted or naked
17056 // functions.
17057 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
17058 !FD->hasAttr<NakedAttr>())
17059 DiagnoseUnusedParameters(Parameters: FD->parameters());
17060 DiagnoseSizeOfParametersAndReturnValue(Parameters: FD->parameters(),
17061 ReturnTy: FD->getReturnType(), D: FD);
17062
17063 // If this is a structor, we need a vtable.
17064 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: FD))
17065 MarkVTableUsed(Loc: FD->getLocation(), Class: Constructor->getParent());
17066 else if (CXXDestructorDecl *Destructor =
17067 dyn_cast<CXXDestructorDecl>(Val: FD))
17068 MarkVTableUsed(Loc: FD->getLocation(), Class: Destructor->getParent());
17069
17070 // Try to apply the named return value optimization. We have to check
17071 // if we can do this here because lambdas keep return statements around
17072 // to deduce an implicit return type.
17073 if (FD->getReturnType()->isRecordType() &&
17074 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
17075 computeNRVO(Body, Scope: FSI);
17076 }
17077
17078 // GNU warning -Wmissing-prototypes:
17079 // Warn if a global function is defined without a previous
17080 // prototype declaration. This warning is issued even if the
17081 // definition itself provides a prototype. The aim is to detect
17082 // global functions that fail to be declared in header files.
17083 const FunctionDecl *PossiblePrototype = nullptr;
17084 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
17085 Diag(Loc: FD->getLocation(), DiagID: diag::warn_missing_prototype) << FD;
17086
17087 if (PossiblePrototype) {
17088 // We found a declaration that is not a prototype,
17089 // but that could be a zero-parameter prototype
17090 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
17091 TypeLoc TL = TI->getTypeLoc();
17092 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
17093 Diag(Loc: PossiblePrototype->getLocation(),
17094 DiagID: diag::note_declaration_not_a_prototype)
17095 << (FD->getNumParams() != 0)
17096 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
17097 InsertionLoc: FTL.getRParenLoc(), Code: "void")
17098 : FixItHint{});
17099 }
17100 } else {
17101 // Returns true if the token beginning at this Loc is `const`.
17102 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
17103 const LangOptions &LangOpts) {
17104 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
17105 if (LocInfo.first.isInvalid())
17106 return false;
17107
17108 bool Invalid = false;
17109 StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid);
17110 if (Invalid)
17111 return false;
17112
17113 if (LocInfo.second > Buffer.size())
17114 return false;
17115
17116 const char *LexStart = Buffer.data() + LocInfo.second;
17117 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
17118
17119 return StartTok.consume_front(Prefix: "const") &&
17120 (StartTok.empty() || isWhitespace(c: StartTok[0]) ||
17121 StartTok.starts_with(Prefix: "/*") || StartTok.starts_with(Prefix: "//"));
17122 };
17123
17124 auto findBeginLoc = [&]() {
17125 // If the return type has `const` qualifier, we want to insert
17126 // `static` before `const` (and not before the typename).
17127 if ((FD->getReturnType()->isAnyPointerType() &&
17128 FD->getReturnType()->getPointeeType().isConstQualified()) ||
17129 FD->getReturnType().isConstQualified()) {
17130 // But only do this if we can determine where the `const` is.
17131
17132 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
17133 getLangOpts()))
17134
17135 return FD->getBeginLoc();
17136 }
17137 return FD->getTypeSpecStartLoc();
17138 };
17139 Diag(Loc: FD->getTypeSpecStartLoc(),
17140 DiagID: diag::note_static_for_internal_linkage)
17141 << /* function */ 1
17142 << (FD->getStorageClass() == SC_None
17143 ? FixItHint::CreateInsertion(InsertionLoc: findBeginLoc(), Code: "static ")
17144 : FixItHint{});
17145 }
17146 }
17147
17148 // We might not have found a prototype because we didn't wish to warn on
17149 // the lack of a missing prototype. Try again without the checks for
17150 // whether we want to warn on the missing prototype.
17151 if (!PossiblePrototype)
17152 (void)FindPossiblePrototype(FD, PossiblePrototype);
17153
17154 // If the function being defined does not have a prototype, then we may
17155 // need to diagnose it as changing behavior in C23 because we now know
17156 // whether the function accepts arguments or not. This only handles the
17157 // case where the definition has no prototype but does have parameters
17158 // and either there is no previous potential prototype, or the previous
17159 // potential prototype also has no actual prototype. This handles cases
17160 // like:
17161 // void f(); void f(a) int a; {}
17162 // void g(a) int a; {}
17163 // See MergeFunctionDecl() for other cases of the behavior change
17164 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
17165 // type without a prototype.
17166 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
17167 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
17168 !PossiblePrototype->isImplicit()))) {
17169 // The function definition has parameters, so this will change behavior
17170 // in C23. If there is a possible prototype, it comes before the
17171 // function definition.
17172 // FIXME: The declaration may have already been diagnosed as being
17173 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
17174 // there's no way to test for the "changes behavior" condition in
17175 // SemaType.cpp when forming the declaration's function type. So, we do
17176 // this awkward dance instead.
17177 //
17178 // If we have a possible prototype and it declares a function with a
17179 // prototype, we don't want to diagnose it; if we have a possible
17180 // prototype and it has no prototype, it may have already been
17181 // diagnosed in SemaType.cpp as deprecated depending on whether
17182 // -Wstrict-prototypes is enabled. If we already warned about it being
17183 // deprecated, add a note that it also changes behavior. If we didn't
17184 // warn about it being deprecated (because the diagnostic is not
17185 // enabled), warn now that it is deprecated and changes behavior.
17186
17187 // This K&R C function definition definitely changes behavior in C23,
17188 // so diagnose it.
17189 Diag(Loc: FD->getLocation(), DiagID: diag::warn_non_prototype_changes_behavior)
17190 << /*definition*/ 1 << /* not supported in C23 */ 0;
17191
17192 // If we have a possible prototype for the function which is a user-
17193 // visible declaration, we already tested that it has no prototype.
17194 // This will change behavior in C23. This gets a warning rather than a
17195 // note because it's the same behavior-changing problem as with the
17196 // definition.
17197 if (PossiblePrototype)
17198 Diag(Loc: PossiblePrototype->getLocation(),
17199 DiagID: diag::warn_non_prototype_changes_behavior)
17200 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
17201 << /*definition*/ 1;
17202 }
17203
17204 // Warn on CPUDispatch with an actual body.
17205 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
17206 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Val: Body))
17207 if (!CmpndBody->body_empty())
17208 Diag(Loc: CmpndBody->body_front()->getBeginLoc(),
17209 DiagID: diag::warn_dispatch_body_ignored);
17210
17211 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
17212 const CXXMethodDecl *KeyFunction;
17213 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
17214 MD->isVirtual() &&
17215 (KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent())) &&
17216 MD == KeyFunction->getCanonicalDecl()) {
17217 // Update the key-function state if necessary for this ABI.
17218 if (FD->isInlined() &&
17219 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
17220 Context.setNonKeyFunction(MD);
17221
17222 // If the newly-chosen key function is already defined, then we
17223 // need to mark the vtable as used retroactively.
17224 KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent());
17225 const FunctionDecl *Definition;
17226 if (KeyFunction && KeyFunction->isDefined(Definition))
17227 MarkVTableUsed(Loc: Definition->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
17228 } else {
17229 // We just defined they key function; mark the vtable as used.
17230 MarkVTableUsed(Loc: FD->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
17231 }
17232 }
17233 }
17234
17235 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
17236 "Function parsing confused");
17237 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Val: dcl)) {
17238 assert(MD == getCurMethodDecl() && "Method parsing confused");
17239 MD->setBody(Body);
17240 if (!MD->isInvalidDecl()) {
17241 DiagnoseSizeOfParametersAndReturnValue(Parameters: MD->parameters(),
17242 ReturnTy: MD->getReturnType(), D: MD);
17243
17244 if (Body)
17245 computeNRVO(Body, Scope: FSI);
17246 }
17247 if (FSI->ObjCShouldCallSuper) {
17248 Diag(Loc: MD->getEndLoc(), DiagID: diag::warn_objc_missing_super_call)
17249 << MD->getSelector().getAsString();
17250 FSI->ObjCShouldCallSuper = false;
17251 }
17252 if (FSI->ObjCWarnForNoDesignatedInitChain) {
17253 const ObjCMethodDecl *InitMethod = nullptr;
17254 bool isDesignated =
17255 MD->isDesignatedInitializerForTheInterface(InitMethod: &InitMethod);
17256 assert(isDesignated && InitMethod);
17257 (void)isDesignated;
17258
17259 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
17260 auto IFace = MD->getClassInterface();
17261 if (!IFace)
17262 return false;
17263 auto SuperD = IFace->getSuperClass();
17264 if (!SuperD)
17265 return false;
17266 return SuperD->getIdentifier() ==
17267 ObjC().NSAPIObj->getNSClassId(K: NSAPI::ClassId_NSObject);
17268 };
17269 // Don't issue this warning for unavailable inits or direct subclasses
17270 // of NSObject.
17271 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
17272 Diag(Loc: MD->getLocation(),
17273 DiagID: diag::warn_objc_designated_init_missing_super_call);
17274 Diag(Loc: InitMethod->getLocation(),
17275 DiagID: diag::note_objc_designated_init_marked_here);
17276 }
17277 FSI->ObjCWarnForNoDesignatedInitChain = false;
17278 }
17279 if (FSI->ObjCWarnForNoInitDelegation) {
17280 // Don't issue this warning for unavailable inits.
17281 if (!MD->isUnavailable())
17282 Diag(Loc: MD->getLocation(),
17283 DiagID: diag::warn_objc_secondary_init_missing_init_call);
17284 FSI->ObjCWarnForNoInitDelegation = false;
17285 }
17286
17287 diagnoseImplicitlyRetainedSelf(S&: *this);
17288 } else {
17289 // Parsing the function declaration failed in some way. Pop the fake scope
17290 // we pushed on.
17291 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
17292 return nullptr;
17293 }
17294
17295 if (Body) {
17296 if (FSI->HasPotentialAvailabilityViolations)
17297 DiagnoseUnguardedAvailabilityViolations(FD: dcl);
17298 else if (AMDGPU().HasPotentiallyUnguardedBuiltinUsage(FD))
17299 AMDGPU().DiagnoseUnguardedBuiltinUsage(FD);
17300 }
17301
17302 assert(!FSI->ObjCShouldCallSuper &&
17303 "This should only be set for ObjC methods, which should have been "
17304 "handled in the block above.");
17305
17306 // Verify and clean out per-function state.
17307 if (Body && (!FD || !FD->isDefaulted())) {
17308 // C++ constructors that have function-try-blocks can't have return
17309 // statements in the handlers of that block. (C++ [except.handle]p14)
17310 // Verify this.
17311 if (FD && isa<CXXConstructorDecl>(Val: FD) && isa<CXXTryStmt>(Val: Body))
17312 DiagnoseReturnInConstructorExceptionHandler(TryBlock: cast<CXXTryStmt>(Val: Body));
17313
17314 // Verify that gotos and switch cases don't jump into scopes illegally.
17315 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
17316 DiagnoseInvalidJumps(Body);
17317
17318 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: dcl)) {
17319 if (!Destructor->getParent()->isDependentType())
17320 CheckDestructor(Destructor);
17321
17322 MarkBaseAndMemberDestructorsReferenced(Loc: Destructor->getLocation(),
17323 Record: Destructor->getParent());
17324 }
17325
17326 // If any errors have occurred, clear out any temporaries that may have
17327 // been leftover. This ensures that these temporaries won't be picked up
17328 // for deletion in some later function.
17329 if (hasUncompilableErrorOccurred() ||
17330 hasAnyUnrecoverableErrorsInThisFunction() ||
17331 getDiagnostics().getSuppressAllDiagnostics()) {
17332 DiscardCleanupsInEvaluationContext();
17333 }
17334 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(Val: dcl)) {
17335 // Since the body is valid, issue any analysis-based warnings that are
17336 // enabled.
17337 ActivePolicy = &WP;
17338 }
17339
17340 if (!IsInstantiation && FD &&
17341 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
17342 !FD->isInvalidDecl() &&
17343 !CheckConstexprFunctionDefinition(FD, Kind: CheckConstexprKind::Diagnose))
17344 FD->setInvalidDecl();
17345
17346 if (FD && FD->hasAttr<NakedAttr>()) {
17347 for (const Stmt *S : Body->children()) {
17348 // Allow local register variables without initializer as they don't
17349 // require prologue.
17350 bool RegisterVariables = false;
17351 if (auto *DS = dyn_cast<DeclStmt>(Val: S)) {
17352 for (const auto *Decl : DS->decls()) {
17353 if (const auto *Var = dyn_cast<VarDecl>(Val: Decl)) {
17354 RegisterVariables =
17355 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
17356 if (!RegisterVariables)
17357 break;
17358 }
17359 }
17360 }
17361 if (RegisterVariables)
17362 continue;
17363 if (!isa<AsmStmt>(Val: S) && !isa<NullStmt>(Val: S)) {
17364 Diag(Loc: S->getBeginLoc(), DiagID: diag::err_non_asm_stmt_in_naked_function);
17365 Diag(Loc: FD->getAttr<NakedAttr>()->getLocation(), DiagID: diag::note_attribute);
17366 FD->setInvalidDecl();
17367 break;
17368 }
17369 }
17370 }
17371
17372 assert(ExprCleanupObjects.size() ==
17373 ExprEvalContexts.back().NumCleanupObjects &&
17374 "Leftover temporaries in function");
17375 assert(!Cleanup.exprNeedsCleanups() &&
17376 "Unaccounted cleanups in function");
17377 assert(MaybeODRUseExprs.empty() &&
17378 "Leftover expressions for odr-use checking");
17379 }
17380 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
17381 // the declaration context below. Otherwise, we're unable to transform
17382 // 'this' expressions when transforming immediate context functions.
17383
17384 if (FD)
17385 CheckImmediateEscalatingFunctionDefinition(FD, FSI: getCurFunction());
17386
17387 if (!IsInstantiation)
17388 PopDeclContext();
17389
17390 if (!RetainFunctionScopeInfo)
17391 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
17392 // If any errors have occurred, clear out any temporaries that may have
17393 // been leftover. This ensures that these temporaries won't be picked up for
17394 // deletion in some later function.
17395 if (hasUncompilableErrorOccurred()) {
17396 DiscardCleanupsInEvaluationContext();
17397 }
17398
17399 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
17400 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
17401 auto ES = getEmissionStatus(Decl: FD);
17402 if (ES == Sema::FunctionEmissionStatus::Emitted ||
17403 ES == Sema::FunctionEmissionStatus::Unknown)
17404 DeclsToCheckForDeferredDiags.insert(X: FD);
17405 }
17406
17407 if (FD && !FD->isDeleted())
17408 checkTypeSupport(Ty: FD->getType(), Loc: FD->getLocation(), D: FD);
17409
17410 return dcl;
17411}
17412
17413/// When we finish delayed parsing of an attribute, we must attach it to the
17414/// relevant Decl.
17415void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
17416 ParsedAttributes &Attrs) {
17417 // Always attach attributes to the underlying decl.
17418 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D))
17419 D = TD->getTemplatedDecl();
17420 ProcessDeclAttributeList(S, D, AttrList: Attrs);
17421 ProcessAPINotes(D);
17422
17423 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: D))
17424 if (Method->isStatic())
17425 checkThisInStaticMemberFunctionAttributes(Method);
17426}
17427
17428NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
17429 IdentifierInfo &II, Scope *S) {
17430 // It is not valid to implicitly define a function in C23.
17431 assert(LangOpts.implicitFunctionsAllowed() &&
17432 "Implicit function declarations aren't allowed in this language mode");
17433
17434 // Find the scope in which the identifier is injected and the corresponding
17435 // DeclContext.
17436 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17437 // In that case, we inject the declaration into the translation unit scope
17438 // instead.
17439 Scope *BlockScope = S;
17440 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17441 BlockScope = BlockScope->getParent();
17442
17443 // Loop until we find a DeclContext that is either a function/method or the
17444 // translation unit, which are the only two valid places to implicitly define
17445 // a function. This avoids accidentally defining the function within a tag
17446 // declaration, for example.
17447 Scope *ContextScope = BlockScope;
17448 while (!ContextScope->getEntity() ||
17449 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17450 !ContextScope->getEntity()->isTranslationUnit()))
17451 ContextScope = ContextScope->getParent();
17452 ContextRAII SavedContext(*this, ContextScope->getEntity());
17453
17454 // Before we produce a declaration for an implicitly defined
17455 // function, see whether there was a locally-scoped declaration of
17456 // this name as a function or variable. If so, use that
17457 // (non-visible) declaration, and complain about it.
17458 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(Name: &II);
17459 if (ExternCPrev) {
17460 // We still need to inject the function into the enclosing block scope so
17461 // that later (non-call) uses can see it.
17462 PushOnScopeChains(D: ExternCPrev, S: BlockScope, /*AddToContext*/false);
17463
17464 // C89 footnote 38:
17465 // If in fact it is not defined as having type "function returning int",
17466 // the behavior is undefined.
17467 if (!isa<FunctionDecl>(Val: ExternCPrev) ||
17468 !Context.typesAreCompatible(
17469 T1: cast<FunctionDecl>(Val: ExternCPrev)->getType(),
17470 T2: Context.getFunctionNoProtoType(ResultTy: Context.IntTy))) {
17471 Diag(Loc, DiagID: diag::ext_use_out_of_scope_declaration)
17472 << ExternCPrev << !getLangOpts().C99;
17473 Diag(Loc: ExternCPrev->getLocation(), DiagID: diag::note_previous_declaration);
17474 return ExternCPrev;
17475 }
17476 }
17477
17478 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17479 unsigned diag_id;
17480 if (II.getName().starts_with(Prefix: "__builtin_"))
17481 diag_id = diag::warn_builtin_unknown;
17482 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17483 else if (getLangOpts().C99)
17484 diag_id = diag::ext_implicit_function_decl_c99;
17485 else
17486 diag_id = diag::warn_implicit_function_decl;
17487
17488 TypoCorrection Corrected;
17489 // Because typo correction is expensive, only do it if the implicit
17490 // function declaration is going to be treated as an error.
17491 //
17492 // Perform the correction before issuing the main diagnostic, as some
17493 // consumers use typo-correction callbacks to enhance the main diagnostic.
17494 if (S && !ExternCPrev &&
17495 (Diags.getDiagnosticLevel(DiagID: diag_id, Loc) >= DiagnosticsEngine::Error)) {
17496 DeclFilterCCC<FunctionDecl> CCC{};
17497 Corrected = CorrectTypo(Typo: DeclarationNameInfo(&II, Loc), LookupKind: LookupOrdinaryName,
17498 S, SS: nullptr, CCC, Mode: CorrectTypoKind::NonError);
17499 }
17500
17501 Diag(Loc, DiagID: diag_id) << &II;
17502 if (Corrected) {
17503 // If the correction is going to suggest an implicitly defined function,
17504 // skip the correction as not being a particularly good idea.
17505 bool Diagnose = true;
17506 if (const auto *D = Corrected.getCorrectionDecl())
17507 Diagnose = !D->isImplicit();
17508 if (Diagnose)
17509 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::note_function_suggestion),
17510 /*ErrorRecovery*/ false);
17511 }
17512
17513 // If we found a prior declaration of this function, don't bother building
17514 // another one. We've already pushed that one into scope, so there's nothing
17515 // more to do.
17516 if (ExternCPrev)
17517 return ExternCPrev;
17518
17519 // Set a Declarator for the implicit definition: int foo();
17520 const char *Dummy;
17521 AttributeFactory attrFactory;
17522 DeclSpec DS(attrFactory);
17523 unsigned DiagID;
17524 bool Error = DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc, PrevSpec&: Dummy, DiagID,
17525 Policy: Context.getPrintingPolicy());
17526 (void)Error; // Silence warning.
17527 assert(!Error && "Error setting up implicit decl!");
17528 SourceLocation NoLoc;
17529 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
17530 D.AddTypeInfo(TI: DeclaratorChunk::getFunction(/*HasProto=*/false,
17531 /*IsAmbiguous=*/false,
17532 /*LParenLoc=*/NoLoc,
17533 /*Params=*/nullptr,
17534 /*NumParams=*/0,
17535 /*EllipsisLoc=*/NoLoc,
17536 /*RParenLoc=*/NoLoc,
17537 /*RefQualifierIsLvalueRef=*/true,
17538 /*RefQualifierLoc=*/NoLoc,
17539 /*MutableLoc=*/NoLoc, ESpecType: EST_None,
17540 /*ESpecRange=*/SourceRange(),
17541 /*Exceptions=*/nullptr,
17542 /*ExceptionRanges=*/nullptr,
17543 /*NumExceptions=*/0,
17544 /*NoexceptExpr=*/nullptr,
17545 /*ExceptionSpecTokens=*/nullptr,
17546 /*DeclsInPrototype=*/{}, LocalRangeBegin: Loc, LocalRangeEnd: Loc,
17547 TheDeclarator&: D),
17548 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
17549 D.SetIdentifier(Id: &II, IdLoc: Loc);
17550
17551 // Insert this function into the enclosing block scope.
17552 FunctionDecl *FD = cast<FunctionDecl>(Val: ActOnDeclarator(S: BlockScope, D));
17553 FD->setImplicit();
17554
17555 AddKnownFunctionAttributes(FD);
17556
17557 return FD;
17558}
17559
17560void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
17561 FunctionDecl *FD) {
17562 if (FD->isInvalidDecl())
17563 return;
17564
17565 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17566 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17567 return;
17568
17569 UnsignedOrNone AlignmentParam = std::nullopt;
17570 bool IsNothrow = false;
17571 if (!FD->isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam, IsNothrow: &IsNothrow))
17572 return;
17573
17574 // C++2a [basic.stc.dynamic.allocation]p4:
17575 // An allocation function that has a non-throwing exception specification
17576 // indicates failure by returning a null pointer value. Any other allocation
17577 // function never returns a null pointer value and indicates failure only by
17578 // throwing an exception [...]
17579 //
17580 // However, -fcheck-new invalidates this possible assumption, so don't add
17581 // NonNull when that is enabled.
17582 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17583 !getLangOpts().CheckNew)
17584 FD->addAttr(A: ReturnsNonNullAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17585
17586 // C++2a [basic.stc.dynamic.allocation]p2:
17587 // An allocation function attempts to allocate the requested amount of
17588 // storage. [...] If the request succeeds, the value returned by a
17589 // replaceable allocation function is a [...] pointer value p0 different
17590 // from any previously returned value p1 [...]
17591 //
17592 // However, this particular information is being added in codegen,
17593 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17594
17595 // C++2a [basic.stc.dynamic.allocation]p2:
17596 // An allocation function attempts to allocate the requested amount of
17597 // storage. If it is successful, it returns the address of the start of a
17598 // block of storage whose length in bytes is at least as large as the
17599 // requested size.
17600 if (!FD->hasAttr<AllocSizeAttr>()) {
17601 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17602 Ctx&: Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17603 /*NumElemsParam=*/ParamIdx(), Range: FD->getLocation()));
17604 }
17605
17606 // C++2a [basic.stc.dynamic.allocation]p3:
17607 // For an allocation function [...], the pointer returned on a successful
17608 // call shall represent the address of storage that is aligned as follows:
17609 // (3.1) If the allocation function takes an argument of type
17610 // std​::​align_­val_­t, the storage will have the alignment
17611 // specified by the value of this argument.
17612 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17613 FD->addAttr(A: AllocAlignAttr::CreateImplicit(
17614 Ctx&: Context, ParamIndex: ParamIdx(*AlignmentParam, FD), Range: FD->getLocation()));
17615 }
17616
17617 // FIXME:
17618 // C++2a [basic.stc.dynamic.allocation]p3:
17619 // For an allocation function [...], the pointer returned on a successful
17620 // call shall represent the address of storage that is aligned as follows:
17621 // (3.2) Otherwise, if the allocation function is named operator new[],
17622 // the storage is aligned for any object that does not have
17623 // new-extended alignment ([basic.align]) and is no larger than the
17624 // requested size.
17625 // (3.3) Otherwise, the storage is aligned for any object that does not
17626 // have new-extended alignment and is of the requested size.
17627}
17628
17629void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
17630 if (FD->isInvalidDecl())
17631 return;
17632
17633 // If this is a built-in function, map its builtin attributes to
17634 // actual attributes.
17635 if (unsigned BuiltinID = FD->getBuiltinID()) {
17636 // Handle printf-formatting attributes.
17637 unsigned FormatIdx;
17638 bool HasVAListArg;
17639 if (Context.BuiltinInfo.isPrintfLike(ID: BuiltinID, FormatIdx, HasVAListArg)) {
17640 if (!FD->hasAttr<FormatAttr>()) {
17641 const char *fmt = "printf";
17642 unsigned int NumParams = FD->getNumParams();
17643 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17644 FD->getParamDecl(i: FormatIdx)->getType()->isObjCObjectPointerType())
17645 fmt = "NSString";
17646 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17647 Type: &Context.Idents.get(Name: fmt),
17648 FormatIdx: FormatIdx+1,
17649 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17650 Range: FD->getLocation()));
17651 }
17652 }
17653 if (Context.BuiltinInfo.isScanfLike(ID: BuiltinID, FormatIdx,
17654 HasVAListArg)) {
17655 if (!FD->hasAttr<FormatAttr>())
17656 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17657 Type: &Context.Idents.get(Name: "scanf"),
17658 FormatIdx: FormatIdx+1,
17659 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17660 Range: FD->getLocation()));
17661 }
17662
17663 // Handle automatically recognized callbacks.
17664 SmallVector<int, 4> Encoding;
17665 if (!FD->hasAttr<CallbackAttr>() &&
17666 Context.BuiltinInfo.performsCallback(ID: BuiltinID, Encoding))
17667 FD->addAttr(A: CallbackAttr::CreateImplicit(
17668 Ctx&: Context, Encoding: Encoding.data(), EncodingSize: Encoding.size(), Range: FD->getLocation()));
17669
17670 // Mark const if we don't care about errno and/or floating point exceptions
17671 // that are the only thing preventing the function from being const. This
17672 // allows IRgen to use LLVM intrinsics for such functions.
17673 bool NoExceptions =
17674 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
17675 bool ConstWithoutErrnoAndExceptions =
17676 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(ID: BuiltinID);
17677 bool ConstWithoutExceptions =
17678 Context.BuiltinInfo.isConstWithoutExceptions(ID: BuiltinID);
17679 if (!FD->hasAttr<ConstAttr>() &&
17680 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17681 (!ConstWithoutErrnoAndExceptions ||
17682 (!getLangOpts().MathErrno && NoExceptions)) &&
17683 (!ConstWithoutExceptions || NoExceptions))
17684 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17685
17686 // We make "fma" on GNU or Windows const because we know it does not set
17687 // errno in those environments even though it could set errno based on the
17688 // C standard.
17689 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17690 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17691 !FD->hasAttr<ConstAttr>()) {
17692 switch (BuiltinID) {
17693 case Builtin::BI__builtin_fma:
17694 case Builtin::BI__builtin_fmaf:
17695 case Builtin::BI__builtin_fmal:
17696 case Builtin::BIfma:
17697 case Builtin::BIfmaf:
17698 case Builtin::BIfmal:
17699 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17700 break;
17701 default:
17702 break;
17703 }
17704 }
17705
17706 SmallVector<int, 4> Indxs;
17707 Builtin::Info::NonNullMode OptMode;
17708 if (Context.BuiltinInfo.isNonNull(ID: BuiltinID, Indxs, Mode&: OptMode) &&
17709 !FD->hasAttr<NonNullAttr>()) {
17710 if (OptMode == Builtin::Info::NonNullMode::NonOptimizing) {
17711 for (int I : Indxs) {
17712 ParmVarDecl *PVD = FD->getParamDecl(i: I);
17713 QualType T = PVD->getType();
17714 T = Context.getAttributedType(attrKind: attr::TypeNonNull, modifiedType: T, equivalentType: T);
17715 PVD->setType(T);
17716 }
17717 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17718 llvm::SmallVector<ParamIdx, 4> ParamIndxs;
17719 for (int I : Indxs)
17720 ParamIndxs.push_back(Elt: ParamIdx(I + 1, FD));
17721 FD->addAttr(A: NonNullAttr::CreateImplicit(Ctx&: Context, Args: ParamIndxs.data(),
17722 ArgsSize: ParamIndxs.size()));
17723 }
17724 }
17725 if (Context.BuiltinInfo.isReturnsTwice(ID: BuiltinID) &&
17726 !FD->hasAttr<ReturnsTwiceAttr>())
17727 FD->addAttr(A: ReturnsTwiceAttr::CreateImplicit(Ctx&: Context,
17728 Range: FD->getLocation()));
17729 if (Context.BuiltinInfo.isNoThrow(ID: BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17730 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17731 if (Context.BuiltinInfo.isPure(ID: BuiltinID) && !FD->hasAttr<PureAttr>())
17732 FD->addAttr(A: PureAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17733 if (Context.BuiltinInfo.isConst(ID: BuiltinID) && !FD->hasAttr<ConstAttr>())
17734 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17735 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID) &&
17736 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17737 // Add the appropriate attribute, depending on the CUDA compilation mode
17738 // and which target the builtin belongs to. For example, during host
17739 // compilation, aux builtins are __device__, while the rest are __host__.
17740 if (getLangOpts().CUDAIsDevice !=
17741 Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID))
17742 FD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17743 else
17744 FD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17745 }
17746
17747 // Add known guaranteed alignment for allocation functions.
17748 switch (BuiltinID) {
17749 case Builtin::BImemalign:
17750 case Builtin::BIaligned_alloc:
17751 if (!FD->hasAttr<AllocAlignAttr>())
17752 FD->addAttr(A: AllocAlignAttr::CreateImplicit(Ctx&: Context, ParamIndex: ParamIdx(1, FD),
17753 Range: FD->getLocation()));
17754 break;
17755 default:
17756 break;
17757 }
17758
17759 // Add allocsize attribute for allocation functions.
17760 switch (BuiltinID) {
17761 case Builtin::BIcalloc:
17762 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17763 Ctx&: Context, ElemSizeParam: ParamIdx(1, FD), NumElemsParam: ParamIdx(2, FD), Range: FD->getLocation()));
17764 break;
17765 case Builtin::BImemalign:
17766 case Builtin::BIaligned_alloc:
17767 case Builtin::BIrealloc:
17768 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(2, FD),
17769 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17770 break;
17771 case Builtin::BImalloc:
17772 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(1, FD),
17773 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17774 break;
17775 default:
17776 break;
17777 }
17778 }
17779
17780 LazyProcessLifetimeCaptureByParams(FD);
17781 inferLifetimeBoundAttribute(FD);
17782 inferLifetimeCaptureByAttribute(FD);
17783 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
17784
17785 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17786 // throw, add an implicit nothrow attribute to any extern "C" function we come
17787 // across.
17788 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17789 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17790 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17791 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17792 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17793 }
17794
17795 IdentifierInfo *Name = FD->getIdentifier();
17796 if (!Name)
17797 return;
17798 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
17799 (isa<LinkageSpecDecl>(Val: FD->getDeclContext()) &&
17800 cast<LinkageSpecDecl>(Val: FD->getDeclContext())->getLanguage() ==
17801 LinkageSpecLanguageIDs::C)) {
17802 // Okay: this could be a libc/libm/Objective-C function we know
17803 // about.
17804 } else
17805 return;
17806
17807 if (Name->isStr(Str: "asprintf") || Name->isStr(Str: "vasprintf")) {
17808 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17809 // target-specific builtins, perhaps?
17810 if (!FD->hasAttr<FormatAttr>())
17811 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17812 Type: &Context.Idents.get(Name: "printf"), FormatIdx: 2,
17813 FirstArg: Name->isStr(Str: "vasprintf") ? 0 : 3,
17814 Range: FD->getLocation()));
17815 }
17816
17817 if (Name->isStr(Str: "__CFStringMakeConstantString")) {
17818 // We already have a __builtin___CFStringMakeConstantString,
17819 // but builds that use -fno-constant-cfstrings don't go through that.
17820 if (!FD->hasAttr<FormatArgAttr>())
17821 FD->addAttr(A: FormatArgAttr::CreateImplicit(Ctx&: Context, FormatIdx: ParamIdx(1, FD),
17822 Range: FD->getLocation()));
17823 }
17824}
17825
17826TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
17827 TypeSourceInfo *TInfo) {
17828 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17829 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17830
17831 if (!TInfo) {
17832 assert(D.isInvalidType() && "no declarator info for valid type");
17833 TInfo = Context.getTrivialTypeSourceInfo(T);
17834 }
17835
17836 // Scope manipulation handled by caller.
17837 TypedefDecl *NewTD =
17838 TypedefDecl::Create(C&: Context, DC: CurContext, StartLoc: D.getBeginLoc(),
17839 IdLoc: D.getIdentifierLoc(), Id: D.getIdentifier(), TInfo);
17840
17841 // Bail out immediately if we have an invalid declaration.
17842 if (D.isInvalidType()) {
17843 NewTD->setInvalidDecl();
17844 return NewTD;
17845 }
17846
17847 if (D.getDeclSpec().isModulePrivateSpecified()) {
17848 if (CurContext->isFunctionOrMethod())
17849 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_module_private_local)
17850 << 2 << NewTD
17851 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
17852 << FixItHint::CreateRemoval(
17853 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
17854 else
17855 NewTD->setModulePrivate();
17856 }
17857
17858 // C++ [dcl.typedef]p8:
17859 // If the typedef declaration defines an unnamed class (or
17860 // enum), the first typedef-name declared by the declaration
17861 // to be that class type (or enum type) is used to denote the
17862 // class type (or enum type) for linkage purposes only.
17863 // We need to check whether the type was declared in the declaration.
17864 switch (D.getDeclSpec().getTypeSpecType()) {
17865 case TST_enum:
17866 case TST_struct:
17867 case TST_interface:
17868 case TST_union:
17869 case TST_class: {
17870 TagDecl *tagFromDeclSpec = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
17871 setTagNameForLinkagePurposes(TagFromDeclSpec: tagFromDeclSpec, NewTD);
17872 break;
17873 }
17874
17875 default:
17876 break;
17877 }
17878
17879 return NewTD;
17880}
17881
17882bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
17883 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17884 QualType T = TI->getType();
17885
17886 if (T->isDependentType())
17887 return false;
17888
17889 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17890 // integral type; any cv-qualification is ignored.
17891 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17892 // non-atomic version of the type specified by the type specifiers in the
17893 // specifier qualifier list.
17894 // Because of how odd C's rule is, we'll let the user know that operations
17895 // involving the enumeration type will be non-atomic.
17896 if (T->isAtomicType())
17897 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_atomic_stripped_in_enum);
17898
17899 Qualifiers Q = T.getQualifiers();
17900 std::optional<unsigned> QualSelect;
17901 if (Q.hasConst() && Q.hasVolatile())
17902 QualSelect = diag::CVQualList::Both;
17903 else if (Q.hasConst())
17904 QualSelect = diag::CVQualList::Const;
17905 else if (Q.hasVolatile())
17906 QualSelect = diag::CVQualList::Volatile;
17907
17908 if (QualSelect)
17909 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_cv_stripped_in_enum) << *QualSelect;
17910
17911 T = T.getAtomicUnqualifiedType();
17912
17913 // This doesn't use 'isIntegralType' despite the error message mentioning
17914 // integral type because isIntegralType would also allow enum types in C.
17915 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17916 if (BT->isInteger())
17917 return false;
17918
17919 return Diag(Loc: UnderlyingLoc, DiagID: diag::err_enum_invalid_underlying)
17920 << T << T->isBitIntType();
17921}
17922
17923bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
17924 QualType EnumUnderlyingTy, bool IsFixed,
17925 const EnumDecl *Prev) {
17926 if (IsScoped != Prev->isScoped()) {
17927 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_scoped_mismatch)
17928 << Prev->isScoped();
17929 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17930 return true;
17931 }
17932
17933 if (IsFixed && Prev->isFixed()) {
17934 if (!EnumUnderlyingTy->isDependentType() &&
17935 !Prev->getIntegerType()->isDependentType() &&
17936 !Context.hasSameUnqualifiedType(T1: EnumUnderlyingTy,
17937 T2: Prev->getIntegerType())) {
17938 // TODO: Highlight the underlying type of the redeclaration.
17939 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_type_mismatch)
17940 << EnumUnderlyingTy << Prev->getIntegerType();
17941 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration)
17942 << Prev->getIntegerTypeRange();
17943 return true;
17944 }
17945 } else if (IsFixed != Prev->isFixed()) {
17946 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_fixed_mismatch)
17947 << Prev->isFixed();
17948 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17949 return true;
17950 }
17951
17952 return false;
17953}
17954
17955/// Get diagnostic %select index for tag kind for
17956/// redeclaration diagnostic message.
17957/// WARNING: Indexes apply to particular diagnostics only!
17958///
17959/// \returns diagnostic %select index.
17960static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
17961 switch (Tag) {
17962 case TagTypeKind::Struct:
17963 return 0;
17964 case TagTypeKind::Interface:
17965 return 1;
17966 case TagTypeKind::Class:
17967 return 2;
17968 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17969 }
17970}
17971
17972/// Determine if tag kind is a class-key compatible with
17973/// class for redeclaration (class, struct, or __interface).
17974///
17975/// \returns true iff the tag kind is compatible.
17976static bool isClassCompatTagKind(TagTypeKind Tag)
17977{
17978 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17979 Tag == TagTypeKind::Interface;
17980}
17981
17982NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, TagTypeKind TTK) {
17983 if (isa<TypedefDecl>(Val: PrevDecl))
17984 return NonTagKind::Typedef;
17985 else if (isa<TypeAliasDecl>(Val: PrevDecl))
17986 return NonTagKind::TypeAlias;
17987 else if (isa<ClassTemplateDecl>(Val: PrevDecl))
17988 return NonTagKind::Template;
17989 else if (isa<TypeAliasTemplateDecl>(Val: PrevDecl))
17990 return NonTagKind::TypeAliasTemplate;
17991 else if (isa<TemplateTemplateParmDecl>(Val: PrevDecl))
17992 return NonTagKind::TemplateTemplateArgument;
17993 switch (TTK) {
17994 case TagTypeKind::Struct:
17995 case TagTypeKind::Interface:
17996 case TagTypeKind::Class:
17997 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17998 : NonTagKind::NonStruct;
17999 case TagTypeKind::Union:
18000 return NonTagKind::NonUnion;
18001 case TagTypeKind::Enum:
18002 return NonTagKind::NonEnum;
18003 }
18004 llvm_unreachable("invalid TTK");
18005}
18006
18007bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
18008 TagTypeKind NewTag, bool isDefinition,
18009 SourceLocation NewTagLoc,
18010 const IdentifierInfo *Name) {
18011 // C++ [dcl.type.elab]p3:
18012 // The class-key or enum keyword present in the
18013 // elaborated-type-specifier shall agree in kind with the
18014 // declaration to which the name in the elaborated-type-specifier
18015 // refers. This rule also applies to the form of
18016 // elaborated-type-specifier that declares a class-name or
18017 // friend class since it can be construed as referring to the
18018 // definition of the class. Thus, in any
18019 // elaborated-type-specifier, the enum keyword shall be used to
18020 // refer to an enumeration (7.2), the union class-key shall be
18021 // used to refer to a union (clause 9), and either the class or
18022 // struct class-key shall be used to refer to a class (clause 9)
18023 // declared using the class or struct class-key.
18024 TagTypeKind OldTag = Previous->getTagKind();
18025 if (OldTag != NewTag &&
18026 !(isClassCompatTagKind(Tag: OldTag) && isClassCompatTagKind(Tag: NewTag)))
18027 return false;
18028
18029 // Tags are compatible, but we might still want to warn on mismatched tags.
18030 // Non-class tags can't be mismatched at this point.
18031 if (!isClassCompatTagKind(Tag: NewTag))
18032 return true;
18033
18034 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
18035 // by our warning analysis. We don't want to warn about mismatches with (eg)
18036 // declarations in system headers that are designed to be specialized, but if
18037 // a user asks us to warn, we should warn if their code contains mismatched
18038 // declarations.
18039 auto IsIgnoredLoc = [&](SourceLocation Loc) {
18040 return getDiagnostics().isIgnored(DiagID: diag::warn_struct_class_tag_mismatch,
18041 Loc);
18042 };
18043 if (IsIgnoredLoc(NewTagLoc))
18044 return true;
18045
18046 auto IsIgnored = [&](const TagDecl *Tag) {
18047 return IsIgnoredLoc(Tag->getLocation());
18048 };
18049 while (IsIgnored(Previous)) {
18050 Previous = Previous->getPreviousDecl();
18051 if (!Previous)
18052 return true;
18053 OldTag = Previous->getTagKind();
18054 }
18055
18056 bool isTemplate = false;
18057 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Previous))
18058 isTemplate = Record->getDescribedClassTemplate();
18059
18060 if (inTemplateInstantiation()) {
18061 if (OldTag != NewTag) {
18062 // In a template instantiation, do not offer fix-its for tag mismatches
18063 // since they usually mess up the template instead of fixing the problem.
18064 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
18065 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
18066 << getRedeclDiagFromTagKind(Tag: OldTag);
18067 // FIXME: Note previous location?
18068 }
18069 return true;
18070 }
18071
18072 if (isDefinition) {
18073 // On definitions, check all previous tags and issue a fix-it for each
18074 // one that doesn't match the current tag.
18075 if (Previous->getDefinition()) {
18076 // Don't suggest fix-its for redefinitions.
18077 return true;
18078 }
18079
18080 bool previousMismatch = false;
18081 for (const TagDecl *I : Previous->redecls()) {
18082 if (I->getTagKind() != NewTag) {
18083 // Ignore previous declarations for which the warning was disabled.
18084 if (IsIgnored(I))
18085 continue;
18086
18087 if (!previousMismatch) {
18088 previousMismatch = true;
18089 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_previous_tag_mismatch)
18090 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
18091 << getRedeclDiagFromTagKind(Tag: I->getTagKind());
18092 }
18093 Diag(Loc: I->getInnerLocStart(), DiagID: diag::note_struct_class_suggestion)
18094 << getRedeclDiagFromTagKind(Tag: NewTag)
18095 << FixItHint::CreateReplacement(RemoveRange: I->getInnerLocStart(),
18096 Code: TypeWithKeyword::getTagTypeKindName(Kind: NewTag));
18097 }
18098 }
18099 return true;
18100 }
18101
18102 // Identify the prevailing tag kind: this is the kind of the definition (if
18103 // there is a non-ignored definition), or otherwise the kind of the prior
18104 // (non-ignored) declaration.
18105 const TagDecl *PrevDef = Previous->getDefinition();
18106 if (PrevDef && IsIgnored(PrevDef))
18107 PrevDef = nullptr;
18108 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
18109 if (Redecl->getTagKind() != NewTag) {
18110 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
18111 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
18112 << getRedeclDiagFromTagKind(Tag: OldTag);
18113 Diag(Loc: Redecl->getLocation(), DiagID: diag::note_previous_use);
18114
18115 // If there is a previous definition, suggest a fix-it.
18116 if (PrevDef) {
18117 Diag(Loc: NewTagLoc, DiagID: diag::note_struct_class_suggestion)
18118 << getRedeclDiagFromTagKind(Tag: Redecl->getTagKind())
18119 << FixItHint::CreateReplacement(RemoveRange: SourceRange(NewTagLoc),
18120 Code: TypeWithKeyword::getTagTypeKindName(Kind: Redecl->getTagKind()));
18121 }
18122 }
18123
18124 return true;
18125}
18126
18127/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
18128/// from an outer enclosing namespace or file scope inside a friend declaration.
18129/// This should provide the commented out code in the following snippet:
18130/// namespace N {
18131/// struct X;
18132/// namespace M {
18133/// struct Y { friend struct /*N::*/ X; };
18134/// }
18135/// }
18136static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
18137 SourceLocation NameLoc) {
18138 // While the decl is in a namespace, do repeated lookup of that name and see
18139 // if we get the same namespace back. If we do not, continue until
18140 // translation unit scope, at which point we have a fully qualified NNS.
18141 SmallVector<IdentifierInfo *, 4> Namespaces;
18142 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
18143 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
18144 // This tag should be declared in a namespace, which can only be enclosed by
18145 // other namespaces. Bail if there's an anonymous namespace in the chain.
18146 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: DC);
18147 if (!Namespace || Namespace->isAnonymousNamespace())
18148 return FixItHint();
18149 IdentifierInfo *II = Namespace->getIdentifier();
18150 Namespaces.push_back(Elt: II);
18151 NamedDecl *Lookup = SemaRef.LookupSingleName(
18152 S, Name: II, Loc: NameLoc, NameKind: Sema::LookupNestedNameSpecifierName);
18153 if (Lookup == Namespace)
18154 break;
18155 }
18156
18157 // Once we have all the namespaces, reverse them to go outermost first, and
18158 // build an NNS.
18159 SmallString<64> Insertion;
18160 llvm::raw_svector_ostream OS(Insertion);
18161 if (DC->isTranslationUnit())
18162 OS << "::";
18163 std::reverse(first: Namespaces.begin(), last: Namespaces.end());
18164 for (auto *II : Namespaces)
18165 OS << II->getName() << "::";
18166 return FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: Insertion);
18167}
18168
18169/// Determine whether a tag originally declared in context \p OldDC can
18170/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
18171/// found a declaration in \p OldDC as a previous decl, perhaps through a
18172/// using-declaration).
18173static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
18174 DeclContext *NewDC) {
18175 OldDC = OldDC->getRedeclContext();
18176 NewDC = NewDC->getRedeclContext();
18177
18178 if (OldDC->Equals(DC: NewDC))
18179 return true;
18180
18181 // In MSVC mode, we allow a redeclaration if the contexts are related (either
18182 // encloses the other).
18183 if (S.getLangOpts().MSVCCompat &&
18184 (OldDC->Encloses(DC: NewDC) || NewDC->Encloses(DC: OldDC)))
18185 return true;
18186
18187 return false;
18188}
18189
18190DeclResult
18191Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
18192 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18193 const ParsedAttributesView &Attrs, AccessSpecifier AS,
18194 SourceLocation ModulePrivateLoc,
18195 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
18196 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
18197 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
18198 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
18199 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
18200 // If this is not a definition, it must have a name.
18201 IdentifierInfo *OrigName = Name;
18202 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
18203 "Nameless record must be a definition!");
18204 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
18205
18206 OwnedDecl = false;
18207 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
18208 bool ScopedEnum = ScopedEnumKWLoc.isValid();
18209
18210 // FIXME: Check member specializations more carefully.
18211 bool isMemberSpecialization = false;
18212 bool IsInjectedClassName = false;
18213 bool Invalid = false;
18214
18215 // We only need to do this matching if we have template parameters
18216 // or a scope specifier, which also conveniently avoids this work
18217 // for non-C++ cases.
18218 if (TemplateParameterLists.size() > 0 ||
18219 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
18220 TemplateParameterList *TemplateParams =
18221 MatchTemplateParametersToScopeSpecifier(
18222 DeclStartLoc: KWLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TemplateParameterLists,
18223 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
18224
18225 // C++23 [dcl.type.elab] p2:
18226 // If an elaborated-type-specifier is the sole constituent of a
18227 // declaration, the declaration is ill-formed unless it is an explicit
18228 // specialization, an explicit instantiation or it has one of the
18229 // following forms: [...]
18230 // C++23 [dcl.enum] p1:
18231 // If the enum-head-name of an opaque-enum-declaration contains a
18232 // nested-name-specifier, the declaration shall be an explicit
18233 // specialization.
18234 //
18235 // FIXME: Class template partial specializations can be forward declared
18236 // per CWG2213, but the resolution failed to allow qualified forward
18237 // declarations. This is almost certainly unintentional, so we allow them.
18238 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
18239 !isMemberSpecialization)
18240 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_standalone_class_nested_name_specifier)
18241 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();
18242
18243 if (TemplateParams) {
18244 if (Kind == TagTypeKind::Enum) {
18245 Diag(Loc: KWLoc, DiagID: diag::err_enum_template);
18246 return true;
18247 }
18248
18249 if (TemplateParams->size() > 0) {
18250 // This is a declaration or definition of a class template (which may
18251 // be a member of another template).
18252
18253 if (Invalid)
18254 return true;
18255
18256 OwnedDecl = false;
18257 DeclResult Result = CheckClassTemplate(
18258 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attr: Attrs, TemplateParams,
18259 AS, ModulePrivateLoc,
18260 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
18261 OuterTemplateParamLists: TemplateParameterLists.data(), IsMemberSpecialization: isMemberSpecialization, SkipBody);
18262 return Result.get();
18263 } else {
18264 // The "template<>" header is extraneous.
18265 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
18266 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18267 isMemberSpecialization = true;
18268 }
18269 }
18270
18271 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
18272 CheckTemplateDeclScope(S, TemplateParams: TemplateParameterLists.back()))
18273 return true;
18274 }
18275
18276 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
18277 // C++23 [dcl.type.elab]p4:
18278 // If an elaborated-type-specifier appears with the friend specifier as
18279 // an entire member-declaration, the member-declaration shall have one
18280 // of the following forms:
18281 // friend class-key nested-name-specifier(opt) identifier ;
18282 // friend class-key simple-template-id ;
18283 // friend class-key nested-name-specifier template(opt)
18284 // simple-template-id ;
18285 //
18286 // Since enum is not a class-key, so declarations like "friend enum E;"
18287 // are ill-formed. Although CWG2363 reaffirms that such declarations are
18288 // invalid, most implementations accept so we issue a pedantic warning.
18289 Diag(Loc: KWLoc, DiagID: diag::ext_enum_friend) << FixItHint::CreateRemoval(
18290 RemoveRange: ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
18291 assert(ScopedEnum || !ScopedEnumUsesClassTag);
18292 Diag(Loc: KWLoc, DiagID: diag::note_enum_friend)
18293 << (ScopedEnum + ScopedEnumUsesClassTag);
18294 }
18295
18296 // Figure out the underlying type if this a enum declaration. We need to do
18297 // this early, because it's needed to detect if this is an incompatible
18298 // redeclaration.
18299 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
18300 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
18301
18302 if (Kind == TagTypeKind::Enum) {
18303 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum) ||
18304 Invalid) {
18305 // No underlying type explicitly specified, or we failed to parse the
18306 // type, default to int.
18307 EnumUnderlying = Context.IntTy.getTypePtr();
18308 } else if (UnderlyingType.get()) {
18309 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
18310 // integral type; any cv-qualification is ignored.
18311 // C23 6.7.3.3p5: The underlying type of the enumeration is the
18312 // unqualified, non-atomic version of the type specified by the type
18313 // specifiers in the specifier qualifier list.
18314 TypeSourceInfo *TI = nullptr;
18315 GetTypeFromParser(Ty: UnderlyingType.get(), TInfo: &TI);
18316 EnumUnderlying = TI;
18317
18318 if (CheckEnumUnderlyingType(TI))
18319 // Recover by falling back to int.
18320 EnumUnderlying = Context.IntTy.getTypePtr();
18321
18322 if (DiagnoseUnexpandedParameterPack(Loc: TI->getTypeLoc().getBeginLoc(), T: TI,
18323 UPPC: UPPC_FixedUnderlyingType))
18324 EnumUnderlying = Context.IntTy.getTypePtr();
18325
18326 // If the underlying type is atomic, we need to adjust the type before
18327 // continuing. This only happens in the case we stored a TypeSourceInfo
18328 // into EnumUnderlying because the other cases are error recovery up to
18329 // this point. But because it's not possible to gin up a TypeSourceInfo
18330 // for a non-atomic type from an atomic one, we'll store into the Type
18331 // field instead. FIXME: it would be nice to have an easy way to get a
18332 // derived TypeSourceInfo which strips qualifiers including the weird
18333 // ones like _Atomic where it forms a different type.
18334 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying);
18335 TI && TI->getType()->isAtomicType())
18336 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
18337
18338 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
18339 // For MSVC ABI compatibility, unfixed enums must use an underlying type
18340 // of 'int'. However, if this is an unfixed forward declaration, don't set
18341 // the underlying type unless the user enables -fms-compatibility. This
18342 // makes unfixed forward declared enums incomplete and is more conforming.
18343 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
18344 EnumUnderlying = Context.IntTy.getTypePtr();
18345 }
18346 }
18347
18348 DeclContext *SearchDC = CurContext;
18349 DeclContext *DC = CurContext;
18350 bool isStdBadAlloc = false;
18351 bool isStdAlignValT = false;
18352
18353 RedeclarationKind Redecl = forRedeclarationInCurContext();
18354 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
18355 Redecl = RedeclarationKind::NotForRedeclaration;
18356
18357 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
18358 /// implemented asks for structural equivalence checking, the returned decl
18359 /// here is passed back to the parser, allowing the tag body to be parsed.
18360 auto createTagFromNewDecl = [&]() -> TagDecl * {
18361 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
18362 // If there is an identifier, use the location of the identifier as the
18363 // location of the decl, otherwise use the location of the struct/union
18364 // keyword.
18365 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18366 TagDecl *New = nullptr;
18367
18368 if (Kind == TagTypeKind::Enum) {
18369 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, PrevDecl: nullptr,
18370 IsScoped: ScopedEnum, IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18371 // If this is an undefined enum, bail.
18372 if (TUK != TagUseKind::Definition && !Invalid)
18373 return nullptr;
18374 if (EnumUnderlying) {
18375 EnumDecl *ED = cast<EnumDecl>(Val: New);
18376 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
18377 ED->setIntegerTypeSourceInfo(TI);
18378 else
18379 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
18380 QualType EnumTy = ED->getIntegerType();
18381 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
18382 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
18383 : EnumTy);
18384 }
18385 } else { // struct/union
18386 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18387 PrevDecl: nullptr);
18388 }
18389
18390 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18391 // Add alignment attributes if necessary; these attributes are checked
18392 // when the ASTContext lays out the structure.
18393 //
18394 // It is important for implementing the correct semantics that this
18395 // happen here (in ActOnTag). The #pragma pack stack is
18396 // maintained as a result of parser callbacks which can occur at
18397 // many points during the parsing of a struct declaration (because
18398 // the #pragma tokens are effectively skipped over during the
18399 // parsing of the struct).
18400 if (TUK == TagUseKind::Definition &&
18401 (!SkipBody || !SkipBody->ShouldSkip)) {
18402 if (LangOpts.HLSL)
18403 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
18404 AddAlignmentAttributesForRecord(RD);
18405 AddMsStructLayoutForRecord(RD);
18406 }
18407 }
18408 New->setLexicalDeclContext(CurContext);
18409 return New;
18410 };
18411
18412 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
18413 if (Name && SS.isNotEmpty()) {
18414 // We have a nested-name tag ('struct foo::bar').
18415
18416 // Check for invalid 'foo::'.
18417 if (SS.isInvalid()) {
18418 Name = nullptr;
18419 goto CreateNewDecl;
18420 }
18421
18422 // If this is a friend or a reference to a class in a dependent
18423 // context, don't try to make a decl for it.
18424 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18425 DC = computeDeclContext(SS, EnteringContext: false);
18426 if (!DC) {
18427 IsDependent = true;
18428 return true;
18429 }
18430 } else {
18431 DC = computeDeclContext(SS, EnteringContext: true);
18432 if (!DC) {
18433 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_dependent_nested_name_spec)
18434 << SS.getRange();
18435 return true;
18436 }
18437 }
18438
18439 if (RequireCompleteDeclContext(SS, DC))
18440 return true;
18441
18442 SearchDC = DC;
18443 // Look-up name inside 'foo::'.
18444 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18445
18446 if (Previous.isAmbiguous())
18447 return true;
18448
18449 if (Previous.empty()) {
18450 // Name lookup did not find anything. However, if the
18451 // nested-name-specifier refers to the current instantiation,
18452 // and that current instantiation has any dependent base
18453 // classes, we might find something at instantiation time: treat
18454 // this as a dependent elaborated-type-specifier.
18455 // But this only makes any sense for reference-like lookups.
18456 if (Previous.wasNotFoundInCurrentInstantiation() &&
18457 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18458 IsDependent = true;
18459 return true;
18460 }
18461
18462 // A tag 'foo::bar' must already exist.
18463 Diag(Loc: NameLoc, DiagID: diag::err_not_tag_in_scope)
18464 << Kind << Name << DC << SS.getRange();
18465 Name = nullptr;
18466 Invalid = true;
18467 goto CreateNewDecl;
18468 }
18469 } else if (Name) {
18470 // C++14 [class.mem]p14:
18471 // If T is the name of a class, then each of the following shall have a
18472 // name different from T:
18473 // -- every member of class T that is itself a type
18474 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18475 DiagnoseClassNameShadow(DC: SearchDC, NameInfo: DeclarationNameInfo(Name, NameLoc)))
18476 return true;
18477
18478 // If this is a named struct, check to see if there was a previous forward
18479 // declaration or definition.
18480 // FIXME: We're looking into outer scopes here, even when we
18481 // shouldn't be. Doing so can result in ambiguities that we
18482 // shouldn't be diagnosing.
18483 LookupName(R&: Previous, S);
18484
18485 // When declaring or defining a tag, ignore ambiguities introduced
18486 // by types using'ed into this scope.
18487 if (Previous.isAmbiguous() &&
18488 (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) {
18489 LookupResult::Filter F = Previous.makeFilter();
18490 while (F.hasNext()) {
18491 NamedDecl *ND = F.next();
18492 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18493 DC: SearchDC->getRedeclContext()))
18494 F.erase();
18495 }
18496 F.done();
18497 }
18498
18499 // C++11 [namespace.memdef]p3:
18500 // If the name in a friend declaration is neither qualified nor
18501 // a template-id and the declaration is a function or an
18502 // elaborated-type-specifier, the lookup to determine whether
18503 // the entity has been previously declared shall not consider
18504 // any scopes outside the innermost enclosing namespace.
18505 //
18506 // MSVC doesn't implement the above rule for types, so a friend tag
18507 // declaration may be a redeclaration of a type declared in an enclosing
18508 // scope. They do implement this rule for friend functions.
18509 //
18510 // Does it matter that this should be by scope instead of by
18511 // semantic context?
18512 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18513 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18514 LookupResult::Filter F = Previous.makeFilter();
18515 bool FriendSawTagOutsideEnclosingNamespace = false;
18516 while (F.hasNext()) {
18517 NamedDecl *ND = F.next();
18518 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
18519 if (DC->isFileContext() &&
18520 !EnclosingNS->Encloses(DC: ND->getDeclContext())) {
18521 if (getLangOpts().MSVCCompat)
18522 FriendSawTagOutsideEnclosingNamespace = true;
18523 else
18524 F.erase();
18525 }
18526 }
18527 F.done();
18528
18529 // Diagnose this MSVC extension in the easy case where lookup would have
18530 // unambiguously found something outside the enclosing namespace.
18531 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18532 NamedDecl *ND = Previous.getFoundDecl();
18533 Diag(Loc: NameLoc, DiagID: diag::ext_friend_tag_redecl_outside_namespace)
18534 << createFriendTagNNSFixIt(SemaRef&: *this, ND, S, NameLoc);
18535 }
18536 }
18537
18538 // Note: there used to be some attempt at recovery here.
18539 if (Previous.isAmbiguous())
18540 return true;
18541
18542 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18543 // FIXME: This makes sure that we ignore the contexts associated
18544 // with C structs, unions, and enums when looking for a matching
18545 // tag declaration or definition. See the similar lookup tweak
18546 // in Sema::LookupName; is there a better way to deal with this?
18547 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(Val: SearchDC))
18548 SearchDC = SearchDC->getParent();
18549 } else if (getLangOpts().CPlusPlus) {
18550 // Inside ObjCContainer want to keep it as a lexical decl context but go
18551 // past it (most often to TranslationUnit) to find the semantic decl
18552 // context.
18553 while (isa<ObjCContainerDecl>(Val: SearchDC))
18554 SearchDC = SearchDC->getParent();
18555 }
18556 } else if (getLangOpts().CPlusPlus) {
18557 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18558 // TagDecl the same way as we skip it for named TagDecl.
18559 while (isa<ObjCContainerDecl>(Val: SearchDC))
18560 SearchDC = SearchDC->getParent();
18561 }
18562
18563 if (Previous.isSingleResult() &&
18564 Previous.getFoundDecl()->isTemplateParameter()) {
18565 // Maybe we will complain about the shadowed template parameter.
18566 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl: Previous.getFoundDecl());
18567 // Just pretend that we didn't see the previous declaration.
18568 Previous.clear();
18569 }
18570
18571 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18572 DC->getRedeclContext()->Equals(DC: getStdNamespace())) {
18573 if (Name->isStr(Str: "bad_alloc")) {
18574 // This is a declaration of or a reference to "std::bad_alloc".
18575 isStdBadAlloc = true;
18576
18577 // If std::bad_alloc has been implicitly declared (but made invisible to
18578 // name lookup), fill in this implicit declaration as the previous
18579 // declaration, so that the declarations get chained appropriately.
18580 if (Previous.empty() && StdBadAlloc)
18581 Previous.addDecl(D: getStdBadAlloc());
18582 } else if (Name->isStr(Str: "align_val_t")) {
18583 isStdAlignValT = true;
18584 if (Previous.empty() && StdAlignValT)
18585 Previous.addDecl(D: getStdAlignValT());
18586 }
18587 }
18588
18589 // If we didn't find a previous declaration, and this is a reference
18590 // (or friend reference), move to the correct scope. In C++, we
18591 // also need to do a redeclaration lookup there, just in case
18592 // there's a shadow friend decl.
18593 if (Name && Previous.empty() &&
18594 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18595 IsTemplateParamOrArg)) {
18596 if (Invalid) goto CreateNewDecl;
18597 assert(SS.isEmpty());
18598
18599 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18600 // C++ [basic.scope.pdecl]p5:
18601 // -- for an elaborated-type-specifier of the form
18602 //
18603 // class-key identifier
18604 //
18605 // if the elaborated-type-specifier is used in the
18606 // decl-specifier-seq or parameter-declaration-clause of a
18607 // function defined in namespace scope, the identifier is
18608 // declared as a class-name in the namespace that contains
18609 // the declaration; otherwise, except as a friend
18610 // declaration, the identifier is declared in the smallest
18611 // non-class, non-function-prototype scope that contains the
18612 // declaration.
18613 //
18614 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18615 // C structs and unions.
18616 //
18617 // It is an error in C++ to declare (rather than define) an enum
18618 // type, including via an elaborated type specifier. We'll
18619 // diagnose that later; for now, declare the enum in the same
18620 // scope as we would have picked for any other tag type.
18621 //
18622 // GNU C also supports this behavior as part of its incomplete
18623 // enum types extension, while GNU C++ does not.
18624 //
18625 // Find the context where we'll be declaring the tag.
18626 // FIXME: We would like to maintain the current DeclContext as the
18627 // lexical context,
18628 SearchDC = getTagInjectionContext(DC: SearchDC);
18629
18630 // Find the scope where we'll be declaring the tag.
18631 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18632 } else {
18633 assert(TUK == TagUseKind::Friend);
18634 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: SearchDC);
18635
18636 // C++ [namespace.memdef]p3:
18637 // If a friend declaration in a non-local class first declares a
18638 // class or function, the friend class or function is a member of
18639 // the innermost enclosing namespace.
18640 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18641 : SearchDC->getEnclosingNamespaceContext();
18642 }
18643
18644 // In C++, we need to do a redeclaration lookup to properly
18645 // diagnose some problems.
18646 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18647 // hidden declaration so that we don't get ambiguity errors when using a
18648 // type declared by an elaborated-type-specifier. In C that is not correct
18649 // and we should instead merge compatible types found by lookup.
18650 if (getLangOpts().CPlusPlus) {
18651 // FIXME: This can perform qualified lookups into function contexts,
18652 // which are meaningless.
18653 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18654 LookupQualifiedName(R&: Previous, LookupCtx: SearchDC);
18655 } else {
18656 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18657 LookupName(R&: Previous, S);
18658 }
18659 }
18660
18661 // If we have a known previous declaration to use, then use it.
18662 if (Previous.empty() && SkipBody && SkipBody->Previous)
18663 Previous.addDecl(D: SkipBody->Previous);
18664
18665 if (!Previous.empty()) {
18666 NamedDecl *PrevDecl = Previous.getFoundDecl();
18667 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18668
18669 // It's okay to have a tag decl in the same scope as a typedef
18670 // which hides a tag decl in the same scope. Finding this
18671 // with a redeclaration lookup can only actually happen in C++.
18672 //
18673 // This is also okay for elaborated-type-specifiers, which is
18674 // technically forbidden by the current standard but which is
18675 // okay according to the likely resolution of an open issue;
18676 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18677 if (getLangOpts().CPlusPlus) {
18678 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18679 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18680 if (Tag->getDeclName() == Name &&
18681 Tag->getDeclContext()->getRedeclContext()
18682 ->Equals(DC: TD->getDeclContext()->getRedeclContext())) {
18683 PrevDecl = Tag;
18684 Previous.clear();
18685 Previous.addDecl(D: Tag);
18686 Previous.resolveKind();
18687 }
18688 }
18689 }
18690 }
18691
18692 // If this is a redeclaration of a using shadow declaration, it must
18693 // declare a tag in the same context. In MSVC mode, we allow a
18694 // redefinition if either context is within the other.
18695 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: DirectPrevDecl)) {
18696 auto *OldTag = dyn_cast<TagDecl>(Val: PrevDecl);
18697 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18698 TUK != TagUseKind::Friend &&
18699 isDeclInScope(D: Shadow, Ctx: SearchDC, S, AllowInlineNamespace: isMemberSpecialization) &&
18700 !(OldTag && isAcceptableTagRedeclContext(
18701 S&: *this, OldDC: OldTag->getDeclContext(), NewDC: SearchDC))) {
18702 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
18703 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
18704 DiagID: diag::note_using_decl_target);
18705 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
18706 << 0;
18707 // Recover by ignoring the old declaration.
18708 Previous.clear();
18709 goto CreateNewDecl;
18710 }
18711 }
18712
18713 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(Val: PrevDecl)) {
18714 // If this is a use of a previous tag, or if the tag is already declared
18715 // in the same scope (so that the definition/declaration completes or
18716 // rementions the tag), reuse the decl.
18717 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18718 isTagRedeclarationInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18719 AllowInlineNamespace: SS.isNotEmpty() ||
18720 isMemberSpecialization)) {
18721
18722 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: PrevDecl);
18723 RD && RD->isInjectedClassName()) {
18724 // If lookup found the injected class name, the previous declaration
18725 // is the class being injected into.
18726 Previous.clear();
18727 PrevDecl = PrevTagDecl = cast<CXXRecordDecl>(Val: RD->getDeclContext());
18728 Previous.addDecl(D: PrevDecl);
18729 Previous.resolveKind();
18730 IsInjectedClassName = true;
18731 }
18732
18733 // Make sure that this wasn't declared as an enum and now used as a
18734 // struct or something similar.
18735 if (!isAcceptableTagRedeclaration(Previous: PrevTagDecl, NewTag: Kind,
18736 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
18737 Name)) {
18738 bool SafeToContinue =
18739 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18740 Kind != TagTypeKind::Enum);
18741 if (SafeToContinue)
18742 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
18743 << Name
18744 << FixItHint::CreateReplacement(RemoveRange: SourceRange(KWLoc),
18745 Code: PrevTagDecl->getKindName());
18746 else
18747 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag) << Name;
18748 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_use);
18749
18750 if (SafeToContinue)
18751 Kind = PrevTagDecl->getTagKind();
18752 else {
18753 // Recover by making this an anonymous redefinition.
18754 Name = nullptr;
18755 Previous.clear();
18756 Invalid = true;
18757 }
18758 }
18759
18760 if (Kind == TagTypeKind::Enum &&
18761 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18762 const EnumDecl *PrevEnum = cast<EnumDecl>(Val: PrevTagDecl);
18763 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18764 return PrevTagDecl;
18765
18766 QualType EnumUnderlyingTy;
18767 if (TypeSourceInfo *TI =
18768 dyn_cast_if_present<TypeSourceInfo *>(Val&: EnumUnderlying))
18769 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18770 else if (const Type *T =
18771 dyn_cast_if_present<const Type *>(Val&: EnumUnderlying))
18772 EnumUnderlyingTy = QualType(T, 0);
18773
18774 // All conflicts with previous declarations are recovered by
18775 // returning the previous declaration, unless this is a definition,
18776 // in which case we want the caller to bail out.
18777 if (CheckEnumRedeclaration(EnumLoc: NameLoc.isValid() ? NameLoc : KWLoc,
18778 IsScoped: ScopedEnum, EnumUnderlyingTy,
18779 IsFixed, Prev: PrevEnum))
18780 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18781 }
18782
18783 // C++11 [class.mem]p1:
18784 // A member shall not be declared twice in the member-specification,
18785 // except that a nested class or member class template can be declared
18786 // and then later defined.
18787 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18788 S->isDeclScope(D: PrevDecl)) {
18789 Diag(Loc: NameLoc, DiagID: diag::ext_member_redeclared);
18790 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_declaration);
18791 }
18792
18793 // C++ [class.local]p3:
18794 // A class nested within a local class is a local class. A member of
18795 // a local class X shall be declared only in the definition of X or,
18796 // if the member is a nested class, in the nearest enclosing block
18797 // scope of X.
18798 if (TUK == TagUseKind::Definition && SS.isValid()) {
18799 if (const auto *OutermostClass = dyn_cast<CXXRecordDecl>(Val: PrevDecl)) {
18800 while (const auto *ParentClass =
18801 dyn_cast<CXXRecordDecl>(Val: OutermostClass->getParent()))
18802 OutermostClass = ParentClass;
18803
18804 if (OutermostClass->isLocalClass() &&
18805 !S->isDeclScope(D: OutermostClass)) {
18806 Diag(Loc: NameLoc, DiagID: diag::err_local_nested_class_invalid_scope)
18807 << Name << OutermostClass;
18808 Diag(Loc: OutermostClass->getLocation(), DiagID: diag::note_defined_here)
18809 << OutermostClass;
18810 }
18811 }
18812 }
18813
18814 if (!Invalid) {
18815 // If this is a use, just return the declaration we found, unless
18816 // we have attributes.
18817 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18818 if (!Attrs.empty()) {
18819 // FIXME: Diagnose these attributes. For now, we create a new
18820 // declaration to hold them.
18821 } else if (TUK == TagUseKind::Reference &&
18822 (PrevTagDecl->getFriendObjectKind() ==
18823 Decl::FOK_Undeclared ||
18824 PrevDecl->getOwningModule() != getCurrentModule()) &&
18825 SS.isEmpty()) {
18826 // This declaration is a reference to an existing entity, but
18827 // has different visibility from that entity: it either makes
18828 // a friend visible or it makes a type visible in a new module.
18829 // In either case, create a new declaration. We only do this if
18830 // the declaration would have meant the same thing if no prior
18831 // declaration were found, that is, if it was found in the same
18832 // scope where we would have injected a declaration.
18833 if (!getTagInjectionContext(DC: CurContext)->getRedeclContext()
18834 ->Equals(DC: PrevDecl->getDeclContext()->getRedeclContext()))
18835 return PrevTagDecl;
18836 // This is in the injected scope, create a new declaration in
18837 // that scope.
18838 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18839 } else {
18840 return PrevTagDecl;
18841 }
18842 }
18843
18844 // Diagnose attempts to redefine a tag.
18845 if (TUK == TagUseKind::Definition) {
18846 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18847 // If the type is currently being defined, complain
18848 // about a nested redefinition.
18849 if (Def->isBeingDefined()) {
18850 Diag(Loc: NameLoc, DiagID: diag::err_nested_redefinition) << Name;
18851 Diag(Loc: PrevTagDecl->getLocation(),
18852 DiagID: diag::note_previous_definition);
18853 Name = nullptr;
18854 Previous.clear();
18855 Invalid = true;
18856 } else {
18857 // If we're defining a specialization and the previous
18858 // definition is from an implicit instantiation, don't emit an
18859 // error here; we'll catch this in the general case below.
18860 bool IsExplicitSpecializationAfterInstantiation = false;
18861 if (isMemberSpecialization) {
18862 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Def))
18863 IsExplicitSpecializationAfterInstantiation =
18864 RD->getTemplateSpecializationKind() !=
18865 TSK_ExplicitSpecialization;
18866 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: Def))
18867 IsExplicitSpecializationAfterInstantiation =
18868 ED->getTemplateSpecializationKind() !=
18869 TSK_ExplicitSpecialization;
18870 }
18871
18872 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18873 // do not keep more that one definition around (merge them).
18874 // However, ensure the decl passes the structural compatibility
18875 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18876 NamedDecl *Hidden = nullptr;
18877 bool HiddenDefVisible = false;
18878 if (SkipBody && (isRedefinitionAllowedFor(D: Def, NewDefinitionLoc: NameLoc, Suggested: &Hidden,
18879 Visible&: HiddenDefVisible) ||
18880 getLangOpts().C23)) {
18881 // There is a definition of this tag, but it is not visible.
18882 // We explicitly make use of C++'s one definition rule here,
18883 // and assume that this definition is identical to the hidden
18884 // one we already have. Make the existing definition visible
18885 // and use it in place of this one.
18886 if (!getLangOpts().CPlusPlus) {
18887 // Postpone making the old definition visible until after we
18888 // complete parsing the new one and do the structural
18889 // comparison.
18890 SkipBody->CheckSameAsPrevious = true;
18891 SkipBody->New = createTagFromNewDecl();
18892 SkipBody->Previous = Def;
18893
18894 ProcessDeclAttributeList(S, D: SkipBody->New, AttrList: Attrs);
18895 return Def;
18896 }
18897
18898 SkipBody->ShouldSkip = true;
18899 SkipBody->Previous = Def;
18900 if (!HiddenDefVisible && Hidden)
18901 makeMergedDefinitionVisible(ND: Hidden);
18902 // Carry on and handle it like a normal definition. We'll
18903 // skip starting the definition later.
18904
18905 } else if (!IsExplicitSpecializationAfterInstantiation) {
18906 // A redeclaration in function prototype scope in C isn't
18907 // visible elsewhere, so merely issue a warning.
18908 if (!getLangOpts().CPlusPlus &&
18909 S->containedInPrototypeScope())
18910 Diag(Loc: NameLoc, DiagID: diag::warn_redefinition_in_param_list)
18911 << Name;
18912 else
18913 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
18914 notePreviousDefinition(Old: Def,
18915 New: NameLoc.isValid() ? NameLoc : KWLoc);
18916 // If this is a redefinition, recover by making this
18917 // struct be anonymous, which will make any later
18918 // references get the previous definition.
18919 Name = nullptr;
18920 Previous.clear();
18921 Invalid = true;
18922 }
18923 }
18924 }
18925
18926 // Okay, this is definition of a previously declared or referenced
18927 // tag. We're going to create a new Decl for it.
18928 }
18929
18930 // Okay, we're going to make a redeclaration. If this is some kind
18931 // of reference, make sure we build the redeclaration in the same DC
18932 // as the original, and ignore the current access specifier.
18933 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference ||
18934 IsInjectedClassName) {
18935 SearchDC = PrevTagDecl->getDeclContext();
18936 AS = AS_none;
18937 }
18938 }
18939 // If we get here we have (another) forward declaration or we
18940 // have a definition. Just create a new decl.
18941
18942 } else {
18943 // If we get here, this is a definition of a new tag type in a nested
18944 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18945 // new decl/type. We set PrevDecl to NULL so that the entities
18946 // have distinct types.
18947 Previous.clear();
18948 }
18949 // If we get here, we're going to create a new Decl. If PrevDecl
18950 // is non-NULL, it's a definition of the tag declared by
18951 // PrevDecl. If it's NULL, we have a new definition.
18952
18953 // Otherwise, PrevDecl is not a tag, but was found with tag
18954 // lookup. This is only actually possible in C++, where a few
18955 // things like templates still live in the tag namespace.
18956 } else {
18957 // Use a better diagnostic if an elaborated-type-specifier
18958 // found the wrong kind of type on the first
18959 // (non-redeclaration) lookup.
18960 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18961 !Previous.isForRedeclaration()) {
18962 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18963 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_non_tag)
18964 << PrevDecl << NTK << Kind;
18965 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_declared_at);
18966 Invalid = true;
18967
18968 // Otherwise, only diagnose if the declaration is in scope.
18969 } else if (!isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18970 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18971 // do nothing
18972
18973 // Diagnose implicit declarations introduced by elaborated types.
18974 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18975 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18976 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_conflict) << NTK;
18977 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18978 Invalid = true;
18979
18980 // Otherwise it's a declaration. Call out a particularly common
18981 // case here.
18982 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18983 unsigned Kind = 0;
18984 if (isa<TypeAliasDecl>(Val: PrevDecl)) Kind = 1;
18985 Diag(Loc: NameLoc, DiagID: diag::err_tag_definition_of_typedef)
18986 << Name << Kind << TND->getUnderlyingType();
18987 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18988 Invalid = true;
18989
18990 // Otherwise, diagnose.
18991 } else {
18992 // The tag name clashes with something else in the target scope,
18993 // issue an error and recover by making this tag be anonymous.
18994 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
18995 notePreviousDefinition(Old: PrevDecl, New: NameLoc);
18996 Name = nullptr;
18997 Invalid = true;
18998 }
18999
19000 // The existing declaration isn't relevant to us; we're in a
19001 // new scope, so clear out the previous declaration.
19002 Previous.clear();
19003 }
19004 }
19005
19006CreateNewDecl:
19007
19008 TagDecl *PrevDecl = nullptr;
19009 if (Previous.isSingleResult())
19010 PrevDecl = cast<TagDecl>(Val: Previous.getFoundDecl());
19011
19012 // If there is an identifier, use the location of the identifier as the
19013 // location of the decl, otherwise use the location of the struct/union
19014 // keyword.
19015 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
19016
19017 // Otherwise, create a new declaration. If there is a previous
19018 // declaration of the same entity, the two will be linked via
19019 // PrevDecl.
19020 TagDecl *New;
19021
19022 if (Kind == TagTypeKind::Enum) {
19023 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
19024 // enum X { A, B, C } D; D should chain to X.
19025 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
19026 PrevDecl: cast_or_null<EnumDecl>(Val: PrevDecl), IsScoped: ScopedEnum,
19027 IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
19028
19029 EnumDecl *ED = cast<EnumDecl>(Val: New);
19030 ED->setEnumKeyRange(SourceRange(
19031 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
19032
19033 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
19034 StdAlignValT = cast<EnumDecl>(Val: New);
19035
19036 // If this is an undefined enum, warn.
19037 if (TUK != TagUseKind::Definition && !Invalid) {
19038 TagDecl *Def;
19039 if (IsFixed && ED->isFixed()) {
19040 // C++0x: 7.2p2: opaque-enum-declaration.
19041 // Conflicts are diagnosed above. Do nothing.
19042 } else if (PrevDecl &&
19043 (Def = cast<EnumDecl>(Val: PrevDecl)->getDefinition())) {
19044 Diag(Loc, DiagID: diag::ext_forward_ref_enum_def)
19045 << New;
19046 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
19047 } else {
19048 unsigned DiagID = diag::ext_forward_ref_enum;
19049 if (getLangOpts().MSVCCompat)
19050 DiagID = diag::ext_ms_forward_ref_enum;
19051 else if (getLangOpts().CPlusPlus)
19052 DiagID = diag::err_forward_ref_enum;
19053 Diag(Loc, DiagID);
19054 }
19055 }
19056
19057 if (EnumUnderlying) {
19058 EnumDecl *ED = cast<EnumDecl>(Val: New);
19059 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
19060 ED->setIntegerTypeSourceInfo(TI);
19061 else
19062 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
19063 QualType EnumTy = ED->getIntegerType();
19064 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
19065 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
19066 : EnumTy);
19067 assert(ED->isComplete() && "enum with type should be complete");
19068 }
19069 } else {
19070 // struct/union/class
19071
19072 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
19073 // struct X { int A; } D; D should chain to X.
19074 if (getLangOpts().CPlusPlus) {
19075 // FIXME: Look for a way to use RecordDecl for simple structs.
19076 New = CXXRecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
19077 PrevDecl: cast_or_null<CXXRecordDecl>(Val: PrevDecl));
19078
19079 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
19080 StdBadAlloc = cast<CXXRecordDecl>(Val: New);
19081 } else
19082 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
19083 PrevDecl: cast_or_null<RecordDecl>(Val: PrevDecl));
19084 }
19085
19086 // Only C23 and later allow defining new types in 'offsetof()'.
19087 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
19088 !getLangOpts().CPlusPlus && !getLangOpts().C23)
19089 Diag(Loc: New->getLocation(), DiagID: diag::ext_type_defined_in_offsetof)
19090 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
19091
19092 // C++11 [dcl.type]p3:
19093 // A type-specifier-seq shall not define a class or enumeration [...].
19094 if (!Invalid && getLangOpts().CPlusPlus &&
19095 (IsTypeSpecifier || IsTemplateParamOrArg) &&
19096 TUK == TagUseKind::Definition) {
19097 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_type_specifier)
19098 << Context.getCanonicalTagType(TD: New);
19099 Invalid = true;
19100 }
19101
19102 if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition &&
19103 DC->getDeclKind() == Decl::Enum) {
19104 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_enum)
19105 << Context.getCanonicalTagType(TD: New);
19106 Invalid = true;
19107 }
19108
19109 // Maybe add qualifier info.
19110 if (SS.isNotEmpty()) {
19111 if (SS.isSet()) {
19112 // If this is either a declaration or a definition, check the
19113 // nested-name-specifier against the current context.
19114 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
19115 diagnoseQualifiedDeclaration(SS, DC, Name: OrigName, Loc,
19116 /*TemplateId=*/nullptr,
19117 IsMemberSpecialization: isMemberSpecialization))
19118 Invalid = true;
19119
19120 New->setQualifierInfo(SS.getWithLocInContext(Context));
19121 if (TemplateParameterLists.size() > 0) {
19122 New->setTemplateParameterListsInfo(Context, TPLists: TemplateParameterLists);
19123 }
19124 }
19125 else
19126 Invalid = true;
19127 }
19128
19129 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
19130 // Add alignment attributes if necessary; these attributes are checked when
19131 // the ASTContext lays out the structure.
19132 //
19133 // It is important for implementing the correct semantics that this
19134 // happen here (in ActOnTag). The #pragma pack stack is
19135 // maintained as a result of parser callbacks which can occur at
19136 // many points during the parsing of a struct declaration (because
19137 // the #pragma tokens are effectively skipped over during the
19138 // parsing of the struct).
19139 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
19140 if (LangOpts.HLSL)
19141 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
19142 AddAlignmentAttributesForRecord(RD);
19143 AddMsStructLayoutForRecord(RD);
19144 }
19145 }
19146
19147 if (ModulePrivateLoc.isValid()) {
19148 if (isMemberSpecialization)
19149 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_specialization)
19150 << 2
19151 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
19152 // __module_private__ does not apply to local classes. However, we only
19153 // diagnose this as an error when the declaration specifiers are
19154 // freestanding. Here, we just ignore the __module_private__.
19155 else if (!SearchDC->isFunctionOrMethod())
19156 New->setModulePrivate();
19157 }
19158
19159 // If this is a specialization of a member class (of a class template),
19160 // check the specialization.
19161 if (isMemberSpecialization && CheckMemberSpecialization(Member: New, Previous))
19162 Invalid = true;
19163
19164 // If we're declaring or defining a tag in function prototype scope in C,
19165 // note that this type can only be used within the function and add it to
19166 // the list of decls to inject into the function definition scope. However,
19167 // in C23 and later, while the type is only visible within the function, the
19168 // function can be called with a compatible type defined in the same TU, so
19169 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
19170 if ((Name || Kind == TagTypeKind::Enum) &&
19171 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
19172 if (getLangOpts().CPlusPlus) {
19173 // C++ [dcl.fct]p6:
19174 // Types shall not be defined in return or parameter types.
19175 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
19176 Diag(Loc, DiagID: diag::err_type_defined_in_param_type)
19177 << Name;
19178 Invalid = true;
19179 }
19180 if (TUK == TagUseKind::Declaration)
19181 Invalid = true;
19182 } else if (!PrevDecl) {
19183 // In C23 mode, if the declaration is complete, we do not want to
19184 // diagnose.
19185 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
19186 Diag(Loc, DiagID: diag::warn_decl_in_param_list)
19187 << Context.getCanonicalTagType(TD: New);
19188 }
19189 }
19190
19191 if (Invalid)
19192 New->setInvalidDecl();
19193
19194 // Set the lexical context. If the tag has a C++ scope specifier, the
19195 // lexical context will be different from the semantic context.
19196 New->setLexicalDeclContext(CurContext);
19197
19198 // Mark this as a friend decl if applicable.
19199 // In Microsoft mode, a friend declaration also acts as a forward
19200 // declaration so we always pass true to setObjectOfFriendDecl to make
19201 // the tag name visible.
19202 if (TUK == TagUseKind::Friend)
19203 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
19204
19205 // Set the access specifier.
19206 if (!Invalid && SearchDC->isRecord())
19207 SetMemberAccessSpecifier(MemberDecl: New, PrevMemberDecl: PrevDecl, LexicalAS: AS);
19208
19209 // FIXME: An elaborated-type-specifier referring to an existing tag should
19210 // ideally not introduce a redeclaration. ActOnTag currently creates one, so
19211 // avoid diagnosing it as a redeclaration across module boundaries.
19212 //
19213 // See https://github.com/llvm/llvm-project/pull/194546 for full background.
19214 if (PrevDecl && TUK != TagUseKind::Reference)
19215 CheckRedeclarationInModule(New, Old: PrevDecl);
19216
19217 if (TUK == TagUseKind::Definition) {
19218 if (!SkipBody || !SkipBody->ShouldSkip) {
19219 New->startDefinition();
19220 } else {
19221 New->setCompleteDefinition();
19222 New->demoteThisDefinitionToDeclaration();
19223 }
19224 }
19225
19226 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
19227 AddPragmaAttributes(S, D: New);
19228
19229 // If this has an identifier, add it to the scope stack.
19230 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
19231 // We might be replacing an existing declaration in the lookup tables;
19232 // if so, borrow its access specifier.
19233 if (PrevDecl)
19234 New->setAccess(PrevDecl->getAccess());
19235
19236 DeclContext *DC = New->getDeclContext()->getRedeclContext();
19237 DC->makeDeclVisibleInContext(D: New);
19238 if (Name) // can be null along some error paths
19239 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
19240 PushOnScopeChains(D: New, S: EnclosingScope, /* AddToContext = */ false);
19241 } else if (Name) {
19242 S = getNonFieldDeclScope(S);
19243 PushOnScopeChains(D: New, S, AddToContext: true);
19244 } else {
19245 CurContext->addDecl(D: New);
19246 }
19247
19248 // If this is the C FILE type, notify the AST context.
19249 if (IdentifierInfo *II = New->getIdentifier())
19250 if (!New->isInvalidDecl() &&
19251 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
19252 II->isStr(Str: "FILE"))
19253 Context.setFILEDecl(New);
19254
19255 if (PrevDecl)
19256 mergeDeclAttributes(New, Old: PrevDecl);
19257
19258 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: New)) {
19259 inferGslOwnerPointerAttribute(Record: CXXRD);
19260 inferNullableClassAttribute(CRD: CXXRD);
19261 }
19262
19263 // If there's a #pragma GCC visibility in scope, set the visibility of this
19264 // record.
19265 AddPushedVisibilityAttribute(RD: New);
19266
19267 // If this is not a definition, process API notes for it now.
19268 if (TUK != TagUseKind::Definition)
19269 ProcessAPINotes(D: New);
19270
19271 if (isMemberSpecialization && !New->isInvalidDecl())
19272 CompleteMemberSpecialization(Member: New, Previous);
19273
19274 OwnedDecl = true;
19275 // In C++, don't return an invalid declaration. We can't recover well from
19276 // the cases where we make the type anonymous.
19277 if (Invalid && getLangOpts().CPlusPlus) {
19278 if (New->isBeingDefined())
19279 if (auto RD = dyn_cast<RecordDecl>(Val: New))
19280 RD->completeDefinition();
19281 return true;
19282 } else if (SkipBody && SkipBody->ShouldSkip) {
19283 return SkipBody->Previous;
19284 } else {
19285 return New;
19286 }
19287}
19288
19289void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
19290 AdjustDeclIfTemplate(Decl&: TagD);
19291 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19292
19293 // Enter the tag context.
19294 PushDeclContext(S, DC: Tag);
19295
19296 ActOnDocumentableDecl(D: TagD);
19297
19298 // If there's a #pragma GCC visibility in scope, set the visibility of this
19299 // record.
19300 AddPushedVisibilityAttribute(RD: Tag);
19301}
19302
19303bool Sema::ActOnDuplicateDefinition(Scope *S, Decl *Prev,
19304 SkipBodyInfo &SkipBody) {
19305 if (!hasStructuralCompatLayout(D: Prev, Suggested: SkipBody.New))
19306 return false;
19307
19308 // Make the previous decl visible.
19309 makeMergedDefinitionVisible(ND: SkipBody.Previous);
19310 CleanupMergedEnum(S, New: SkipBody.New);
19311 return true;
19312}
19313
19314void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
19315 SourceLocation FinalLoc,
19316 bool IsFinalSpelledSealed,
19317 bool IsAbstract,
19318 SourceLocation LBraceLoc) {
19319 AdjustDeclIfTemplate(Decl&: TagD);
19320 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: TagD);
19321
19322 FieldCollector->StartClass();
19323
19324 if (!Record->getIdentifier())
19325 return;
19326
19327 if (IsAbstract)
19328 Record->markAbstract();
19329
19330 if (FinalLoc.isValid()) {
19331 Record->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: FinalLoc,
19332 S: IsFinalSpelledSealed
19333 ? FinalAttr::Keyword_sealed
19334 : FinalAttr::Keyword_final));
19335 }
19336
19337 // C++ [class]p2:
19338 // [...] The class-name is also inserted into the scope of the
19339 // class itself; this is known as the injected-class-name. For
19340 // purposes of access checking, the injected-class-name is treated
19341 // as if it were a public member name.
19342 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
19343 C: Context, TK: Record->getTagKind(), DC: CurContext, StartLoc: Record->getBeginLoc(),
19344 IdLoc: Record->getLocation(), Id: Record->getIdentifier());
19345 InjectedClassName->setImplicit();
19346 InjectedClassName->setAccess(AS_public);
19347 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
19348 InjectedClassName->setDescribedClassTemplate(Template);
19349
19350 PushOnScopeChains(D: InjectedClassName, S);
19351 assert(InjectedClassName->isInjectedClassName() &&
19352 "Broken injected-class-name");
19353}
19354
19355void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
19356 SourceRange BraceRange) {
19357 AdjustDeclIfTemplate(Decl&: TagD);
19358 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19359 Tag->setBraceRange(BraceRange);
19360
19361 // Make sure we "complete" the definition even it is invalid.
19362 if (Tag->isBeingDefined()) {
19363 assert(Tag->isInvalidDecl() && "We should already have completed it");
19364 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
19365 RD->completeDefinition();
19366 }
19367
19368 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
19369 FieldCollector->FinishClass();
19370 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
19371 auto *Def = RD->getDefinition();
19372 assert(Def && "The record is expected to have a completed definition");
19373 unsigned NumInitMethods = 0;
19374 for (auto *Method : Def->methods()) {
19375 if (!Method->getIdentifier())
19376 continue;
19377 if (Method->getName() == "__init")
19378 NumInitMethods++;
19379 }
19380 if (NumInitMethods > 1 || !Def->hasInitMethod())
19381 Diag(Loc: RD->getLocation(), DiagID: diag::err_sycl_special_type_num_init_method);
19382 }
19383
19384 // If we're defining a dynamic class in a module interface unit, we always
19385 // need to produce the vtable for it, even if the vtable is not used in the
19386 // current TU.
19387 //
19388 // The case where the current class is not dynamic is handled in
19389 // MarkVTableUsed.
19390 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
19391 MarkVTableUsed(Loc: RD->getLocation(), Class: RD, /*DefinitionRequired=*/true);
19392 }
19393
19394 // Exit this scope of this tag's definition.
19395 PopDeclContext();
19396
19397 if (getCurLexicalContext()->isObjCContainer() &&
19398 Tag->getDeclContext()->isFileContext())
19399 Tag->setTopLevelDeclInObjCContainer();
19400
19401 // Notify the consumer that we've defined a tag.
19402 if (!Tag->isInvalidDecl())
19403 Consumer.HandleTagDeclDefinition(D: Tag);
19404
19405 // Clangs implementation of #pragma align(packed) differs in bitfield layout
19406 // from XLs and instead matches the XL #pragma pack(1) behavior.
19407 if (Context.getTargetInfo().getTriple().isOSAIX() &&
19408 AlignPackStack.hasValue()) {
19409 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
19410 // Only diagnose #pragma align(packed).
19411 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
19412 return;
19413 const RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag);
19414 if (!RD)
19415 return;
19416 // Only warn if there is at least 1 bitfield member.
19417 if (llvm::any_of(Range: RD->fields(),
19418 P: [](const FieldDecl *FD) { return FD->isBitField(); }))
19419 Diag(Loc: BraceRange.getBegin(), DiagID: diag::warn_pragma_align_not_xl_compatible);
19420 }
19421}
19422
19423void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
19424 AdjustDeclIfTemplate(Decl&: TagD);
19425 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19426 Tag->setInvalidDecl();
19427
19428 // Make sure we "complete" the definition even it is invalid.
19429 if (Tag->isBeingDefined()) {
19430 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
19431 RD->completeDefinition();
19432 }
19433
19434 // We're undoing ActOnTagStartDefinition here, not
19435 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
19436 // the FieldCollector.
19437
19438 PopDeclContext();
19439}
19440
19441// Note that FieldName may be null for anonymous bitfields.
19442ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
19443 const IdentifierInfo *FieldName,
19444 QualType FieldTy, bool IsMsStruct,
19445 Expr *BitWidth) {
19446 assert(BitWidth);
19447 if (BitWidth->containsErrors())
19448 return ExprError();
19449
19450 // C99 6.7.2.1p4 - verify the field type.
19451 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
19452 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19453 // Handle incomplete and sizeless types with a specific error.
19454 if (RequireCompleteSizedType(Loc: FieldLoc, T: FieldTy,
19455 DiagID: diag::err_field_incomplete_or_sizeless))
19456 return ExprError();
19457 if (FieldName)
19458 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_bitfield)
19459 << FieldName << FieldTy << BitWidth->getSourceRange();
19460 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_anon_bitfield)
19461 << FieldTy << BitWidth->getSourceRange();
19462 } else if (DiagnoseUnexpandedParameterPack(E: BitWidth, UPPC: UPPC_BitFieldWidth))
19463 return ExprError();
19464
19465 // If the bit-width is type- or value-dependent, don't try to check
19466 // it now.
19467 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19468 return BitWidth;
19469
19470 llvm::APSInt Value;
19471 ExprResult ICE =
19472 VerifyIntegerConstantExpression(E: BitWidth, Result: &Value, CanFold: AllowFoldKind::Allow);
19473 if (ICE.isInvalid())
19474 return ICE;
19475 BitWidth = ICE.get();
19476
19477 // Zero-width bitfield is ok for anonymous field.
19478 if (Value == 0 && FieldName)
19479 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_zero_width)
19480 << FieldName << BitWidth->getSourceRange();
19481
19482 if (Value.isSigned() && Value.isNegative()) {
19483 if (FieldName)
19484 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_negative_width)
19485 << FieldName << toString(I: Value, Radix: 10);
19486 return Diag(Loc: FieldLoc, DiagID: diag::err_anon_bitfield_has_negative_width)
19487 << toString(I: Value, Radix: 10);
19488 }
19489
19490 // The size of the bit-field must not exceed our maximum permitted object
19491 // size.
19492 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19493 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_too_wide)
19494 << !FieldName << FieldName << toString(I: Value, Radix: 10);
19495 }
19496
19497 if (!FieldTy->isDependentType()) {
19498 uint64_t TypeStorageSize = Context.getTypeSize(T: FieldTy);
19499 uint64_t TypeWidth = Context.getIntWidth(T: FieldTy);
19500 bool BitfieldIsOverwide = Value.ugt(RHS: TypeWidth);
19501
19502 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19503 // ABI.
19504 bool CStdConstraintViolation =
19505 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19506 bool MSBitfieldViolation = Value.ugt(RHS: TypeStorageSize) && IsMsStruct;
19507 if (CStdConstraintViolation || MSBitfieldViolation) {
19508 unsigned DiagWidth =
19509 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19510 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_width_exceeds_type_width)
19511 << (bool)FieldName << FieldName << toString(I: Value, Radix: 10)
19512 << !CStdConstraintViolation << DiagWidth;
19513 }
19514
19515 // Warn on types where the user might conceivably expect to get all
19516 // specified bits as value bits: that's all integral types other than
19517 // 'bool'.
19518 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19519 Diag(Loc: FieldLoc, DiagID: diag::warn_bitfield_width_exceeds_type_width)
19520 << FieldName << Value << (unsigned)TypeWidth;
19521 }
19522 }
19523
19524 if (isa<ConstantExpr>(Val: BitWidth))
19525 return BitWidth;
19526 return ConstantExpr::Create(Context: getASTContext(), E: BitWidth, Result: APValue{Value});
19527}
19528
19529Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
19530 Declarator &D, Expr *BitfieldWidth) {
19531 FieldDecl *Res = HandleField(S, TagD: cast_if_present<RecordDecl>(Val: TagD), DeclStart,
19532 D, BitfieldWidth,
19533 /*InitStyle=*/ICIS_NoInit, AS: AS_public);
19534 return Res;
19535}
19536
19537FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
19538 SourceLocation DeclStart,
19539 Declarator &D, Expr *BitWidth,
19540 InClassInitStyle InitStyle,
19541 AccessSpecifier AS) {
19542 if (D.isDecompositionDeclarator()) {
19543 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
19544 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
19545 << Decomp.getSourceRange();
19546 return nullptr;
19547 }
19548
19549 const IdentifierInfo *II = D.getIdentifier();
19550 SourceLocation Loc = DeclStart;
19551 if (II) Loc = D.getIdentifierLoc();
19552
19553 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19554 QualType T = TInfo->getType();
19555 if (getLangOpts().CPlusPlus) {
19556 CheckExtraCXXDefaultArguments(D);
19557
19558 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19559 UPPC: UPPC_DataMemberType)) {
19560 D.setInvalidType();
19561 T = Context.IntTy;
19562 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19563 }
19564 }
19565
19566 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19567
19568 if (D.getDeclSpec().isInlineSpecified())
19569 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
19570 << getLangOpts().CPlusPlus17;
19571 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19572 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
19573 DiagID: diag::err_invalid_thread)
19574 << DeclSpec::getSpecifierName(S: TSCS);
19575
19576 // Check to see if this name was declared as a member previously
19577 NamedDecl *PrevDecl = nullptr;
19578 LookupResult Previous(*this, II, Loc, LookupMemberName,
19579 RedeclarationKind::ForVisibleRedeclaration);
19580 LookupName(R&: Previous, S);
19581 switch (Previous.getResultKind()) {
19582 case LookupResultKind::Found:
19583 case LookupResultKind::FoundUnresolvedValue:
19584 PrevDecl = Previous.getAsSingle<NamedDecl>();
19585 break;
19586
19587 case LookupResultKind::FoundOverloaded:
19588 PrevDecl = Previous.getRepresentativeDecl();
19589 break;
19590
19591 case LookupResultKind::NotFound:
19592 case LookupResultKind::NotFoundInCurrentInstantiation:
19593 case LookupResultKind::Ambiguous:
19594 break;
19595 }
19596 Previous.suppressDiagnostics();
19597
19598 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19599 // Maybe we will complain about the shadowed template parameter.
19600 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
19601 // Just pretend that we didn't see the previous declaration.
19602 PrevDecl = nullptr;
19603 }
19604
19605 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
19606 PrevDecl = nullptr;
19607
19608 bool Mutable
19609 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19610 SourceLocation TSSL = D.getBeginLoc();
19611 FieldDecl *NewFD
19612 = CheckFieldDecl(Name: II, T, TInfo, Record, Loc, Mutable, BitfieldWidth: BitWidth, InitStyle,
19613 TSSL, AS, PrevDecl, D: &D);
19614
19615 if (NewFD->isInvalidDecl())
19616 Record->setInvalidDecl();
19617
19618 if (D.getDeclSpec().isModulePrivateSpecified())
19619 NewFD->setModulePrivate();
19620
19621 if (NewFD->isInvalidDecl() && PrevDecl) {
19622 // Don't introduce NewFD into scope; there's already something
19623 // with the same name in the same scope.
19624 } else if (II) {
19625 PushOnScopeChains(D: NewFD, S);
19626 } else
19627 Record->addDecl(D: NewFD);
19628
19629 return NewFD;
19630}
19631
19632FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
19633 TypeSourceInfo *TInfo,
19634 RecordDecl *Record, SourceLocation Loc,
19635 bool Mutable, Expr *BitWidth,
19636 InClassInitStyle InitStyle,
19637 SourceLocation TSSL,
19638 AccessSpecifier AS, NamedDecl *PrevDecl,
19639 Declarator *D) {
19640 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19641 bool InvalidDecl = false;
19642 if (D) InvalidDecl = D->isInvalidType();
19643
19644 // If we receive a broken type, recover by assuming 'int' and
19645 // marking this declaration as invalid.
19646 if (T.isNull() || T->containsErrors()) {
19647 InvalidDecl = true;
19648 T = Context.IntTy;
19649 }
19650
19651 QualType EltTy = Context.getBaseElementType(QT: T);
19652 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19653 bool isIncomplete =
19654 LangOpts.HLSL // HLSL allows sizeless builtin types
19655 ? RequireCompleteType(Loc, T: EltTy, DiagID: diag::err_incomplete_type)
19656 : RequireCompleteSizedType(Loc, T: EltTy,
19657 DiagID: diag::err_field_incomplete_or_sizeless);
19658 if (isIncomplete) {
19659 // Fields of incomplete type force their record to be invalid.
19660 Record->setInvalidDecl();
19661 InvalidDecl = true;
19662 } else {
19663 NamedDecl *Def;
19664 EltTy->isIncompleteType(Def: &Def);
19665 if (Def && Def->isInvalidDecl()) {
19666 Record->setInvalidDecl();
19667 InvalidDecl = true;
19668 }
19669 }
19670 }
19671
19672 // TR 18037 does not allow fields to be declared with address space
19673 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19674 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19675 Diag(Loc, DiagID: diag::err_field_with_address_space);
19676 Record->setInvalidDecl();
19677 InvalidDecl = true;
19678 }
19679
19680 if (LangOpts.OpenCL) {
19681 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19682 // used as structure or union field: image, sampler, event or block types.
19683 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19684 T->isBlockPointerType()) {
19685 Diag(Loc, DiagID: diag::err_opencl_type_struct_or_union_field) << T;
19686 Record->setInvalidDecl();
19687 InvalidDecl = true;
19688 }
19689 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19690 // is enabled.
19691 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19692 Ext: "__cl_clang_bitfields", LO: LangOpts)) {
19693 Diag(Loc, DiagID: diag::err_opencl_bitfields);
19694 InvalidDecl = true;
19695 }
19696 }
19697
19698 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19699 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19700 T.hasQualifiers()) {
19701 InvalidDecl = true;
19702 Diag(Loc, DiagID: diag::err_anon_bitfield_qualifiers);
19703 }
19704
19705 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19706 // than a variably modified type.
19707 if (!InvalidDecl && T->isVariablyModifiedType()) {
19708 if (!tryToFixVariablyModifiedVarType(
19709 TInfo, T, Loc, FailedFoldDiagID: diag::err_typecheck_field_variable_size))
19710 InvalidDecl = true;
19711 }
19712
19713 // Fields can not have abstract class types
19714 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19715 DiagID: diag::err_abstract_type_in_decl,
19716 Args: AbstractFieldType))
19717 InvalidDecl = true;
19718
19719 if (InvalidDecl)
19720 BitWidth = nullptr;
19721 // If this is declared as a bit-field, check the bit-field.
19722 if (BitWidth) {
19723 BitWidth =
19724 VerifyBitField(FieldLoc: Loc, FieldName: II, FieldTy: T, IsMsStruct: Record->isMsStruct(C: Context), BitWidth).get();
19725 if (!BitWidth) {
19726 InvalidDecl = true;
19727 BitWidth = nullptr;
19728 }
19729 }
19730
19731 // Check that 'mutable' is consistent with the type of the declaration.
19732 if (!InvalidDecl && Mutable) {
19733 unsigned DiagID = 0;
19734 if (T->isReferenceType())
19735 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19736 : diag::err_mutable_reference;
19737 else if (T.isConstQualified())
19738 DiagID = diag::err_mutable_const;
19739
19740 if (DiagID) {
19741 SourceLocation ErrLoc = Loc;
19742 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19743 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19744 Diag(Loc: ErrLoc, DiagID);
19745 if (DiagID != diag::ext_mutable_reference) {
19746 Mutable = false;
19747 InvalidDecl = true;
19748 }
19749 }
19750 }
19751
19752 // C++11 [class.union]p8 (DR1460):
19753 // At most one variant member of a union may have a
19754 // brace-or-equal-initializer.
19755 if (InitStyle != ICIS_NoInit)
19756 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Record), DefaultInitLoc: Loc);
19757
19758 FieldDecl *NewFD = FieldDecl::Create(C: Context, DC: Record, StartLoc: TSSL, IdLoc: Loc, Id: II, T, TInfo,
19759 BW: BitWidth, Mutable, InitStyle);
19760 if (InvalidDecl)
19761 NewFD->setInvalidDecl();
19762
19763 if (!InvalidDecl)
19764 warnOnCTypeHiddenInCPlusPlus(D: NewFD);
19765
19766 if (PrevDecl && !isa<TagDecl>(Val: PrevDecl) &&
19767 !PrevDecl->isPlaceholderVar(LangOpts: getLangOpts())) {
19768 Diag(Loc, DiagID: diag::err_duplicate_member) << II;
19769 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
19770 NewFD->setInvalidDecl();
19771 }
19772
19773 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19774 if (Record->isUnion()) {
19775 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19776 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19777
19778 // C++ [class.union]p1: An object of a class with a non-trivial
19779 // constructor, a non-trivial copy constructor, a non-trivial
19780 // destructor, or a non-trivial copy assignment operator
19781 // cannot be a member of a union, nor can an array of such
19782 // objects.
19783 if (CheckNontrivialField(FD: NewFD))
19784 NewFD->setInvalidDecl();
19785 }
19786
19787 // C++ [class.union]p1: If a union contains a member of reference type,
19788 // the program is ill-formed, except when compiling with MSVC extensions
19789 // enabled.
19790 if (EltTy->isReferenceType()) {
19791 const bool HaveMSExt =
19792 getLangOpts().MicrosoftExt &&
19793 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
19794
19795 Diag(Loc: NewFD->getLocation(),
19796 DiagID: HaveMSExt ? diag::ext_union_member_of_reference_type
19797 : diag::err_union_member_of_reference_type)
19798 << NewFD->getDeclName() << EltTy;
19799 if (!HaveMSExt)
19800 NewFD->setInvalidDecl();
19801 }
19802 }
19803 }
19804
19805 // FIXME: We need to pass in the attributes given an AST
19806 // representation, not a parser representation.
19807 if (D) {
19808 // FIXME: The current scope is almost... but not entirely... correct here.
19809 ProcessDeclAttributes(S: getCurScope(), D: NewFD, PD: *D);
19810
19811 if (NewFD->hasAttrs())
19812 CheckAlignasUnderalignment(D: NewFD);
19813 }
19814
19815 // In auto-retain/release, infer strong retension for fields of
19816 // retainable type.
19817 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewFD))
19818 NewFD->setInvalidDecl();
19819
19820 if (T.isObjCGCWeak())
19821 Diag(Loc, DiagID: diag::warn_attribute_weak_on_field);
19822
19823 // PPC MMA non-pointer types are not allowed as field types.
19824 if (Context.getTargetInfo().getTriple().isPPC64() &&
19825 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewFD->getLocation()))
19826 NewFD->setInvalidDecl();
19827
19828 if (Context.getTargetInfo().hasAMDGPUTypes()) {
19829 if (!AMDGPU().checkAMDGPUTypeSupport(Ty: T, Loc: NewFD->getLocation()))
19830 NewFD->setInvalidDecl();
19831 }
19832
19833 NewFD->setAccess(AS);
19834 return NewFD;
19835}
19836
19837bool Sema::CheckNontrivialField(FieldDecl *FD) {
19838 assert(FD);
19839 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19840
19841 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19842 return false;
19843
19844 QualType EltTy = Context.getBaseElementType(QT: FD->getType());
19845 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19846 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19847 // We check for copy constructors before constructors
19848 // because otherwise we'll never get complaints about
19849 // copy constructors.
19850
19851 CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;
19852 // We're required to check for any non-trivial constructors. Since the
19853 // implicit default constructor is suppressed if there are any
19854 // user-declared constructors, we just need to check that there is a
19855 // trivial default constructor and a trivial copy constructor. (We don't
19856 // worry about move constructors here, since this is a C++98 check.)
19857 if (RDecl->hasNonTrivialCopyConstructor())
19858 member = CXXSpecialMemberKind::CopyConstructor;
19859 else if (!RDecl->hasTrivialDefaultConstructor())
19860 member = CXXSpecialMemberKind::DefaultConstructor;
19861 else if (RDecl->hasNonTrivialCopyAssignment())
19862 member = CXXSpecialMemberKind::CopyAssignment;
19863 else if (RDecl->hasNonTrivialDestructor())
19864 member = CXXSpecialMemberKind::Destructor;
19865
19866 if (member != CXXSpecialMemberKind::Invalid) {
19867 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19868 RDecl->hasObjectMember()) {
19869 // Objective-C++ ARC: it is an error to have a non-trivial field of
19870 // a union. However, system headers in Objective-C programs
19871 // occasionally have Objective-C lifetime objects within unions,
19872 // and rather than cause the program to fail, we make those
19873 // members unavailable.
19874 SourceLocation Loc = FD->getLocation();
19875 if (getSourceManager().isInSystemHeader(Loc)) {
19876 if (!FD->hasAttr<UnavailableAttr>())
19877 FD->addAttr(A: UnavailableAttr::CreateImplicit(
19878 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership, Range: Loc));
19879 return false;
19880 }
19881 }
19882
19883 Diag(Loc: FD->getLocation(),
19884 DiagID: getLangOpts().CPlusPlus11
19885 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19886 : diag::err_illegal_union_or_anon_struct_member)
19887 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19888 DiagnoseNontrivial(Record: RDecl, CSM: member);
19889 return !getLangOpts().CPlusPlus11;
19890 }
19891 }
19892
19893 return false;
19894}
19895
19896void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
19897 SmallVectorImpl<Decl *> &AllIvarDecls) {
19898 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19899 return;
19900
19901 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19902 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Val: ivarDecl);
19903
19904 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19905 return;
19906 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: CurContext);
19907 if (!ID) {
19908 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(Val: CurContext)) {
19909 if (!CD->IsClassExtension())
19910 return;
19911 }
19912 // No need to add this to end of @implementation.
19913 else
19914 return;
19915 }
19916 // All conditions are met. Add a new bitfield to the tail end of ivars.
19917 llvm::APInt Zero(Context.getTypeSize(T: Context.IntTy), 0);
19918 Expr * BW = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: DeclLoc);
19919 Expr *BitWidth =
19920 ConstantExpr::Create(Context, E: BW, Result: APValue(llvm::APSInt(Zero)));
19921
19922 Ivar = ObjCIvarDecl::Create(
19923 C&: Context, DC: cast<ObjCContainerDecl>(Val: CurContext), StartLoc: DeclLoc, IdLoc: DeclLoc, Id: nullptr,
19924 T: Context.CharTy, TInfo: Context.getTrivialTypeSourceInfo(T: Context.CharTy, Loc: DeclLoc),
19925 ac: ObjCIvarDecl::Private, BW: BitWidth, synthesized: true);
19926 AllIvarDecls.push_back(Elt: Ivar);
19927}
19928
19929/// [class.dtor]p4:
19930/// At the end of the definition of a class, overload resolution is
19931/// performed among the prospective destructors declared in that class with
19932/// an empty argument list to select the destructor for the class, also
19933/// known as the selected destructor.
19934///
19935/// We do the overload resolution here, then mark the selected constructor in the AST.
19936/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19937static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
19938 if (!Record->hasUserDeclaredDestructor()) {
19939 return;
19940 }
19941
19942 SourceLocation Loc = Record->getLocation();
19943 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
19944
19945 for (auto *Decl : Record->decls()) {
19946 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: Decl)) {
19947 if (DD->isInvalidDecl())
19948 continue;
19949 S.AddOverloadCandidate(Function: DD, FoundDecl: DeclAccessPair::make(D: DD, AS: DD->getAccess()), Args: {},
19950 CandidateSet&: OCS);
19951 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19952 }
19953 }
19954
19955 if (OCS.empty()) {
19956 return;
19957 }
19958 OverloadCandidateSet::iterator Best;
19959 unsigned Msg = 0;
19960 OverloadCandidateDisplayKind DisplayKind;
19961
19962 switch (OCS.BestViableFunction(S, Loc, Best)) {
19963 case OR_Success:
19964 case OR_Deleted:
19965 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: Best->Function));
19966 break;
19967
19968 case OR_Ambiguous:
19969 Msg = diag::err_ambiguous_destructor;
19970 DisplayKind = OCD_AmbiguousCandidates;
19971 break;
19972
19973 case OR_No_Viable_Function:
19974 Msg = diag::err_no_viable_destructor;
19975 DisplayKind = OCD_AllCandidates;
19976 break;
19977 }
19978
19979 if (Msg) {
19980 // OpenCL have got their own thing going with destructors. It's slightly broken,
19981 // but we allow it.
19982 if (!S.LangOpts.OpenCL) {
19983 PartialDiagnostic Diag = S.PDiag(DiagID: Msg) << Record;
19984 OCS.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, OCD: DisplayKind, Args: {});
19985 Record->setInvalidDecl();
19986 }
19987 // It's a bit hacky: At this point we've raised an error but we want the
19988 // rest of the compiler to continue somehow working. However almost
19989 // everything we'll try to do with the class will depend on there being a
19990 // destructor. So let's pretend the first one is selected and hope for the
19991 // best.
19992 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: OCS.begin()->Function));
19993 }
19994}
19995
19996/// [class.mem.special]p5
19997/// Two special member functions are of the same kind if:
19998/// - they are both default constructors,
19999/// - they are both copy or move constructors with the same first parameter
20000/// type, or
20001/// - they are both copy or move assignment operators with the same first
20002/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
20003static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
20004 CXXMethodDecl *M1,
20005 CXXMethodDecl *M2,
20006 CXXSpecialMemberKind CSM) {
20007 // We don't want to compare templates to non-templates: See
20008 // https://github.com/llvm/llvm-project/issues/59206
20009 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
20010 return bool(M1->getDescribedFunctionTemplate()) ==
20011 bool(M2->getDescribedFunctionTemplate());
20012 // FIXME: better resolve CWG
20013 // https://cplusplus.github.io/CWG/issues/2787.html
20014 if (!Context.hasSameType(T1: M1->getNonObjectParameter(I: 0)->getType(),
20015 T2: M2->getNonObjectParameter(I: 0)->getType()))
20016 return false;
20017 if (!Context.hasSameType(T1: M1->getFunctionObjectParameterReferenceType(),
20018 T2: M2->getFunctionObjectParameterReferenceType()))
20019 return false;
20020
20021 return true;
20022}
20023
20024/// [class.mem.special]p6:
20025/// An eligible special member function is a special member function for which:
20026/// - the function is not deleted,
20027/// - the associated constraints, if any, are satisfied, and
20028/// - no special member function of the same kind whose associated constraints
20029/// [CWG2595], if any, are satisfied is more constrained.
20030static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
20031 ArrayRef<CXXMethodDecl *> Methods,
20032 CXXSpecialMemberKind CSM) {
20033 SmallVector<bool, 4> SatisfactionStatus;
20034
20035 for (CXXMethodDecl *Method : Methods) {
20036 if (!Method->getTrailingRequiresClause())
20037 SatisfactionStatus.push_back(Elt: true);
20038 else {
20039 ConstraintSatisfaction Satisfaction;
20040 if (S.CheckFunctionConstraints(FD: Method, Satisfaction))
20041 SatisfactionStatus.push_back(Elt: false);
20042 else
20043 SatisfactionStatus.push_back(Elt: Satisfaction.IsSatisfied);
20044 }
20045 }
20046
20047 for (size_t i = 0; i < Methods.size(); i++) {
20048 if (!SatisfactionStatus[i])
20049 continue;
20050 CXXMethodDecl *Method = Methods[i];
20051 CXXMethodDecl *OrigMethod = Method;
20052 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
20053 OrigMethod = cast<CXXMethodDecl>(Val: MF);
20054
20055 AssociatedConstraint Orig = OrigMethod->getTrailingRequiresClause();
20056 bool AnotherMethodIsMoreConstrained = false;
20057 for (size_t j = 0; j < Methods.size(); j++) {
20058 if (i == j || !SatisfactionStatus[j])
20059 continue;
20060 CXXMethodDecl *OtherMethod = Methods[j];
20061 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
20062 OtherMethod = cast<CXXMethodDecl>(Val: MF);
20063
20064 if (!AreSpecialMemberFunctionsSameKind(Context&: S.Context, M1: OrigMethod, M2: OtherMethod,
20065 CSM))
20066 continue;
20067
20068 AssociatedConstraint Other = OtherMethod->getTrailingRequiresClause();
20069 if (!Other)
20070 continue;
20071 if (!Orig) {
20072 AnotherMethodIsMoreConstrained = true;
20073 break;
20074 }
20075 if (S.IsAtLeastAsConstrained(D1: OtherMethod, AC1: {Other}, D2: OrigMethod, AC2: {Orig},
20076 Result&: AnotherMethodIsMoreConstrained)) {
20077 // There was an error with the constraints comparison. Exit the loop
20078 // and don't consider this function eligible.
20079 AnotherMethodIsMoreConstrained = true;
20080 }
20081 if (AnotherMethodIsMoreConstrained)
20082 break;
20083 }
20084 // FIXME: Do not consider deleted methods as eligible after implementing
20085 // DR1734 and DR1496.
20086 if (!AnotherMethodIsMoreConstrained) {
20087 Method->setIneligibleOrNotSelected(false);
20088 Record->addedEligibleSpecialMemberFunction(MD: Method,
20089 SMKind: 1 << llvm::to_underlying(E: CSM));
20090 }
20091 }
20092}
20093
20094static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
20095 CXXRecordDecl *Record) {
20096 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
20097 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
20098 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
20099 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
20100 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
20101
20102 for (auto *Decl : Record->decls()) {
20103 auto *MD = dyn_cast<CXXMethodDecl>(Val: Decl);
20104 if (!MD) {
20105 auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Decl);
20106 if (FTD)
20107 MD = dyn_cast<CXXMethodDecl>(Val: FTD->getTemplatedDecl());
20108 }
20109 if (!MD)
20110 continue;
20111 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD)) {
20112 if (CD->isInvalidDecl())
20113 continue;
20114 if (CD->isDefaultConstructor())
20115 DefaultConstructors.push_back(Elt: MD);
20116 else if (CD->isCopyConstructor())
20117 CopyConstructors.push_back(Elt: MD);
20118 else if (CD->isMoveConstructor())
20119 MoveConstructors.push_back(Elt: MD);
20120 } else if (MD->isCopyAssignmentOperator()) {
20121 CopyAssignmentOperators.push_back(Elt: MD);
20122 } else if (MD->isMoveAssignmentOperator()) {
20123 MoveAssignmentOperators.push_back(Elt: MD);
20124 }
20125 }
20126
20127 SetEligibleMethods(S, Record, Methods: DefaultConstructors,
20128 CSM: CXXSpecialMemberKind::DefaultConstructor);
20129 SetEligibleMethods(S, Record, Methods: CopyConstructors,
20130 CSM: CXXSpecialMemberKind::CopyConstructor);
20131 SetEligibleMethods(S, Record, Methods: MoveConstructors,
20132 CSM: CXXSpecialMemberKind::MoveConstructor);
20133 SetEligibleMethods(S, Record, Methods: CopyAssignmentOperators,
20134 CSM: CXXSpecialMemberKind::CopyAssignment);
20135 SetEligibleMethods(S, Record, Methods: MoveAssignmentOperators,
20136 CSM: CXXSpecialMemberKind::MoveAssignment);
20137}
20138
20139bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
20140 // Check to see if a FieldDecl is a pointer to a function.
20141 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
20142 const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
20143 if (!FD) {
20144 // Check whether this is a forward declaration that was inserted by
20145 // Clang. This happens when a non-forward declared / defined type is
20146 // used, e.g.:
20147 //
20148 // struct foo {
20149 // struct bar *(*f)();
20150 // struct bar *(*g)();
20151 // };
20152 //
20153 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
20154 // incomplete definition.
20155 if (const auto *TD = dyn_cast<TagDecl>(Val: D))
20156 return !TD->isCompleteDefinition();
20157 return false;
20158 }
20159 QualType FieldType = FD->getType().getDesugaredType(Context);
20160 if (isa<PointerType>(Val: FieldType)) {
20161 QualType PointeeType = cast<PointerType>(Val&: FieldType)->getPointeeType();
20162 return PointeeType.getDesugaredType(Context)->isFunctionType();
20163 }
20164 // If a member is a struct entirely of function pointers, that counts too.
20165 if (const auto *Record = FieldType->getAsRecordDecl();
20166 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
20167 return true;
20168 return false;
20169 };
20170
20171 return llvm::all_of(Range: Record->decls(), P: IsFunctionPointerOrForwardDecl);
20172}
20173
20174void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
20175 ArrayRef<Decl *> Fields, SourceLocation LBrac,
20176 SourceLocation RBrac,
20177 const ParsedAttributesView &Attrs) {
20178 assert(EnclosingDecl && "missing record or interface decl");
20179
20180 // If this is an Objective-C @implementation or category and we have
20181 // new fields here we should reset the layout of the interface since
20182 // it will now change.
20183 if (!Fields.empty() && isa<ObjCContainerDecl>(Val: EnclosingDecl)) {
20184 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(Val: EnclosingDecl);
20185 switch (DC->getKind()) {
20186 default: break;
20187 case Decl::ObjCCategory:
20188 Context.ResetObjCLayout(D: cast<ObjCCategoryDecl>(Val: DC)->getClassInterface());
20189 break;
20190 case Decl::ObjCImplementation:
20191 Context.
20192 ResetObjCLayout(D: cast<ObjCImplementationDecl>(Val: DC)->getClassInterface());
20193 break;
20194 }
20195 }
20196
20197 RecordDecl *Record = dyn_cast<RecordDecl>(Val: EnclosingDecl);
20198 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Val: EnclosingDecl);
20199
20200 // Start counting up the number of named members; make sure to include
20201 // members of anonymous structs and unions in the total.
20202 unsigned NumNamedMembers = 0;
20203 if (Record) {
20204 for (const auto *I : Record->decls()) {
20205 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
20206 if (IFD->getDeclName())
20207 ++NumNamedMembers;
20208 }
20209 }
20210
20211 // Verify that all the fields are okay.
20212 SmallVector<FieldDecl*, 32> RecFields;
20213 const FieldDecl *PreviousField = nullptr;
20214 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
20215 i != end; PreviousField = cast<FieldDecl>(Val: *i), ++i) {
20216 FieldDecl *FD = cast<FieldDecl>(Val: *i);
20217
20218 // Get the type for the field.
20219 const Type *FDTy = FD->getType().getTypePtr();
20220
20221 if (!FD->isAnonymousStructOrUnion()) {
20222 // Remember all fields written by the user.
20223 RecFields.push_back(Elt: FD);
20224 }
20225
20226 // If the field is already invalid for some reason, don't emit more
20227 // diagnostics about it.
20228 if (FD->isInvalidDecl()) {
20229 EnclosingDecl->setInvalidDecl();
20230 continue;
20231 }
20232
20233 // C99 6.7.2.1p2:
20234 // A structure or union shall not contain a member with
20235 // incomplete or function type (hence, a structure shall not
20236 // contain an instance of itself, but may contain a pointer to
20237 // an instance of itself), except that the last member of a
20238 // structure with more than one named member may have incomplete
20239 // array type; such a structure (and any union containing,
20240 // possibly recursively, a member that is such a structure)
20241 // shall not be a member of a structure or an element of an
20242 // array.
20243 bool IsLastField = (i + 1 == Fields.end());
20244 if (FDTy->isFunctionType()) {
20245 // Field declared as a function.
20246 Diag(Loc: FD->getLocation(), DiagID: diag::err_field_declared_as_function)
20247 << FD->getDeclName();
20248 FD->setInvalidDecl();
20249 EnclosingDecl->setInvalidDecl();
20250 continue;
20251 } else if (FDTy->isIncompleteArrayType() &&
20252 (Record || isa<ObjCContainerDecl>(Val: EnclosingDecl))) {
20253 if (Record) {
20254 // Flexible array member.
20255 // Microsoft and g++ is more permissive regarding flexible array.
20256 // It will accept flexible array in union and also
20257 // as the sole element of a struct/class.
20258 unsigned DiagID = 0;
20259 if (!Record->isUnion() && !IsLastField) {
20260 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_not_at_end)
20261 << FD->getDeclName() << FD->getType() << Record->getTagKind();
20262 Diag(Loc: (*(i + 1))->getLocation(), DiagID: diag::note_next_field_declaration);
20263 FD->setInvalidDecl();
20264 EnclosingDecl->setInvalidDecl();
20265 continue;
20266 } else if (Record->isUnion())
20267 DiagID = getLangOpts().MicrosoftExt
20268 ? diag::ext_flexible_array_union_ms
20269 : diag::ext_flexible_array_union_gnu;
20270 else if (NumNamedMembers < 1)
20271 DiagID = getLangOpts().MicrosoftExt
20272 ? diag::ext_flexible_array_empty_aggregate_ms
20273 : diag::ext_flexible_array_empty_aggregate_gnu;
20274
20275 if (DiagID)
20276 Diag(Loc: FD->getLocation(), DiagID)
20277 << FD->getDeclName() << Record->getTagKind();
20278 // While the layout of types that contain virtual bases is not specified
20279 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
20280 // virtual bases after the derived members. This would make a flexible
20281 // array member declared at the end of an object not adjacent to the end
20282 // of the type.
20283 if (CXXRecord && CXXRecord->getNumVBases() != 0)
20284 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_virtual_base)
20285 << FD->getDeclName() << Record->getTagKind();
20286 if (!getLangOpts().C99)
20287 Diag(Loc: FD->getLocation(), DiagID: diag::ext_c99_flexible_array_member)
20288 << FD->getDeclName() << Record->getTagKind();
20289
20290 // If the element type has a non-trivial destructor, we would not
20291 // implicitly destroy the elements, so disallow it for now.
20292 //
20293 // FIXME: GCC allows this. We should probably either implicitly delete
20294 // the destructor of the containing class, or just allow this.
20295 QualType BaseElem = Context.getBaseElementType(QT: FD->getType());
20296 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
20297 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_has_nontrivial_dtor)
20298 << FD->getDeclName() << FD->getType();
20299 FD->setInvalidDecl();
20300 EnclosingDecl->setInvalidDecl();
20301 continue;
20302 }
20303 // Okay, we have a legal flexible array member at the end of the struct.
20304 Record->setHasFlexibleArrayMember(true);
20305 } else {
20306 // In ObjCContainerDecl ivars with incomplete array type are accepted,
20307 // unless they are followed by another ivar. That check is done
20308 // elsewhere, after synthesized ivars are known.
20309 }
20310 } else if (!FDTy->isDependentType() &&
20311 (LangOpts.HLSL // HLSL allows sizeless builtin types
20312 ? RequireCompleteType(Loc: FD->getLocation(), T: FD->getType(),
20313 DiagID: diag::err_incomplete_type)
20314 : RequireCompleteSizedType(
20315 Loc: FD->getLocation(), T: FD->getType(),
20316 DiagID: diag::err_field_incomplete_or_sizeless))) {
20317 // Incomplete type
20318 FD->setInvalidDecl();
20319 EnclosingDecl->setInvalidDecl();
20320 continue;
20321 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
20322 if (Record && RD->hasFlexibleArrayMember()) {
20323 // A type which contains a flexible array member is considered to be a
20324 // flexible array member.
20325 Record->setHasFlexibleArrayMember(true);
20326 if (!Record->isUnion()) {
20327 // If this is a struct/class and this is not the last element, reject
20328 // it. Note that GCC supports variable sized arrays in the middle of
20329 // structures.
20330 if (!IsLastField)
20331 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variable_sized_type_in_struct)
20332 << FD->getDeclName() << FD->getType();
20333 else {
20334 // We support flexible arrays at the end of structs in
20335 // other structs as an extension.
20336 Diag(Loc: FD->getLocation(), DiagID: diag::ext_flexible_array_in_struct)
20337 << FD->getDeclName();
20338 }
20339 }
20340 }
20341 if (isa<ObjCContainerDecl>(Val: EnclosingDecl) &&
20342 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getType(),
20343 DiagID: diag::err_abstract_type_in_decl,
20344 Args: AbstractIvarType)) {
20345 // Ivars can not have abstract class types
20346 FD->setInvalidDecl();
20347 }
20348 if (Record && RD->hasObjectMember())
20349 Record->setHasObjectMember(true);
20350 if (Record && RD->hasVolatileMember())
20351 Record->setHasVolatileMember(true);
20352 } else if (FDTy->isObjCObjectType()) {
20353 /// A field cannot be an Objective-c object
20354 Diag(Loc: FD->getLocation(), DiagID: diag::err_statically_allocated_object)
20355 << FixItHint::CreateInsertion(InsertionLoc: FD->getLocation(), Code: "*");
20356 QualType T = Context.getObjCObjectPointerType(OIT: FD->getType());
20357 FD->setType(T);
20358 } else if (Record && Record->isUnion() &&
20359 FD->getType().hasNonTrivialObjCLifetime() &&
20360 getSourceManager().isInSystemHeader(Loc: FD->getLocation()) &&
20361 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
20362 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
20363 !Context.hasDirectOwnershipQualifier(Ty: FD->getType()))) {
20364 // For backward compatibility, fields of C unions declared in system
20365 // headers that have non-trivial ObjC ownership qualifications are marked
20366 // as unavailable unless the qualifier is explicit and __strong. This can
20367 // break ABI compatibility between programs compiled with ARC and MRR, but
20368 // is a better option than rejecting programs using those unions under
20369 // ARC.
20370 FD->addAttr(A: UnavailableAttr::CreateImplicit(
20371 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership,
20372 Range: FD->getLocation()));
20373 } else if (getLangOpts().ObjC &&
20374 getLangOpts().getGC() != LangOptions::NonGC && Record &&
20375 !Record->hasObjectMember()) {
20376 if (FD->getType()->isObjCObjectPointerType() ||
20377 FD->getType().isObjCGCStrong())
20378 Record->setHasObjectMember(true);
20379 else if (Context.getAsArrayType(T: FD->getType())) {
20380 QualType BaseType = Context.getBaseElementType(QT: FD->getType());
20381 if (const auto *RD = BaseType->getAsRecordDecl();
20382 RD && RD->hasObjectMember())
20383 Record->setHasObjectMember(true);
20384 else if (BaseType->isObjCObjectPointerType() ||
20385 BaseType.isObjCGCStrong())
20386 Record->setHasObjectMember(true);
20387 }
20388 }
20389
20390 if (Record && !getLangOpts().CPlusPlus &&
20391 !shouldIgnoreForRecordTriviality(FD)) {
20392 QualType FT = FD->getType();
20393 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
20394 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
20395 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
20396 Record->isUnion())
20397 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
20398 }
20399 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
20400 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
20401 Record->setNonTrivialToPrimitiveCopy(true);
20402 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
20403 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
20404 }
20405 if (FD->hasAttr<ExplicitInitAttr>())
20406 Record->setHasUninitializedExplicitInitFields(true);
20407 if (FT.isDestructedType()) {
20408 Record->setNonTrivialToPrimitiveDestroy(true);
20409 Record->setParamDestroyedInCallee(true);
20410 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
20411 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
20412 }
20413
20414 if (const auto *RD = FT->getAsRecordDecl()) {
20415 if (RD->getArgPassingRestrictions() ==
20416 RecordArgPassingKind::CanNeverPassInRegs)
20417 Record->setArgPassingRestrictions(
20418 RecordArgPassingKind::CanNeverPassInRegs);
20419 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
20420 Record->setArgPassingRestrictions(
20421 RecordArgPassingKind::CanNeverPassInRegs);
20422 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
20423 Q && Q.isAddressDiscriminated()) {
20424 Record->setArgPassingRestrictions(
20425 RecordArgPassingKind::CanNeverPassInRegs);
20426 Record->setNonTrivialToPrimitiveCopy(true);
20427 }
20428 }
20429
20430 if (Record && FD->getType().isVolatileQualified())
20431 Record->setHasVolatileMember(true);
20432 bool ReportMSBitfieldStoragePacking =
20433 Record && PreviousField &&
20434 !Diags.isIgnored(DiagID: diag::warn_ms_bitfield_mismatched_storage_packing,
20435 Loc: Record->getLocation());
20436 auto IsNonDependentBitField = [](const FieldDecl *FD) {
20437 return FD->isBitField() && !FD->getType()->isDependentType();
20438 };
20439
20440 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
20441 IsNonDependentBitField(PreviousField)) {
20442 CharUnits FDStorageSize = Context.getTypeSizeInChars(T: FD->getType());
20443 CharUnits PreviousFieldStorageSize =
20444 Context.getTypeSizeInChars(T: PreviousField->getType());
20445 if (FDStorageSize != PreviousFieldStorageSize) {
20446 Diag(Loc: FD->getLocation(),
20447 DiagID: diag::warn_ms_bitfield_mismatched_storage_packing)
20448 << FD << FD->getType() << FDStorageSize.getQuantity()
20449 << PreviousFieldStorageSize.getQuantity();
20450 Diag(Loc: PreviousField->getLocation(),
20451 DiagID: diag::note_ms_bitfield_mismatched_storage_size_previous)
20452 << PreviousField << PreviousField->getType();
20453 }
20454 }
20455 // Keep track of the number of named members.
20456 if (FD->getIdentifier())
20457 ++NumNamedMembers;
20458 }
20459
20460 // Okay, we successfully defined 'Record'.
20461 if (Record) {
20462 bool Completed = false;
20463 if (S) {
20464 Scope *Parent = S->getParent();
20465 if (Parent && Parent->isTypeAliasScope() &&
20466 Parent->isTemplateParamScope())
20467 Record->setInvalidDecl();
20468 }
20469
20470 if (CXXRecord) {
20471 if (!CXXRecord->isInvalidDecl()) {
20472 // Set access bits correctly on the directly-declared conversions.
20473 for (CXXRecordDecl::conversion_iterator
20474 I = CXXRecord->conversion_begin(),
20475 E = CXXRecord->conversion_end(); I != E; ++I)
20476 I.setAccess((*I)->getAccess());
20477 }
20478
20479 // Add any implicitly-declared members to this class.
20480 AddImplicitlyDeclaredMembersToClass(ClassDecl: CXXRecord);
20481
20482 if (!CXXRecord->isDependentType()) {
20483 if (!CXXRecord->isInvalidDecl()) {
20484 // If we have virtual base classes, we may end up finding multiple
20485 // final overriders for a given virtual function. Check for this
20486 // problem now.
20487 if (CXXRecord->getNumVBases()) {
20488 CXXFinalOverriderMap FinalOverriders;
20489 CXXRecord->getFinalOverriders(FinaOverriders&: FinalOverriders);
20490
20491 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20492 MEnd = FinalOverriders.end();
20493 M != MEnd; ++M) {
20494 for (OverridingMethods::iterator SO = M->second.begin(),
20495 SOEnd = M->second.end();
20496 SO != SOEnd; ++SO) {
20497 assert(SO->second.size() > 0 &&
20498 "Virtual function without overriding functions?");
20499 if (SO->second.size() == 1)
20500 continue;
20501
20502 // C++ [class.virtual]p2:
20503 // In a derived class, if a virtual member function of a base
20504 // class subobject has more than one final overrider the
20505 // program is ill-formed.
20506 Diag(Loc: Record->getLocation(), DiagID: diag::err_multiple_final_overriders)
20507 << (const NamedDecl *)M->first << Record;
20508 Diag(Loc: M->first->getLocation(),
20509 DiagID: diag::note_overridden_virtual_function);
20510 for (OverridingMethods::overriding_iterator
20511 OM = SO->second.begin(),
20512 OMEnd = SO->second.end();
20513 OM != OMEnd; ++OM)
20514 Diag(Loc: OM->Method->getLocation(), DiagID: diag::note_final_overrider)
20515 << (const NamedDecl *)M->first << OM->Method->getParent();
20516
20517 Record->setInvalidDecl();
20518 }
20519 }
20520 CXXRecord->completeDefinition(FinalOverriders: &FinalOverriders);
20521 Completed = true;
20522 }
20523 }
20524 ComputeSelectedDestructor(S&: *this, Record: CXXRecord);
20525 ComputeSpecialMemberFunctionsEligiblity(S&: *this, Record: CXXRecord);
20526 }
20527 }
20528
20529 if (!Completed)
20530 Record->completeDefinition();
20531
20532 // Handle attributes before checking the layout.
20533 ProcessDeclAttributeList(S, D: Record, AttrList: Attrs);
20534
20535 // Maybe randomize the record's decls. We automatically randomize a record
20536 // of function pointers, unless it has the "no_randomize_layout" attribute.
20537 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20538 !Record->isRandomized() && !Record->isUnion() &&
20539 (Record->hasAttr<RandomizeLayoutAttr>() ||
20540 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20541 EntirelyFunctionPointers(Record)))) {
20542 SmallVector<Decl *, 32> NewDeclOrdering;
20543 if (randstruct::randomizeStructureLayout(Context, RD: Record,
20544 FinalOrdering&: NewDeclOrdering))
20545 Record->reorderDecls(Decls: NewDeclOrdering);
20546 }
20547
20548 // We may have deferred checking for a deleted destructor. Check now.
20549 if (CXXRecord) {
20550 auto *Dtor = CXXRecord->getDestructor();
20551 if (Dtor && Dtor->isImplicit() &&
20552 ShouldDeleteSpecialMember(MD: Dtor, CSM: CXXSpecialMemberKind::Destructor)) {
20553 CXXRecord->setImplicitDestructorIsDeleted();
20554 SetDeclDeleted(dcl: Dtor, DelLoc: CXXRecord->getLocation());
20555 }
20556 }
20557
20558 if (Record->hasAttrs()) {
20559 CheckAlignasUnderalignment(D: Record);
20560
20561 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20562 checkMSInheritanceAttrOnDefinition(RD: cast<CXXRecordDecl>(Val: Record),
20563 Range: IA->getRange(), BestCase: IA->getBestCase(),
20564 SemanticSpelling: IA->getInheritanceModel());
20565 }
20566
20567 // Check if the structure/union declaration is a type that can have zero
20568 // size in C. For C this is a language extension, for C++ it may cause
20569 // compatibility problems.
20570 bool CheckForZeroSize;
20571 if (!getLangOpts().CPlusPlus) {
20572 CheckForZeroSize = true;
20573 } else {
20574 // For C++ filter out types that cannot be referenced in C code.
20575 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record);
20576 CheckForZeroSize =
20577 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20578 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20579 CXXRecord->isCLike();
20580 }
20581 if (CheckForZeroSize) {
20582 bool ZeroSize = true;
20583 bool IsEmpty = true;
20584 unsigned NonBitFields = 0;
20585 for (RecordDecl::field_iterator I = Record->field_begin(),
20586 E = Record->field_end();
20587 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20588 IsEmpty = false;
20589 if (I->isUnnamedBitField()) {
20590 if (!I->isZeroLengthBitField())
20591 ZeroSize = false;
20592 } else {
20593 ++NonBitFields;
20594 QualType FieldType = I->getType();
20595 if (FieldType->isIncompleteType() ||
20596 !Context.getTypeSizeInChars(T: FieldType).isZero())
20597 ZeroSize = false;
20598 }
20599 }
20600
20601 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20602 // allowed in C++, but warn if its declaration is inside
20603 // extern "C" block.
20604 if (ZeroSize) {
20605 Diag(Loc: RecLoc, DiagID: getLangOpts().CPlusPlus ?
20606 diag::warn_zero_size_struct_union_in_extern_c :
20607 diag::warn_zero_size_struct_union_compat)
20608 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20609 }
20610
20611 // Structs without named members are extension in C (C99 6.7.2.1p7),
20612 // but are accepted by GCC. In C2y, this became implementation-defined
20613 // (C2y 6.7.3.2p10).
20614 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20615 Diag(Loc: RecLoc, DiagID: IsEmpty ? diag::ext_empty_struct_union
20616 : diag::ext_no_named_members_in_struct_union)
20617 << Record->isUnion();
20618 }
20619 }
20620 } else {
20621 ObjCIvarDecl **ClsFields =
20622 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20623 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: EnclosingDecl)) {
20624 ID->setEndOfDefinitionLoc(RBrac);
20625 // Add ivar's to class's DeclContext.
20626 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20627 ClsFields[i]->setLexicalDeclContext(ID);
20628 ID->addDecl(D: ClsFields[i]);
20629 }
20630 // Must enforce the rule that ivars in the base classes may not be
20631 // duplicates.
20632 if (ID->getSuperClass())
20633 ObjC().DiagnoseDuplicateIvars(ID, SID: ID->getSuperClass());
20634 } else if (ObjCImplementationDecl *IMPDecl =
20635 dyn_cast<ObjCImplementationDecl>(Val: EnclosingDecl)) {
20636 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20637 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20638 // Ivar declared in @implementation never belongs to the implementation.
20639 // Only it is in implementation's lexical context.
20640 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20641 ObjC().CheckImplementationIvars(ImpDecl: IMPDecl, Fields: ClsFields, nIvars: RecFields.size(),
20642 Loc: RBrac);
20643 IMPDecl->setIvarLBraceLoc(LBrac);
20644 IMPDecl->setIvarRBraceLoc(RBrac);
20645 } else if (ObjCCategoryDecl *CDecl =
20646 dyn_cast<ObjCCategoryDecl>(Val: EnclosingDecl)) {
20647 // case of ivars in class extension; all other cases have been
20648 // reported as errors elsewhere.
20649 // FIXME. Class extension does not have a LocEnd field.
20650 // CDecl->setLocEnd(RBrac);
20651 // Add ivar's to class extension's DeclContext.
20652 // Diagnose redeclaration of private ivars.
20653 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20654 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20655 if (IDecl) {
20656 if (const ObjCIvarDecl *ClsIvar =
20657 IDecl->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20658 Diag(Loc: ClsFields[i]->getLocation(),
20659 DiagID: diag::err_duplicate_ivar_declaration);
20660 Diag(Loc: ClsIvar->getLocation(), DiagID: diag::note_previous_definition);
20661 continue;
20662 }
20663 for (const auto *Ext : IDecl->known_extensions()) {
20664 if (const ObjCIvarDecl *ClsExtIvar
20665 = Ext->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20666 Diag(Loc: ClsFields[i]->getLocation(),
20667 DiagID: diag::err_duplicate_ivar_declaration);
20668 Diag(Loc: ClsExtIvar->getLocation(), DiagID: diag::note_previous_definition);
20669 continue;
20670 }
20671 }
20672 }
20673 ClsFields[i]->setLexicalDeclContext(CDecl);
20674 CDecl->addDecl(D: ClsFields[i]);
20675 }
20676 CDecl->setIvarLBraceLoc(LBrac);
20677 CDecl->setIvarRBraceLoc(RBrac);
20678 }
20679 }
20680
20681 if (Record)
20682 AMDGPU().checkNamedBarrierWrapper(R: Record);
20683
20684 if (Record && !isa<ClassTemplateSpecializationDecl>(Val: Record))
20685 ProcessAPINotes(D: Record);
20686}
20687
20688// Given an integral type, return the next larger integral type
20689// (or a NULL type of no such type exists).
20690static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
20691 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20692 // enum checking below.
20693 assert((T->isIntegralType(Context) ||
20694 T->isEnumeralType()) && "Integral type required!");
20695 const unsigned NumTypes = 4;
20696 QualType SignedIntegralTypes[NumTypes] = {
20697 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20698 };
20699 QualType UnsignedIntegralTypes[NumTypes] = {
20700 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20701 Context.UnsignedLongLongTy
20702 };
20703
20704 // Compare value widths, not storage sizes: a _BitInt(33) is stored in 64
20705 // bits but a 64-bit standard type can still represent its incremented
20706 // value. C23 6.7.3.3p12 does not allow the widened type to be a
20707 // bit-precise type either.
20708 unsigned BitWidth = Context.getIntWidth(T);
20709 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20710 : UnsignedIntegralTypes;
20711 for (unsigned I = 0; I != NumTypes; ++I)
20712 if (Context.getTypeSize(T: Types[I]) > BitWidth)
20713 return Types[I];
20714
20715 return QualType();
20716}
20717
20718EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
20719 EnumConstantDecl *LastEnumConst,
20720 SourceLocation IdLoc,
20721 IdentifierInfo *Id,
20722 Expr *Val) {
20723 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20724 llvm::APSInt EnumVal(IntWidth);
20725 QualType EltTy;
20726
20727 if (Val && DiagnoseUnexpandedParameterPack(E: Val, UPPC: UPPC_EnumeratorValue))
20728 Val = nullptr;
20729
20730 if (Val)
20731 Val = DefaultLvalueConversion(E: Val).get();
20732
20733 if (Val) {
20734 if (Enum->isDependentType() || Val->isTypeDependent() ||
20735 Val->containsErrors())
20736 EltTy = Context.DependentTy;
20737 else {
20738 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20739 // underlying type, but do allow it in all other contexts.
20740 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20741 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20742 // constant-expression in the enumerator-definition shall be a converted
20743 // constant expression of the underlying type.
20744 EltTy = Enum->getIntegerType();
20745 ExprResult Converted = CheckConvertedConstantExpression(
20746 From: Val, T: EltTy, Value&: EnumVal, CCE: CCEKind::Enumerator);
20747 if (Converted.isInvalid())
20748 Val = nullptr;
20749 else
20750 Val = Converted.get();
20751 } else if (!Val->isValueDependent() &&
20752 !(Val = VerifyIntegerConstantExpression(E: Val, Result: &EnumVal,
20753 CanFold: AllowFoldKind::Allow)
20754 .get())) {
20755 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20756 } else {
20757 if (Enum->isComplete()) {
20758 EltTy = Enum->getIntegerType();
20759
20760 // In Obj-C and Microsoft mode, require the enumeration value to be
20761 // representable in the underlying type of the enumeration. In C++11,
20762 // we perform a non-narrowing conversion as part of converted constant
20763 // expression checking.
20764 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20765 if (Context.getTargetInfo()
20766 .getTriple()
20767 .isWindowsMSVCEnvironment()) {
20768 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_too_large) << EltTy;
20769 } else {
20770 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_too_large) << EltTy;
20771 }
20772 }
20773
20774 // Cast to the underlying type.
20775 Val = ImpCastExprToType(E: Val, Type: EltTy,
20776 CK: EltTy->isBooleanType() ? CK_IntegralToBoolean
20777 : CK_IntegralCast)
20778 .get();
20779 } else if (getLangOpts().CPlusPlus) {
20780 // C++11 [dcl.enum]p5:
20781 // If the underlying type is not fixed, the type of each enumerator
20782 // is the type of its initializing value:
20783 // - If an initializer is specified for an enumerator, the
20784 // initializing value has the same type as the expression.
20785 EltTy = Val->getType();
20786 } else {
20787 // C99 6.7.2.2p2:
20788 // The expression that defines the value of an enumeration constant
20789 // shall be an integer constant expression that has a value
20790 // representable as an int.
20791
20792 // Complain if the value is not representable in an int.
20793 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: Context.IntTy)) {
20794 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20795 ? diag::warn_c17_compat_enum_value_not_int
20796 : diag::ext_c23_enum_value_not_int)
20797 << 0 << toString(I: EnumVal, Radix: 10) << Val->getSourceRange()
20798 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20799 } else if (!Context.hasSameType(T1: Val->getType(), T2: Context.IntTy)) {
20800 // Force the type of the expression to 'int'.
20801 Val = ImpCastExprToType(E: Val, Type: Context.IntTy, CK: CK_IntegralCast).get();
20802 }
20803 EltTy = Val->getType();
20804 }
20805 }
20806 }
20807 }
20808
20809 if (!Val) {
20810 if (Enum->isDependentType())
20811 EltTy = Context.DependentTy;
20812 else if (!LastEnumConst) {
20813 // C++0x [dcl.enum]p5:
20814 // If the underlying type is not fixed, the type of each enumerator
20815 // is the type of its initializing value:
20816 // - If no initializer is specified for the first enumerator, the
20817 // initializing value has an unspecified integral type.
20818 //
20819 // GCC uses 'int' for its unspecified integral type, as does
20820 // C99 6.7.2.2p3.
20821 if (Enum->isFixed()) {
20822 EltTy = Enum->getIntegerType();
20823 }
20824 else {
20825 EltTy = Context.IntTy;
20826 }
20827 } else {
20828 // Assign the last value + 1.
20829 EnumVal = LastEnumConst->getInitVal();
20830 ++EnumVal;
20831 EltTy = LastEnumConst->getType();
20832
20833 // Check for overflow on increment.
20834 if (EnumVal < LastEnumConst->getInitVal()) {
20835 // C++0x [dcl.enum]p5:
20836 // If the underlying type is not fixed, the type of each enumerator
20837 // is the type of its initializing value:
20838 //
20839 // - Otherwise the type of the initializing value is the same as
20840 // the type of the initializing value of the preceding enumerator
20841 // unless the incremented value is not representable in that type,
20842 // in which case the type is an unspecified integral type
20843 // sufficient to contain the incremented value. If no such type
20844 // exists, the program is ill-formed.
20845 QualType T = getNextLargerIntegralType(Context, T: EltTy);
20846 if (T.isNull() || Enum->isFixed()) {
20847 // There is no integral type larger enough to represent this
20848 // value. Complain, then allow the value to wrap around.
20849 EnumVal = LastEnumConst->getInitVal();
20850 EnumVal = EnumVal.zext(width: EnumVal.getBitWidth() * 2);
20851 ++EnumVal;
20852 if (Enum->isFixed())
20853 // When the underlying type is fixed, this is ill-formed.
20854 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_wrapped)
20855 << toString(I: EnumVal, Radix: 10)
20856 << EltTy;
20857 else
20858 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_increment_too_large)
20859 << toString(I: EnumVal, Radix: 10);
20860 } else {
20861 EltTy = T;
20862 }
20863
20864 // Retrieve the last enumerator's value, extent that type to the
20865 // type that is supposed to be large enough to represent the incremented
20866 // value, then increment.
20867 EnumVal = LastEnumConst->getInitVal();
20868 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20869 EnumVal = EnumVal.zextOrTrunc(width: Context.getIntWidth(T: EltTy));
20870 ++EnumVal;
20871
20872 // If we're not in C++, diagnose the overflow of enumerator values,
20873 // which in C99 means that the enumerator value is not representable in
20874 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20875 // are representable in some larger integral type and we allow it in
20876 // older language modes as an extension.
20877 // Exclude fixed enumerators since they are diagnosed with an error for
20878 // this case.
20879 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20880 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20881 ? diag::warn_c17_compat_enum_value_not_int
20882 : diag::ext_c23_enum_value_not_int)
20883 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20884 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20885 !Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20886 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20887 Diag(Loc: IdLoc, DiagID: getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20888 : diag::ext_c23_enum_value_not_int)
20889 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20890 }
20891 }
20892 }
20893
20894 if (!EltTy->isDependentType()) {
20895 // Make the enumerator value match the signedness and size of the
20896 // enumerator's type.
20897 EnumVal = EnumVal.extOrTrunc(width: Context.getIntWidth(T: EltTy));
20898 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20899 }
20900
20901 return EnumConstantDecl::Create(C&: Context, DC: Enum, L: IdLoc, Id, T: EltTy,
20902 E: Val, V: EnumVal);
20903}
20904
20905SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
20906 SourceLocation IILoc) {
20907 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20908 !getLangOpts().CPlusPlus)
20909 return SkipBodyInfo();
20910
20911 // We have an anonymous enum definition. Look up the first enumerator to
20912 // determine if we should merge the definition with an existing one and
20913 // skip the body.
20914 NamedDecl *PrevDecl = LookupSingleName(S, Name: II, Loc: IILoc, NameKind: LookupOrdinaryName,
20915 Redecl: forRedeclarationInCurContext());
20916 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(Val: PrevDecl);
20917 if (!PrevECD)
20918 return SkipBodyInfo();
20919
20920 EnumDecl *PrevED = cast<EnumDecl>(Val: PrevECD->getDeclContext());
20921 NamedDecl *Hidden;
20922 if (!PrevED->getDeclName() && !hasVisibleDefinition(D: PrevED, Suggested: &Hidden)) {
20923 SkipBodyInfo Skip;
20924 Skip.Previous = Hidden;
20925 return Skip;
20926 }
20927
20928 return SkipBodyInfo();
20929}
20930
20931Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20932 SourceLocation IdLoc, IdentifierInfo *Id,
20933 const ParsedAttributesView &Attrs,
20934 SourceLocation EqualLoc, Expr *Val,
20935 SkipBodyInfo *SkipBody) {
20936 EnumDecl *TheEnumDecl = cast<EnumDecl>(Val: theEnumDecl);
20937 EnumConstantDecl *LastEnumConst =
20938 cast_or_null<EnumConstantDecl>(Val: lastEnumConst);
20939
20940 // The scope passed in may not be a decl scope. Zip up the scope tree until
20941 // we find one that is.
20942 S = getNonFieldDeclScope(S);
20943
20944 // Verify that there isn't already something declared with this name in this
20945 // scope.
20946 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20947 RedeclarationKind::ForVisibleRedeclaration);
20948 LookupName(R, S);
20949 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20950
20951 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20952 // Maybe we will complain about the shadowed template parameter.
20953 DiagnoseTemplateParameterShadow(Loc: IdLoc, PrevDecl);
20954 // Just pretend that we didn't see the previous declaration.
20955 PrevDecl = nullptr;
20956 }
20957
20958 // C++ [class.mem]p15:
20959 // If T is the name of a class, then each of the following shall have a name
20960 // different from T:
20961 // - every enumerator of every member of class T that is an unscoped
20962 // enumerated type
20963 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20964 DiagnoseClassNameShadow(DC: TheEnumDecl->getDeclContext(),
20965 NameInfo: DeclarationNameInfo(Id, IdLoc)))
20966 return nullptr;
20967
20968 EnumConstantDecl *New =
20969 CheckEnumConstant(Enum: TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20970 if (!New)
20971 return nullptr;
20972
20973 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20974 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(Val: PrevDecl)) {
20975 // Check for other kinds of shadowing not already handled.
20976 CheckShadow(D: New, ShadowedDecl: PrevDecl, R);
20977 }
20978
20979 // When in C++, we may get a TagDecl with the same name; in this case the
20980 // enum constant will 'hide' the tag.
20981 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20982 "Received TagDecl when not in C++!");
20983 if (!isa<TagDecl>(Val: PrevDecl) && isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
20984 if (isa<EnumConstantDecl>(Val: PrevDecl))
20985 Diag(Loc: IdLoc, DiagID: diag::err_redefinition_of_enumerator) << Id;
20986 else
20987 Diag(Loc: IdLoc, DiagID: diag::err_redefinition) << Id;
20988 notePreviousDefinition(Old: PrevDecl, New: IdLoc);
20989 return nullptr;
20990 }
20991 }
20992
20993 // Process attributes.
20994 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
20995 AddPragmaAttributes(S, D: New);
20996 ProcessAPINotes(D: New);
20997
20998 // Register this decl in the current scope stack.
20999 New->setAccess(TheEnumDecl->getAccess());
21000 PushOnScopeChains(D: New, S);
21001
21002 ActOnDocumentableDecl(D: New);
21003
21004 return New;
21005}
21006
21007// Returns true when the enum initial expression does not trigger the
21008// duplicate enum warning. A few common cases are exempted as follows:
21009// Element2 = Element1
21010// Element2 = Element1 + 1
21011// Element2 = Element1 - 1
21012// Where Element2 and Element1 are from the same enum.
21013static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
21014 Expr *InitExpr = ECD->getInitExpr();
21015 if (!InitExpr)
21016 return true;
21017 InitExpr = InitExpr->IgnoreImpCasts();
21018
21019 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: InitExpr)) {
21020 if (!BO->isAdditiveOp())
21021 return true;
21022 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: BO->getRHS());
21023 if (!IL)
21024 return true;
21025 if (IL->getValue() != 1)
21026 return true;
21027
21028 InitExpr = BO->getLHS();
21029 }
21030
21031 // This checks if the elements are from the same enum.
21032 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InitExpr);
21033 if (!DRE)
21034 return true;
21035
21036 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(Val: DRE->getDecl());
21037 if (!EnumConstant)
21038 return true;
21039
21040 if (cast<EnumDecl>(Val: TagDecl::castFromDeclContext(DC: ECD->getDeclContext())) !=
21041 Enum)
21042 return true;
21043
21044 return false;
21045}
21046
21047// Emits a warning when an element is implicitly set a value that
21048// a previous element has already been set to.
21049static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
21050 EnumDecl *Enum, QualType EnumType) {
21051 // Avoid anonymous enums
21052 if (!Enum->getIdentifier())
21053 return;
21054
21055 // Only check for small enums.
21056 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
21057 return;
21058
21059 if (S.Diags.isIgnored(DiagID: diag::warn_duplicate_enum_values, Loc: Enum->getLocation()))
21060 return;
21061
21062 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
21063 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
21064
21065 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
21066
21067 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
21068 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
21069
21070 // Use int64_t as a key to avoid needing special handling for map keys.
21071 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
21072 llvm::APSInt Val = D->getInitVal();
21073 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
21074 };
21075
21076 DuplicatesVector DupVector;
21077 ValueToVectorMap EnumMap;
21078
21079 // Populate the EnumMap with all values represented by enum constants without
21080 // an initializer.
21081 for (auto *Element : Elements) {
21082 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: Element);
21083
21084 // Null EnumConstantDecl means a previous diagnostic has been emitted for
21085 // this constant. Skip this enum since it may be ill-formed.
21086 if (!ECD) {
21087 return;
21088 }
21089
21090 // Constants with initializers are handled in the next loop.
21091 if (ECD->getInitExpr())
21092 continue;
21093
21094 // Duplicate values are handled in the next loop.
21095 EnumMap.insert(x: {EnumConstantToKey(ECD), ECD});
21096 }
21097
21098 if (EnumMap.size() == 0)
21099 return;
21100
21101 // Create vectors for any values that has duplicates.
21102 for (auto *Element : Elements) {
21103 // The last loop returned if any constant was null.
21104 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Val: Element);
21105 if (!ValidDuplicateEnum(ECD, Enum))
21106 continue;
21107
21108 auto Iter = EnumMap.find(x: EnumConstantToKey(ECD));
21109 if (Iter == EnumMap.end())
21110 continue;
21111
21112 DeclOrVector& Entry = Iter->second;
21113 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Val&: Entry)) {
21114 // Ensure constants are different.
21115 if (D == ECD)
21116 continue;
21117
21118 // Create new vector and push values onto it.
21119 auto Vec = std::make_unique<ECDVector>();
21120 Vec->push_back(Elt: D);
21121 Vec->push_back(Elt: ECD);
21122
21123 // Update entry to point to the duplicates vector.
21124 Entry = Vec.get();
21125
21126 // Store the vector somewhere we can consult later for quick emission of
21127 // diagnostics.
21128 DupVector.emplace_back(Args: std::move(Vec));
21129 continue;
21130 }
21131
21132 ECDVector *Vec = cast<ECDVector *>(Val&: Entry);
21133 // Make sure constants are not added more than once.
21134 if (*Vec->begin() == ECD)
21135 continue;
21136
21137 Vec->push_back(Elt: ECD);
21138 }
21139
21140 // Emit diagnostics.
21141 for (const auto &Vec : DupVector) {
21142 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
21143
21144 // Emit warning for one enum constant.
21145 auto *FirstECD = Vec->front();
21146 S.Diag(Loc: FirstECD->getLocation(), DiagID: diag::warn_duplicate_enum_values)
21147 << FirstECD << toString(I: FirstECD->getInitVal(), Radix: 10)
21148 << FirstECD->getSourceRange();
21149
21150 // Emit one note for each of the remaining enum constants with
21151 // the same value.
21152 for (auto *ECD : llvm::drop_begin(RangeOrContainer&: *Vec))
21153 S.Diag(Loc: ECD->getLocation(), DiagID: diag::note_duplicate_element)
21154 << ECD << toString(I: ECD->getInitVal(), Radix: 10)
21155 << ECD->getSourceRange();
21156 }
21157}
21158
21159bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
21160 bool AllowMask) const {
21161 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
21162 assert(ED->isCompleteDefinition() && "expected enum definition");
21163
21164 auto R = FlagBitsCache.try_emplace(Key: ED);
21165 llvm::APInt &FlagBits = R.first->second;
21166
21167 if (R.second) {
21168 for (auto *E : ED->enumerators()) {
21169 const auto &EVal = E->getInitVal();
21170 // Only single-bit enumerators introduce new flag values.
21171 if (EVal.isPowerOf2())
21172 FlagBits = FlagBits.zext(width: EVal.getBitWidth()) | EVal;
21173 }
21174 }
21175
21176 // A value is in a flag enum if either its bits are a subset of the enum's
21177 // flag bits (the first condition) or we are allowing masks and the same is
21178 // true of its complement (the second condition). When masks are allowed, we
21179 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
21180 //
21181 // While it's true that any value could be used as a mask, the assumption is
21182 // that a mask will have all of the insignificant bits set. Anything else is
21183 // likely a logic error.
21184 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(width: Val.getBitWidth());
21185 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
21186}
21187
21188// Emits a warning when a suspicious comparison operator is used along side
21189// binary operators in enum initializers.
21190static void CheckForComparisonInEnumInitializer(SemaBase &Sema,
21191 const EnumDecl *Enum) {
21192 bool HasBitwiseOp = false;
21193 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
21194
21195 // Iterate over all the enum values, gather suspisious comparison ops and
21196 // whether any enum initialisers contain a binary operator.
21197 for (const auto *ECD : Enum->enumerators()) {
21198 const Expr *InitExpr = ECD->getInitExpr();
21199 if (!InitExpr)
21200 continue;
21201
21202 const Expr *E = InitExpr->IgnoreParenImpCasts();
21203
21204 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: E)) {
21205 BinaryOperatorKind Op = BinOp->getOpcode();
21206
21207 // Check for bitwise ops (<<, >>, &, |)
21208 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
21209 HasBitwiseOp = true;
21210 } else if (Op == BO_LT || Op == BO_GT) {
21211 // Check for the typo pattern (Comparison < or >)
21212 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
21213 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(Val: LHS)) {
21214 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
21215 if (IntLiteral->getValue() == 1)
21216 SuspiciousCompares.push_back(Elt: BinOp);
21217 }
21218 }
21219 }
21220 }
21221
21222 // If we found a bitwise op and some sus compares, iterate over the compares
21223 // and warn.
21224 if (HasBitwiseOp) {
21225 for (const auto *BinOp : SuspiciousCompares) {
21226 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
21227 ? BinaryOperator::getOpcodeStr(Op: BO_Shl)
21228 : BinaryOperator::getOpcodeStr(Op: BO_Shr);
21229 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
21230
21231 Sema.Diag(Loc: OperatorLoc, DiagID: diag::warn_comparison_in_enum_initializer)
21232 << BinOp->getOpcodeStr() << SuggestedOp;
21233
21234 Sema.Diag(Loc: OperatorLoc, DiagID: diag::note_enum_compare_typo_suggest)
21235 << SuggestedOp
21236 << FixItHint::CreateReplacement(RemoveRange: OperatorLoc, Code: SuggestedOp);
21237 }
21238 }
21239}
21240
21241void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
21242 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
21243 const ParsedAttributesView &Attrs) {
21244 EnumDecl *Enum = cast<EnumDecl>(Val: EnumDeclX);
21245 CanQualType EnumType = Context.getCanonicalTagType(TD: Enum);
21246
21247 ProcessDeclAttributeList(S, D: Enum, AttrList: Attrs);
21248 ProcessAPINotes(D: Enum);
21249
21250 if (Enum->isDependentType()) {
21251 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
21252 EnumConstantDecl *ECD =
21253 cast_or_null<EnumConstantDecl>(Val: Elements[i]);
21254 if (!ECD) continue;
21255
21256 ECD->setType(EnumType);
21257 }
21258
21259 Enum->completeDefinition(NewType: Context.DependentTy, PromotionType: Context.DependentTy, NumPositiveBits: 0, NumNegativeBits: 0);
21260 return;
21261 }
21262
21263 // Verify that all the values are okay, compute the size of the values, and
21264 // reverse the list.
21265 unsigned NumNegativeBits = 0;
21266 unsigned NumPositiveBits = 0;
21267 bool MembersRepresentableByInt =
21268 Context.computeEnumBits(EnumConstants: Elements, NumNegativeBits, NumPositiveBits);
21269
21270 // Figure out the type that should be used for this enum.
21271 QualType BestType;
21272 unsigned BestWidth;
21273
21274 // C++0x N3000 [conv.prom]p3:
21275 // An rvalue of an unscoped enumeration type whose underlying
21276 // type is not fixed can be converted to an rvalue of the first
21277 // of the following types that can represent all the values of
21278 // the enumeration: int, unsigned int, long int, unsigned long
21279 // int, long long int, or unsigned long long int.
21280 // C99 6.4.4.3p2:
21281 // An identifier declared as an enumeration constant has type int.
21282 // The C99 rule is modified by C23.
21283 QualType BestPromotionType;
21284
21285 bool Packed = Enum->hasAttr<PackedAttr>();
21286 // -fshort-enums is the equivalent to specifying the packed attribute on all
21287 // enum definitions.
21288 if (LangOpts.ShortEnums)
21289 Packed = true;
21290
21291 // If the enum already has a type because it is fixed or dictated by the
21292 // target, promote that type instead of analyzing the enumerators.
21293 if (Enum->isComplete()) {
21294 BestType = Enum->getIntegerType();
21295 if (Context.isPromotableIntegerType(T: BestType))
21296 BestPromotionType = Context.getPromotedIntegerType(PromotableType: BestType);
21297 else
21298 BestPromotionType = BestType;
21299
21300 BestWidth = Context.getIntWidth(T: BestType);
21301 } else {
21302 bool EnumTooLarge = Context.computeBestEnumTypes(
21303 IsPacked: Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
21304 BestWidth = Context.getIntWidth(T: BestType);
21305 if (EnumTooLarge)
21306 Diag(Loc: Enum->getLocation(), DiagID: diag::ext_enum_too_large);
21307 }
21308
21309 // Loop over all of the enumerator constants, changing their types to match
21310 // the type of the enum if needed.
21311 for (auto *D : Elements) {
21312 auto *ECD = cast_or_null<EnumConstantDecl>(Val: D);
21313 if (!ECD) continue; // Already issued a diagnostic.
21314
21315 // C99 says the enumerators have int type, but we allow, as an
21316 // extension, the enumerators to be larger than int size. If each
21317 // enumerator value fits in an int, type it as an int, otherwise type it the
21318 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
21319 // that X has type 'int', not 'unsigned'.
21320
21321 // Determine whether the value fits into an int.
21322 llvm::APSInt InitVal = ECD->getInitVal();
21323
21324 // If it fits into an integer type, force it. Otherwise force it to match
21325 // the enum decl type.
21326 QualType NewTy;
21327 unsigned NewWidth;
21328 bool NewSign;
21329 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
21330 MembersRepresentableByInt) {
21331 // C23 6.7.3.3.3p15:
21332 // The enumeration member type for an enumerated type without fixed
21333 // underlying type upon completion is:
21334 // - int if all the values of the enumeration are representable as an
21335 // int; or,
21336 // - the enumerated type
21337 NewTy = Context.IntTy;
21338 NewWidth = Context.getTargetInfo().getIntWidth();
21339 NewSign = true;
21340 } else if (ECD->getType() == BestType) {
21341 // Already the right type!
21342 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
21343 // C++ [dcl.enum]p4: Following the closing brace of an
21344 // enum-specifier, each enumerator has the type of its
21345 // enumeration.
21346 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21347 // with fixed underlying type is the enumerated type.
21348 ECD->setType(EnumType);
21349 continue;
21350 } else {
21351 NewTy = BestType;
21352 NewWidth = BestWidth;
21353 NewSign = BestType->isSignedIntegerOrEnumerationType();
21354 }
21355
21356 // Adjust the APSInt value.
21357 InitVal = InitVal.extOrTrunc(width: NewWidth);
21358 InitVal.setIsSigned(NewSign);
21359 ECD->setInitVal(C: Context, V: InitVal);
21360
21361 // Adjust the Expr initializer and type.
21362 if (ECD->getInitExpr() &&
21363 !Context.hasSameType(T1: NewTy, T2: ECD->getInitExpr()->getType()))
21364 ECD->setInitExpr(ImplicitCastExpr::Create(
21365 Context, T: NewTy, Kind: CK_IntegralCast, Operand: ECD->getInitExpr(),
21366 /*base paths*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()));
21367 if (getLangOpts().CPlusPlus ||
21368 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
21369 // C++ [dcl.enum]p4: Following the closing brace of an
21370 // enum-specifier, each enumerator has the type of its
21371 // enumeration.
21372 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21373 // with fixed underlying type is the enumerated type.
21374 ECD->setType(EnumType);
21375 else
21376 ECD->setType(NewTy);
21377 }
21378
21379 Enum->completeDefinition(NewType: BestType, PromotionType: BestPromotionType,
21380 NumPositiveBits, NumNegativeBits);
21381
21382 CheckForDuplicateEnumValues(S&: *this, Elements, Enum, EnumType);
21383 CheckForComparisonInEnumInitializer(Sema&: *this, Enum);
21384
21385 if (Enum->isClosedFlag()) {
21386 for (Decl *D : Elements) {
21387 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: D);
21388 if (!ECD) continue; // Already issued a diagnostic.
21389
21390 llvm::APSInt InitVal = ECD->getInitVal();
21391 if (InitVal != 0 && !InitVal.isPowerOf2() &&
21392 !IsValueInFlagEnum(ED: Enum, Val: InitVal, AllowMask: true))
21393 Diag(Loc: ECD->getLocation(), DiagID: diag::warn_flag_enum_constant_out_of_range)
21394 << ECD << Enum;
21395 }
21396 }
21397
21398 // Now that the enum type is defined, ensure it's not been underaligned.
21399 if (Enum->hasAttrs())
21400 CheckAlignasUnderalignment(D: Enum);
21401}
21402
21403Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, SourceLocation StartLoc,
21404 SourceLocation EndLoc) {
21405
21406 FileScopeAsmDecl *New =
21407 FileScopeAsmDecl::Create(C&: Context, DC: CurContext, Str: expr, AsmLoc: StartLoc, RParenLoc: EndLoc);
21408 CurContext->addDecl(D: New);
21409 return New;
21410}
21411
21412TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {
21413 auto *New = TopLevelStmtDecl::Create(C&: Context, /*Statement=*/nullptr);
21414 CurContext->addDecl(D: New);
21415 PushDeclContext(S, DC: New);
21416 PushFunctionScope();
21417 PushCompoundScope(IsStmtExpr: false);
21418 return New;
21419}
21420
21421void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {
21422 if (Statement)
21423 D->setStmt(Statement);
21424 PopCompoundScope();
21425 PopFunctionScopeInfo();
21426 PopDeclContext();
21427}
21428
21429void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
21430 IdentifierInfo* AliasName,
21431 SourceLocation PragmaLoc,
21432 SourceLocation NameLoc,
21433 SourceLocation AliasNameLoc) {
21434 NamedDecl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc,
21435 NameKind: LookupOrdinaryName);
21436 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
21437 AttributeCommonInfo::Form::Pragma());
21438 AsmLabelAttr *Attr =
21439 AsmLabelAttr::CreateImplicit(Ctx&: Context, Label: AliasName->getName(), CommonInfo: Info);
21440
21441 // If a declaration that:
21442 // 1) declares a function or a variable
21443 // 2) has external linkage
21444 // already exists, add a label attribute to it.
21445 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21446 if (isDeclExternC(D: PrevDecl))
21447 PrevDecl->addAttr(A: Attr);
21448 else
21449 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
21450 << /*Variable*/(isa<FunctionDecl>(Val: PrevDecl) ? 0 : 1) << PrevDecl;
21451 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
21452 } else
21453 (void)ExtnameUndeclaredIdentifiers.insert(KV: std::make_pair(x&: Name, y&: Attr));
21454}
21455
21456void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
21457 SourceLocation PragmaLoc,
21458 SourceLocation NameLoc) {
21459 NamedDecl *PrevDecl =
21460 LookupSingleName(S: TUScope, Name, Loc: NameLoc, NameKind: LookupOrdinaryName);
21461
21462 if (PrevDecl) {
21463 auto *Attr = WeakAttr::CreateImplicit(Ctx&: Context, Range: PragmaLoc);
21464 if (checkWeakAttrCompatibility(S&: *this, ND: *PrevDecl, Attr: *Attr))
21465 PrevDecl->addAttr(A: Attr);
21466 } else {
21467 (void)WeakUndeclaredIdentifiers[Name].insert(X: WeakInfo(nullptr, NameLoc));
21468 }
21469}
21470
21471void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
21472 IdentifierInfo* AliasName,
21473 SourceLocation PragmaLoc,
21474 SourceLocation NameLoc,
21475 SourceLocation AliasNameLoc) {
21476 Decl *PrevDecl = LookupSingleName(S: TUScope, Name: AliasName, Loc: AliasNameLoc,
21477 NameKind: LookupOrdinaryName);
21478 WeakInfo W = WeakInfo(Name, NameLoc);
21479
21480 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21481 if (!PrevDecl->hasAttr<AliasAttr>())
21482 if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: PrevDecl))
21483 DeclApplyPragmaWeak(S: TUScope, ND, W);
21484 } else {
21485 (void)WeakUndeclaredIdentifiers[AliasName].insert(X: W);
21486 }
21487}
21488
21489Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
21490 bool Final) {
21491 assert(FD && "Expected non-null FunctionDecl");
21492
21493 // Templates are emitted when they're instantiated.
21494 if (FD->isDependentContext())
21495 return FunctionEmissionStatus::TemplateDiscarded;
21496
21497 if (LangOpts.SYCLIsDevice && (FD->hasAttr<SYCLKernelAttr>() ||
21498 FD->hasAttr<SYCLKernelEntryPointAttr>() ||
21499 FD->hasAttr<SYCLExternalAttr>()))
21500 return FunctionEmissionStatus::Emitted;
21501
21502 // Check whether this function is an externally visible definition.
21503 auto IsEmittedForExternalSymbol = [this, FD]() {
21504 // We have to check the GVA linkage of the function's *definition* -- if we
21505 // only have a declaration, we don't know whether or not the function will
21506 // be emitted, because (say) the definition could include "inline".
21507 const FunctionDecl *Def = FD->getDefinition();
21508
21509 // We can't compute linkage when we skip function bodies.
21510 return Def && !Def->hasSkippedBody() &&
21511 !isDiscardableGVALinkage(
21512 L: getASTContext().GetGVALinkageForFunction(FD: Def));
21513 };
21514
21515 if (LangOpts.OpenMPIsTargetDevice) {
21516 // In OpenMP device mode we will not emit host only functions, or functions
21517 // we don't need due to their linkage.
21518 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21519 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21520 // DevTy may be changed later by
21521 // #pragma omp declare target to(*) device_type(*).
21522 // Therefore DevTy having no value does not imply host. The emission status
21523 // will be checked again at the end of compilation unit with Final = true.
21524 if (DevTy)
21525 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21526 return FunctionEmissionStatus::OMPDiscarded;
21527 // If we have an explicit value for the device type, or we are in a target
21528 // declare context, we need to emit all extern and used symbols.
21529 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21530 if (IsEmittedForExternalSymbol())
21531 return FunctionEmissionStatus::Emitted;
21532 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21533 // we'll omit it.
21534 if (Final)
21535 return FunctionEmissionStatus::OMPDiscarded;
21536 } else if (LangOpts.OpenMP > 45) {
21537 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21538 // function. In 5.0, no_host was introduced which might cause a function to
21539 // be omitted.
21540 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21541 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21542 if (DevTy)
21543 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21544 return FunctionEmissionStatus::OMPDiscarded;
21545 }
21546
21547 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21548 return FunctionEmissionStatus::Emitted;
21549
21550 if (LangOpts.CUDA) {
21551 // When compiling for device, host functions are never emitted. Similarly,
21552 // when compiling for host, device and global functions are never emitted.
21553 // (Technically, we do emit a host-side stub for global functions, but this
21554 // doesn't count for our purposes here.)
21555 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: FD);
21556 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21557 return FunctionEmissionStatus::CUDADiscarded;
21558 if (!LangOpts.CUDAIsDevice &&
21559 (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))
21560 return FunctionEmissionStatus::CUDADiscarded;
21561
21562 if (IsEmittedForExternalSymbol())
21563 return FunctionEmissionStatus::Emitted;
21564 }
21565
21566 // Otherwise, the function is known-emitted if it's in our set of
21567 // known-emitted functions.
21568 return FunctionEmissionStatus::Unknown;
21569}
21570
21571bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
21572 // Host-side references to a __global__ function refer to the stub, so the
21573 // function itself is never emitted and therefore should not be marked.
21574 // If we have host fn calls kernel fn calls host+device, the HD function
21575 // does not get instantiated on the host. We model this by omitting at the
21576 // call to the kernel from the callgraph. This ensures that, when compiling
21577 // for host, only HD functions actually called from the host get marked as
21578 // known-emitted.
21579 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21580 CUDA().IdentifyTarget(D: Callee) == CUDAFunctionTarget::Global;
21581}
21582
21583bool Sema::isRedefinitionAllowedFor(NamedDecl *D,
21584 SourceLocation NewDefinitionLoc,
21585 NamedDecl **Suggested, bool &Visible) {
21586 Visible = hasVisibleDefinition(D, Suggested);
21587 // Accoding to [basic.def.odr]p16, it is not allowed to have duplicated definition
21588 // for declaratins which is attached to named modules.
21589 // We only did this if the current module is named module as we have better
21590 // diagnostics for declarations in global module and named modules.
21591 if (getCurrentModule() && getCurrentModule()->isNamedModule() &&
21592 D->isInNamedModule())
21593 return false;
21594 // The redefinition of D in the **current** TU is allowed if D is invisible or
21595 // D is defined in the global module of other module units or D is defined in
21596 // the same header in a different module.
21597 return D->isInAnotherModuleUnit() || !Visible ||
21598 isFromSameSingleIncludeHeader(PrevD: D, NewLoc: NewDefinitionLoc);
21599}
21600