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/MangleNumberingContext.h"
27#include "clang/AST/NonTrivialTypeVisitor.h"
28#include "clang/AST/Randstruct.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/Type.h"
31#include "clang/Basic/Builtins.h"
32#include "clang/Basic/DiagnosticComment.h"
33#include "clang/Basic/PartialDiagnostic.h"
34#include "clang/Basic/SourceManager.h"
35#include "clang/Basic/TargetInfo.h"
36#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
37#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
38#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
40#include "clang/Sema/CXXFieldCollector.h"
41#include "clang/Sema/DeclSpec.h"
42#include "clang/Sema/DelayedDiagnostic.h"
43#include "clang/Sema/Initialization.h"
44#include "clang/Sema/Lookup.h"
45#include "clang/Sema/ParsedTemplate.h"
46#include "clang/Sema/Scope.h"
47#include "clang/Sema/ScopeInfo.h"
48#include "clang/Sema/SemaARM.h"
49#include "clang/Sema/SemaCUDA.h"
50#include "clang/Sema/SemaHLSL.h"
51#include "clang/Sema/SemaInternal.h"
52#include "clang/Sema/SemaObjC.h"
53#include "clang/Sema/SemaOpenACC.h"
54#include "clang/Sema/SemaOpenMP.h"
55#include "clang/Sema/SemaPPC.h"
56#include "clang/Sema/SemaRISCV.h"
57#include "clang/Sema/SemaSYCL.h"
58#include "clang/Sema/SemaSwift.h"
59#include "clang/Sema/SemaWasm.h"
60#include "clang/Sema/Template.h"
61#include "llvm/ADT/STLForwardCompat.h"
62#include "llvm/ADT/SmallPtrSet.h"
63#include "llvm/ADT/SmallString.h"
64#include "llvm/ADT/StringExtras.h"
65#include "llvm/Support/SaveAndRestore.h"
66#include "llvm/TargetParser/Triple.h"
67#include <algorithm>
68#include <cstring>
69#include <optional>
70#include <unordered_map>
71
72using namespace clang;
73using namespace sema;
74
75Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
76 if (OwnedType) {
77 Decl *Group[2] = { OwnedType, Ptr };
78 return DeclGroupPtrTy::make(P: DeclGroupRef::Create(C&: Context, Decls: Group, NumDecls: 2));
79 }
80
81 return DeclGroupPtrTy::make(P: DeclGroupRef(Ptr));
82}
83
84namespace {
85
86class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
87 public:
88 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
89 bool AllowTemplates = false,
90 bool AllowNonTemplates = true)
91 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
92 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
93 WantExpressionKeywords = false;
94 WantCXXNamedCasts = false;
95 WantRemainingKeywords = false;
96 }
97
98 bool ValidateCandidate(const TypoCorrection &candidate) override {
99 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
100 if (!AllowInvalidDecl && ND->isInvalidDecl())
101 return false;
102
103 if (getAsTypeTemplateDecl(D: ND))
104 return AllowTemplates;
105
106 bool IsType = isa<TypeDecl>(Val: ND) || isa<ObjCInterfaceDecl>(Val: ND);
107 if (!IsType)
108 return false;
109
110 if (AllowNonTemplates)
111 return true;
112
113 // An injected-class-name of a class template (specialization) is valid
114 // as a template or as a non-template.
115 if (AllowTemplates) {
116 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
117 if (!RD || !RD->isInjectedClassName())
118 return false;
119 RD = cast<CXXRecordDecl>(Val: RD->getDeclContext());
120 return RD->getDescribedClassTemplate() ||
121 isa<ClassTemplateSpecializationDecl>(Val: RD);
122 }
123
124 return false;
125 }
126
127 return !WantClassName && candidate.isKeyword();
128 }
129
130 std::unique_ptr<CorrectionCandidateCallback> clone() override {
131 return std::make_unique<TypeNameValidatorCCC>(args&: *this);
132 }
133
134 private:
135 bool AllowInvalidDecl;
136 bool WantClassName;
137 bool AllowTemplates;
138 bool AllowNonTemplates;
139};
140
141} // end anonymous namespace
142
143QualType Sema::getTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK,
144 TypeDecl *TD, SourceLocation NameLoc) {
145 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
146 auto *FoundRD = dyn_cast<CXXRecordDecl>(Val: TD);
147 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
148 FoundRD->isInjectedClassName() &&
149 declaresSameEntity(D1: LookupRD, D2: cast<Decl>(Val: FoundRD->getParent()))) {
150 Diag(Loc: NameLoc,
151 DiagID: DCK == DiagCtorKind::Typename
152 ? diag::ext_out_of_line_qualified_id_type_names_constructor
153 : diag::err_out_of_line_qualified_id_type_names_constructor)
154 << TD->getIdentifier() << /*Type=*/1
155 << 0 /*if any keyword was present, it was 'typename'*/;
156 }
157
158 DiagnoseUseOfDecl(D: TD, Locs: NameLoc);
159 MarkAnyDeclReferenced(Loc: TD->getLocation(), D: TD, /*OdrUse=*/MightBeOdrUse: false);
160 return Context.getTypeDeclType(Decl: TD);
161}
162
163namespace {
164enum class UnqualifiedTypeNameLookupResult {
165 NotFound,
166 FoundNonType,
167 FoundType
168};
169} // end anonymous namespace
170
171/// Tries to perform unqualified lookup of the type decls in bases for
172/// dependent class.
173/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
174/// type decl, \a FoundType if only type decls are found.
175static UnqualifiedTypeNameLookupResult
176lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
177 SourceLocation NameLoc,
178 const CXXRecordDecl *RD) {
179 if (!RD->hasDefinition())
180 return UnqualifiedTypeNameLookupResult::NotFound;
181 // Look for type decls in base classes.
182 UnqualifiedTypeNameLookupResult FoundTypeDecl =
183 UnqualifiedTypeNameLookupResult::NotFound;
184 for (const auto &Base : RD->bases()) {
185 const CXXRecordDecl *BaseRD = nullptr;
186 if (auto *BaseTT = Base.getType()->getAs<TagType>())
187 BaseRD = BaseTT->getAsCXXRecordDecl();
188 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
189 // Look for type decls in dependent base classes that have known primary
190 // templates.
191 if (!TST || !TST->isDependentType())
192 continue;
193 auto *TD = TST->getTemplateName().getAsTemplateDecl();
194 if (!TD)
195 continue;
196 if (auto *BasePrimaryTemplate =
197 dyn_cast_or_null<CXXRecordDecl>(Val: TD->getTemplatedDecl())) {
198 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
199 BaseRD = BasePrimaryTemplate;
200 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: TD)) {
201 if (const ClassTemplatePartialSpecializationDecl *PS =
202 CTD->findPartialSpecialization(T: Base.getType()))
203 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
204 BaseRD = PS;
205 }
206 }
207 }
208 if (BaseRD) {
209 for (NamedDecl *ND : BaseRD->lookup(Name: &II)) {
210 if (!isa<TypeDecl>(Val: ND))
211 return UnqualifiedTypeNameLookupResult::FoundNonType;
212 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
213 }
214 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
215 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD: BaseRD)) {
216 case UnqualifiedTypeNameLookupResult::FoundNonType:
217 return UnqualifiedTypeNameLookupResult::FoundNonType;
218 case UnqualifiedTypeNameLookupResult::FoundType:
219 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
220 break;
221 case UnqualifiedTypeNameLookupResult::NotFound:
222 break;
223 }
224 }
225 }
226 }
227
228 return FoundTypeDecl;
229}
230
231static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
232 const IdentifierInfo &II,
233 SourceLocation NameLoc) {
234 // Lookup in the parent class template context, if any.
235 const CXXRecordDecl *RD = nullptr;
236 UnqualifiedTypeNameLookupResult FoundTypeDecl =
237 UnqualifiedTypeNameLookupResult::NotFound;
238 for (DeclContext *DC = S.CurContext;
239 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
240 DC = DC->getParent()) {
241 // Look for type decls in dependent base classes that have known primary
242 // templates.
243 RD = dyn_cast<CXXRecordDecl>(Val: DC);
244 if (RD && RD->getDescribedClassTemplate())
245 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
246 }
247 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
248 return nullptr;
249
250 // We found some types in dependent base classes. Recover as if the user
251 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
252 // allowed. We'll fully resolve the lookup during template instantiation.
253 S.Diag(Loc: NameLoc, DiagID: diag::ext_found_in_dependent_base) << &II;
254
255 ASTContext &Context = S.Context;
256 auto *NNS = NestedNameSpecifier::Create(
257 Context, Prefix: nullptr, T: cast<Type>(Val: Context.getRecordType(Decl: RD)));
258 QualType T =
259 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
260
261 CXXScopeSpec SS;
262 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
263
264 TypeLocBuilder Builder;
265 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
266 DepTL.setNameLoc(NameLoc);
267 DepTL.setElaboratedKeywordLoc(SourceLocation());
268 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
269 return S.CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
270}
271
272/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
273static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T,
274 SourceLocation NameLoc,
275 bool WantNontrivialTypeSourceInfo = true) {
276 switch (T->getTypeClass()) {
277 case Type::DeducedTemplateSpecialization:
278 case Type::Enum:
279 case Type::InjectedClassName:
280 case Type::Record:
281 case Type::Typedef:
282 case Type::UnresolvedUsing:
283 case Type::Using:
284 break;
285 // These can never be qualified so an ElaboratedType node
286 // would carry no additional meaning.
287 case Type::ObjCInterface:
288 case Type::ObjCTypeParam:
289 case Type::TemplateTypeParm:
290 return ParsedType::make(P: T);
291 default:
292 llvm_unreachable("Unexpected Type Class");
293 }
294
295 if (!SS || SS->isEmpty())
296 return ParsedType::make(P: S.Context.getElaboratedType(
297 Keyword: ElaboratedTypeKeyword::None, NNS: nullptr, NamedType: T, OwnedTagDecl: nullptr));
298
299 QualType ElTy = S.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, SS: *SS, T);
300 if (!WantNontrivialTypeSourceInfo)
301 return ParsedType::make(P: ElTy);
302
303 TypeLocBuilder Builder;
304 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
305 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T: ElTy);
306 ElabTL.setElaboratedKeywordLoc(SourceLocation());
307 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context&: S.Context));
308 return S.CreateParsedType(T: ElTy, TInfo: Builder.getTypeSourceInfo(Context&: S.Context, T: ElTy));
309}
310
311ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
312 Scope *S, CXXScopeSpec *SS, bool isClassName,
313 bool HasTrailingDot, ParsedType ObjectTypePtr,
314 bool IsCtorOrDtorName,
315 bool WantNontrivialTypeSourceInfo,
316 bool IsClassTemplateDeductionContext,
317 ImplicitTypenameContext AllowImplicitTypename,
318 IdentifierInfo **CorrectedII) {
319 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
320 // FIXME: Consider allowing this outside C++1z mode as an extension.
321 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
322 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
323 !HasTrailingDot;
324
325 // Determine where we will perform name lookup.
326 DeclContext *LookupCtx = nullptr;
327 if (ObjectTypePtr) {
328 QualType ObjectType = ObjectTypePtr.get();
329 if (ObjectType->isRecordType())
330 LookupCtx = computeDeclContext(T: ObjectType);
331 } else if (SS && SS->isNotEmpty()) {
332 LookupCtx = computeDeclContext(SS: *SS, EnteringContext: false);
333
334 if (!LookupCtx) {
335 if (isDependentScopeSpecifier(SS: *SS)) {
336 // C++ [temp.res]p3:
337 // A qualified-id that refers to a type and in which the
338 // nested-name-specifier depends on a template-parameter (14.6.2)
339 // shall be prefixed by the keyword typename to indicate that the
340 // qualified-id denotes a type, forming an
341 // elaborated-type-specifier (7.1.5.3).
342 //
343 // We therefore do not perform any name lookup if the result would
344 // refer to a member of an unknown specialization.
345 // In C++2a, in several contexts a 'typename' is not required. Also
346 // allow this as an extension.
347 if (IsImplicitTypename) {
348 if (AllowImplicitTypename == ImplicitTypenameContext::No)
349 return nullptr;
350 SourceLocation QualifiedLoc = SS->getRange().getBegin();
351 auto DB =
352 DiagCompat(Loc: QualifiedLoc, CompatDiagId: diag_compat::implicit_typename)
353 << NestedNameSpecifier::Create(Context, Prefix: SS->getScopeRep(), II: &II);
354 if (!getLangOpts().CPlusPlus20)
355 DB << FixItHint::CreateInsertion(InsertionLoc: QualifiedLoc, Code: "typename ");
356 }
357
358 // We know from the grammar that this name refers to a type,
359 // so build a dependent node to describe the type.
360 if (WantNontrivialTypeSourceInfo)
361 return ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II, IdLoc: NameLoc,
362 IsImplicitTypename: (ImplicitTypenameContext)IsImplicitTypename)
363 .get();
364
365 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
366 QualType T = CheckTypenameType(
367 Keyword: IsImplicitTypename ? ElaboratedTypeKeyword::Typename
368 : ElaboratedTypeKeyword::None,
369 KeywordLoc: SourceLocation(), QualifierLoc, II, IILoc: NameLoc);
370 return ParsedType::make(P: T);
371 }
372
373 return nullptr;
374 }
375
376 if (!LookupCtx->isDependentContext() &&
377 RequireCompleteDeclContext(SS&: *SS, DC: LookupCtx))
378 return nullptr;
379 }
380
381 // In the case where we know that the identifier is a class name, we know that
382 // it is a type declaration (struct, class, union or enum) so we can use tag
383 // name lookup.
384 //
385 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
386 // the component name of the type-name or simple-template-id is type-only.
387 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
388 LookupResult Result(*this, &II, NameLoc, Kind);
389 if (LookupCtx) {
390 // Perform "qualified" name lookup into the declaration context we
391 // computed, which is either the type of the base of a member access
392 // expression or the declaration context associated with a prior
393 // nested-name-specifier.
394 LookupQualifiedName(R&: Result, LookupCtx);
395
396 if (ObjectTypePtr && Result.empty()) {
397 // C++ [basic.lookup.classref]p3:
398 // If the unqualified-id is ~type-name, the type-name is looked up
399 // in the context of the entire postfix-expression. If the type T of
400 // the object expression is of a class type C, the type-name is also
401 // looked up in the scope of class C. At least one of the lookups shall
402 // find a name that refers to (possibly cv-qualified) T.
403 LookupName(R&: Result, S);
404 }
405 } else {
406 // Perform unqualified name lookup.
407 LookupName(R&: Result, S);
408
409 // For unqualified lookup in a class template in MSVC mode, look into
410 // dependent base classes where the primary class template is known.
411 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
412 if (ParsedType TypeInBase =
413 recoverFromTypeInKnownDependentBase(S&: *this, II, NameLoc))
414 return TypeInBase;
415 }
416 }
417
418 NamedDecl *IIDecl = nullptr;
419 UsingShadowDecl *FoundUsingShadow = nullptr;
420 switch (Result.getResultKind()) {
421 case LookupResultKind::NotFound:
422 if (CorrectedII) {
423 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
424 AllowDeducedTemplate);
425 TypoCorrection Correction =
426 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Kind, S, SS, CCC,
427 Mode: CorrectTypoKind::ErrorRecovery);
428 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
429 TemplateTy Template;
430 bool MemberOfUnknownSpecialization;
431 UnqualifiedId TemplateName;
432 TemplateName.setIdentifier(Id: NewII, IdLoc: NameLoc);
433 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
434 CXXScopeSpec NewSS, *NewSSPtr = SS;
435 if (SS && NNS) {
436 NewSS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
437 NewSSPtr = &NewSS;
438 }
439 if (Correction && (NNS || NewII != &II) &&
440 // Ignore a correction to a template type as the to-be-corrected
441 // identifier is not a template (typo correction for template names
442 // is handled elsewhere).
443 !(getLangOpts().CPlusPlus && NewSSPtr &&
444 isTemplateName(S, SS&: *NewSSPtr, hasTemplateKeyword: false, Name: TemplateName, ObjectType: nullptr, EnteringContext: false,
445 Template, MemberOfUnknownSpecialization))) {
446 ParsedType Ty = getTypeName(II: *NewII, NameLoc, S, SS: NewSSPtr,
447 isClassName, HasTrailingDot, ObjectTypePtr,
448 IsCtorOrDtorName,
449 WantNontrivialTypeSourceInfo,
450 IsClassTemplateDeductionContext);
451 if (Ty) {
452 diagnoseTypo(Correction,
453 TypoDiag: PDiag(DiagID: diag::err_unknown_type_or_class_name_suggest)
454 << Result.getLookupName() << isClassName);
455 if (SS && NNS)
456 SS->MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
457 *CorrectedII = NewII;
458 return Ty;
459 }
460 }
461 }
462 Result.suppressDiagnostics();
463 return nullptr;
464 case LookupResultKind::NotFoundInCurrentInstantiation:
465 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
466 QualType T = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
467 NNS: SS->getScopeRep(), Name: &II);
468 TypeLocBuilder TLB;
469 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T);
470 TL.setElaboratedKeywordLoc(SourceLocation());
471 TL.setQualifierLoc(SS->getWithLocInContext(Context));
472 TL.setNameLoc(NameLoc);
473 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
474 }
475 [[fallthrough]];
476 case LookupResultKind::FoundOverloaded:
477 case LookupResultKind::FoundUnresolvedValue:
478 Result.suppressDiagnostics();
479 return nullptr;
480
481 case LookupResultKind::Ambiguous:
482 // Recover from type-hiding ambiguities by hiding the type. We'll
483 // do the lookup again when looking for an object, and we can
484 // diagnose the error then. If we don't do this, then the error
485 // about hiding the type will be immediately followed by an error
486 // that only makes sense if the identifier was treated like a type.
487 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
488 Result.suppressDiagnostics();
489 return nullptr;
490 }
491
492 // Look to see if we have a type anywhere in the list of results.
493 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
494 Res != ResEnd; ++Res) {
495 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
496 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
497 Val: RealRes) ||
498 (AllowDeducedTemplate && getAsTypeTemplateDecl(D: RealRes))) {
499 if (!IIDecl ||
500 // Make the selection of the recovery decl deterministic.
501 RealRes->getLocation() < IIDecl->getLocation()) {
502 IIDecl = RealRes;
503 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Res);
504 }
505 }
506 }
507
508 if (!IIDecl) {
509 // None of the entities we found is a type, so there is no way
510 // to even assume that the result is a type. In this case, don't
511 // complain about the ambiguity. The parser will either try to
512 // perform this lookup again (e.g., as an object name), which
513 // will produce the ambiguity, or will complain that it expected
514 // a type name.
515 Result.suppressDiagnostics();
516 return nullptr;
517 }
518
519 // We found a type within the ambiguous lookup; diagnose the
520 // ambiguity and then return that type. This might be the right
521 // answer, or it might not be, but it suppresses any attempt to
522 // perform the name lookup again.
523 break;
524
525 case LookupResultKind::Found:
526 IIDecl = Result.getFoundDecl();
527 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Result.begin());
528 break;
529 }
530
531 assert(IIDecl && "Didn't find decl");
532
533 QualType T;
534 if (TypeDecl *TD = dyn_cast<TypeDecl>(Val: IIDecl)) {
535 // C++ [class.qual]p2: A lookup that would find the injected-class-name
536 // instead names the constructors of the class, except when naming a class.
537 // This is ill-formed when we're not actually forming a ctor or dtor name.
538 T = getTypeDeclType(LookupCtx,
539 DCK: IsImplicitTypename ? DiagCtorKind::Implicit
540 : DiagCtorKind::None,
541 TD, NameLoc);
542 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(Val: IIDecl)) {
543 (void)DiagnoseUseOfDecl(D: IDecl, Locs: NameLoc);
544 if (!HasTrailingDot)
545 T = Context.getObjCInterfaceType(Decl: IDecl);
546 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
547 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: IIDecl)) {
548 (void)DiagnoseUseOfDecl(D: UD, Locs: NameLoc);
549 // Recover with 'int'
550 return ParsedType::make(P: Context.IntTy);
551 } else if (AllowDeducedTemplate) {
552 if (auto *TD = getAsTypeTemplateDecl(D: IIDecl)) {
553 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
554 TemplateName Template = Context.getQualifiedTemplateName(
555 NNS: SS ? SS->getScopeRep() : nullptr, /*TemplateKeyword=*/false,
556 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
557 T = Context.getDeducedTemplateSpecializationType(Template, DeducedType: QualType(),
558 IsDependent: false);
559 // Don't wrap in a further UsingType.
560 FoundUsingShadow = nullptr;
561 }
562 }
563
564 if (T.isNull()) {
565 // If it's not plausibly a type, suppress diagnostics.
566 Result.suppressDiagnostics();
567 return nullptr;
568 }
569
570 if (FoundUsingShadow)
571 T = Context.getUsingType(Found: FoundUsingShadow, Underlying: T);
572
573 return buildNamedType(S&: *this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
574}
575
576// Builds a fake NNS for the given decl context.
577static NestedNameSpecifier *
578synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
579 for (;; DC = DC->getLookupParent()) {
580 DC = DC->getPrimaryContext();
581 auto *ND = dyn_cast<NamespaceDecl>(Val: DC);
582 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
583 return NestedNameSpecifier::Create(Context, Prefix: nullptr, NS: ND);
584 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
585 return NestedNameSpecifier::Create(Context, Prefix: nullptr,
586 T: RD->getTypeForDecl());
587 if (isa<TranslationUnitDecl>(Val: DC))
588 return NestedNameSpecifier::GlobalSpecifier(Context);
589 }
590 llvm_unreachable("something isn't in TU scope?");
591}
592
593/// Find the parent class with dependent bases of the innermost enclosing method
594/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
595/// up allowing unqualified dependent type names at class-level, which MSVC
596/// correctly rejects.
597static const CXXRecordDecl *
598findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
599 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
600 DC = DC->getPrimaryContext();
601 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
602 if (MD->getParent()->hasAnyDependentBases())
603 return MD->getParent();
604 }
605 return nullptr;
606}
607
608ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
609 SourceLocation NameLoc,
610 bool IsTemplateTypeArg) {
611 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
612
613 NestedNameSpecifier *NNS = nullptr;
614 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
615 // If we weren't able to parse a default template argument, delay lookup
616 // until instantiation time by making a non-dependent DependentTypeName. We
617 // pretend we saw a NestedNameSpecifier referring to the current scope, and
618 // lookup is retried.
619 // FIXME: This hurts our diagnostic quality, since we get errors like "no
620 // type named 'Foo' in 'current_namespace'" when the user didn't write any
621 // name specifiers.
622 NNS = synthesizeCurrentNestedNameSpecifier(Context, DC: CurContext);
623 Diag(Loc: NameLoc, DiagID: diag::ext_ms_delayed_template_argument) << &II;
624 } else if (const CXXRecordDecl *RD =
625 findRecordWithDependentBasesOfEnclosingMethod(DC: CurContext)) {
626 // Build a DependentNameType that will perform lookup into RD at
627 // instantiation time.
628 NNS = NestedNameSpecifier::Create(Context, Prefix: nullptr, T: RD->getTypeForDecl());
629
630 // Diagnose that this identifier was undeclared, and retry the lookup during
631 // template instantiation.
632 Diag(Loc: NameLoc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base) << &II
633 << RD;
634 } else {
635 // This is not a situation that we should recover from.
636 return ParsedType();
637 }
638
639 QualType T =
640 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
641
642 // Build type location information. We synthesized the qualifier, so we have
643 // to build a fake NestedNameSpecifierLoc.
644 NestedNameSpecifierLocBuilder NNSLocBuilder;
645 NNSLocBuilder.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
646 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
647
648 TypeLocBuilder Builder;
649 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
650 DepTL.setNameLoc(NameLoc);
651 DepTL.setElaboratedKeywordLoc(SourceLocation());
652 DepTL.setQualifierLoc(QualifierLoc);
653 return CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
654}
655
656DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
657 // Do a tag name lookup in this scope.
658 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
659 LookupName(R, S, AllowBuiltinCreation: false);
660 R.suppressDiagnostics();
661 if (R.getResultKind() == LookupResultKind::Found)
662 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
663 switch (TD->getTagKind()) {
664 case TagTypeKind::Struct:
665 return DeclSpec::TST_struct;
666 case TagTypeKind::Interface:
667 return DeclSpec::TST_interface;
668 case TagTypeKind::Union:
669 return DeclSpec::TST_union;
670 case TagTypeKind::Class:
671 return DeclSpec::TST_class;
672 case TagTypeKind::Enum:
673 return DeclSpec::TST_enum;
674 }
675 }
676
677 return DeclSpec::TST_unspecified;
678}
679
680bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
681 if (CurContext->isRecord()) {
682 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
683 return true;
684
685 const Type *Ty = SS->getScopeRep()->getAsType();
686
687 CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: CurContext);
688 for (const auto &Base : RD->bases())
689 if (Ty && Context.hasSameUnqualifiedType(T1: QualType(Ty, 1), T2: Base.getType()))
690 return true;
691 return S->isFunctionPrototypeScope();
692 }
693 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
694}
695
696void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
697 SourceLocation IILoc,
698 Scope *S,
699 CXXScopeSpec *SS,
700 ParsedType &SuggestedType,
701 bool IsTemplateName) {
702 // Don't report typename errors for editor placeholders.
703 if (II->isEditorPlaceholder())
704 return;
705 // We don't have anything to suggest (yet).
706 SuggestedType = nullptr;
707
708 // There may have been a typo in the name of the type. Look up typo
709 // results, in case we have something that we can suggest.
710 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
711 /*AllowTemplates=*/IsTemplateName,
712 /*AllowNonTemplates=*/!IsTemplateName);
713 if (TypoCorrection Corrected =
714 CorrectTypo(Typo: DeclarationNameInfo(II, IILoc), LookupKind: LookupOrdinaryName, S, SS,
715 CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
716 // FIXME: Support error recovery for the template-name case.
717 bool CanRecover = !IsTemplateName;
718 if (Corrected.isKeyword()) {
719 // We corrected to a keyword.
720 diagnoseTypo(Correction: Corrected,
721 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
722 : diag::err_unknown_typename_suggest)
723 << II);
724 II = Corrected.getCorrectionAsIdentifierInfo();
725 } else {
726 // We found a similarly-named type or interface; suggest that.
727 if (!SS || !SS->isSet()) {
728 diagnoseTypo(Correction: Corrected,
729 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
730 : diag::err_unknown_typename_suggest)
731 << II, ErrorRecovery: CanRecover);
732 } else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false)) {
733 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
734 bool DroppedSpecifier =
735 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
736 diagnoseTypo(Correction: Corrected,
737 TypoDiag: PDiag(DiagID: IsTemplateName
738 ? diag::err_no_member_template_suggest
739 : diag::err_unknown_nested_typename_suggest)
740 << II << DC << DroppedSpecifier << SS->getRange(),
741 ErrorRecovery: CanRecover);
742 } else {
743 llvm_unreachable("could not have corrected a typo here");
744 }
745
746 if (!CanRecover)
747 return;
748
749 CXXScopeSpec tmpSS;
750 if (Corrected.getCorrectionSpecifier())
751 tmpSS.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
752 R: SourceRange(IILoc));
753 // FIXME: Support class template argument deduction here.
754 SuggestedType =
755 getTypeName(II: *Corrected.getCorrectionAsIdentifierInfo(), NameLoc: IILoc, S,
756 SS: tmpSS.isSet() ? &tmpSS : SS, isClassName: false, HasTrailingDot: false, ObjectTypePtr: nullptr,
757 /*IsCtorOrDtorName=*/false,
758 /*WantNontrivialTypeSourceInfo=*/true);
759 }
760 return;
761 }
762
763 if (getLangOpts().CPlusPlus && !IsTemplateName) {
764 // See if II is a class template that the user forgot to pass arguments to.
765 UnqualifiedId Name;
766 Name.setIdentifier(Id: II, IdLoc: IILoc);
767 CXXScopeSpec EmptySS;
768 TemplateTy TemplateResult;
769 bool MemberOfUnknownSpecialization;
770 if (isTemplateName(S, SS&: SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
771 Name, ObjectType: nullptr, EnteringContext: true, Template&: TemplateResult,
772 MemberOfUnknownSpecialization) == TNK_Type_template) {
773 diagnoseMissingTemplateArguments(Name: TemplateResult.get(), Loc: IILoc);
774 return;
775 }
776 }
777
778 // FIXME: Should we move the logic that tries to recover from a missing tag
779 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
780
781 if (!SS || (!SS->isSet() && !SS->isInvalid()))
782 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_template
783 : diag::err_unknown_typename)
784 << II;
785 else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false))
786 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_member_template
787 : diag::err_typename_nested_not_found)
788 << II << DC << SS->getRange();
789 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
790 SuggestedType =
791 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
792 } else if (isDependentScopeSpecifier(SS: *SS)) {
793 unsigned DiagID = diag::err_typename_missing;
794 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
795 DiagID = diag::ext_typename_missing;
796
797 Diag(Loc: SS->getRange().getBegin(), DiagID)
798 << NestedNameSpecifier::Create(Context, Prefix: SS->getScopeRep(), II)
799 << SourceRange(SS->getRange().getBegin(), IILoc)
800 << FixItHint::CreateInsertion(InsertionLoc: SS->getRange().getBegin(), Code: "typename ");
801 SuggestedType = ActOnTypenameType(S, TypenameLoc: SourceLocation(),
802 SS: *SS, II: *II, IdLoc: IILoc).get();
803 } else {
804 assert(SS && SS->isInvalid() &&
805 "Invalid scope specifier has already been diagnosed");
806 }
807}
808
809/// Determine whether the given result set contains either a type name
810/// or
811static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
812 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
813 NextToken.is(K: tok::less);
814
815 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
816 if (isa<TypeDecl>(Val: *I) || isa<ObjCInterfaceDecl>(Val: *I))
817 return true;
818
819 if (CheckTemplate && isa<TemplateDecl>(Val: *I))
820 return true;
821 }
822
823 return false;
824}
825
826static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
827 Scope *S, CXXScopeSpec &SS,
828 IdentifierInfo *&Name,
829 SourceLocation NameLoc) {
830 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
831 SemaRef.LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
832 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
833 StringRef FixItTagName;
834 switch (Tag->getTagKind()) {
835 case TagTypeKind::Class:
836 FixItTagName = "class ";
837 break;
838
839 case TagTypeKind::Enum:
840 FixItTagName = "enum ";
841 break;
842
843 case TagTypeKind::Struct:
844 FixItTagName = "struct ";
845 break;
846
847 case TagTypeKind::Interface:
848 FixItTagName = "__interface ";
849 break;
850
851 case TagTypeKind::Union:
852 FixItTagName = "union ";
853 break;
854 }
855
856 StringRef TagName = FixItTagName.drop_back();
857 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_use_of_tag_name_without_tag)
858 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
859 << FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: FixItTagName);
860
861 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
862 I != IEnd; ++I)
863 SemaRef.Diag(Loc: (*I)->getLocation(), DiagID: diag::note_decl_hiding_tag_type)
864 << Name << TagName;
865
866 // Replace lookup results with just the tag decl.
867 Result.clear(Kind: Sema::LookupTagName);
868 SemaRef.LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType());
869 return true;
870 }
871
872 return false;
873}
874
875Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
876 IdentifierInfo *&Name,
877 SourceLocation NameLoc,
878 const Token &NextToken,
879 CorrectionCandidateCallback *CCC) {
880 DeclarationNameInfo NameInfo(Name, NameLoc);
881 ObjCMethodDecl *CurMethod = getCurMethodDecl();
882
883 assert(NextToken.isNot(tok::coloncolon) &&
884 "parse nested name specifiers before calling ClassifyName");
885 if (getLangOpts().CPlusPlus && SS.isSet() &&
886 isCurrentClassName(II: *Name, S, SS: &SS)) {
887 // Per [class.qual]p2, this names the constructors of SS, not the
888 // injected-class-name. We don't have a classification for that.
889 // There's not much point caching this result, since the parser
890 // will reject it later.
891 return NameClassification::Unknown();
892 }
893
894 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
895 LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType(),
896 /*AllowBuiltinCreation=*/!CurMethod);
897
898 if (SS.isInvalid())
899 return NameClassification::Error();
900
901 // For unqualified lookup in a class template in MSVC mode, look into
902 // dependent base classes where the primary class template is known.
903 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
904 if (ParsedType TypeInBase =
905 recoverFromTypeInKnownDependentBase(S&: *this, II: *Name, NameLoc))
906 return TypeInBase;
907 }
908
909 // Perform lookup for Objective-C instance variables (including automatically
910 // synthesized instance variables), if we're in an Objective-C method.
911 // FIXME: This lookup really, really needs to be folded in to the normal
912 // unqualified lookup mechanism.
913 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(R&: Result, NextToken)) {
914 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Name);
915 if (Ivar.isInvalid())
916 return NameClassification::Error();
917 if (Ivar.isUsable())
918 return NameClassification::NonType(D: cast<NamedDecl>(Val: Ivar.get()));
919
920 // We defer builtin creation until after ivar lookup inside ObjC methods.
921 if (Result.empty())
922 LookupBuiltin(R&: Result);
923 }
924
925 bool SecondTry = false;
926 bool IsFilteredTemplateName = false;
927
928Corrected:
929 switch (Result.getResultKind()) {
930 case LookupResultKind::NotFound:
931 // If an unqualified-id is followed by a '(', then we have a function
932 // call.
933 if (SS.isEmpty() && NextToken.is(K: tok::l_paren)) {
934 // In C++, this is an ADL-only call.
935 // FIXME: Reference?
936 if (getLangOpts().CPlusPlus)
937 return NameClassification::UndeclaredNonType();
938
939 // C90 6.3.2.2:
940 // If the expression that precedes the parenthesized argument list in a
941 // function call consists solely of an identifier, and if no
942 // declaration is visible for this identifier, the identifier is
943 // implicitly declared exactly as if, in the innermost block containing
944 // the function call, the declaration
945 //
946 // extern int identifier ();
947 //
948 // appeared.
949 //
950 // We also allow this in C99 as an extension. However, this is not
951 // allowed in all language modes as functions without prototypes may not
952 // be supported.
953 if (getLangOpts().implicitFunctionsAllowed()) {
954 if (NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *Name, S))
955 return NameClassification::NonType(D);
956 }
957 }
958
959 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(K: tok::less)) {
960 // In C++20 onwards, this could be an ADL-only call to a function
961 // template, and we're required to assume that this is a template name.
962 //
963 // FIXME: Find a way to still do typo correction in this case.
964 TemplateName Template =
965 Context.getAssumedTemplateName(Name: NameInfo.getName());
966 return NameClassification::UndeclaredTemplate(Name: Template);
967 }
968
969 // In C, we first see whether there is a tag type by the same name, in
970 // which case it's likely that the user just forgot to write "enum",
971 // "struct", or "union".
972 if (!getLangOpts().CPlusPlus && !SecondTry &&
973 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
974 break;
975 }
976
977 // Perform typo correction to determine if there is another name that is
978 // close to this name.
979 if (!SecondTry && CCC) {
980 SecondTry = true;
981 if (TypoCorrection Corrected =
982 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Result.getLookupKind(), S,
983 SS: &SS, CCC&: *CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
984 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
985 unsigned QualifiedDiag = diag::err_no_member_suggest;
986
987 NamedDecl *FirstDecl = Corrected.getFoundDecl();
988 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
989 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
990 UnderlyingFirstDecl && isa<TemplateDecl>(Val: UnderlyingFirstDecl)) {
991 UnqualifiedDiag = diag::err_no_template_suggest;
992 QualifiedDiag = diag::err_no_member_template_suggest;
993 } else if (UnderlyingFirstDecl &&
994 (isa<TypeDecl>(Val: UnderlyingFirstDecl) ||
995 isa<ObjCInterfaceDecl>(Val: UnderlyingFirstDecl) ||
996 isa<ObjCCompatibleAliasDecl>(Val: UnderlyingFirstDecl))) {
997 UnqualifiedDiag = diag::err_unknown_typename_suggest;
998 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
999 }
1000
1001 if (SS.isEmpty()) {
1002 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: UnqualifiedDiag) << Name);
1003 } else {// FIXME: is this even reachable? Test it.
1004 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
1005 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1006 Name->getName() == CorrectedStr;
1007 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: QualifiedDiag)
1008 << Name << computeDeclContext(SS, EnteringContext: false)
1009 << DroppedSpecifier << SS.getRange());
1010 }
1011
1012 // Update the name, so that the caller has the new name.
1013 Name = Corrected.getCorrectionAsIdentifierInfo();
1014
1015 // Typo correction corrected to a keyword.
1016 if (Corrected.isKeyword())
1017 return Name;
1018
1019 // Also update the LookupResult...
1020 // FIXME: This should probably go away at some point
1021 Result.clear();
1022 Result.setLookupName(Corrected.getCorrection());
1023 if (FirstDecl)
1024 Result.addDecl(D: FirstDecl);
1025
1026 // If we found an Objective-C instance variable, let
1027 // LookupInObjCMethod build the appropriate expression to
1028 // reference the ivar.
1029 // FIXME: This is a gross hack.
1030 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1031 DeclResult R =
1032 ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Ivar->getIdentifier());
1033 if (R.isInvalid())
1034 return NameClassification::Error();
1035 if (R.isUsable())
1036 return NameClassification::NonType(D: Ivar);
1037 }
1038
1039 goto Corrected;
1040 }
1041 }
1042
1043 // We failed to correct; just fall through and let the parser deal with it.
1044 Result.suppressDiagnostics();
1045 return NameClassification::Unknown();
1046
1047 case LookupResultKind::NotFoundInCurrentInstantiation: {
1048 // We performed name lookup into the current instantiation, and there were
1049 // dependent bases, so we treat this result the same way as any other
1050 // dependent nested-name-specifier.
1051
1052 // C++ [temp.res]p2:
1053 // A name used in a template declaration or definition and that is
1054 // dependent on a template-parameter is assumed not to name a type
1055 // unless the applicable name lookup finds a type name or the name is
1056 // qualified by the keyword typename.
1057 //
1058 // FIXME: If the next token is '<', we might want to ask the parser to
1059 // perform some heroics to see if we actually have a
1060 // template-argument-list, which would indicate a missing 'template'
1061 // keyword here.
1062 return NameClassification::DependentNonType();
1063 }
1064
1065 case LookupResultKind::Found:
1066 case LookupResultKind::FoundOverloaded:
1067 case LookupResultKind::FoundUnresolvedValue:
1068 break;
1069
1070 case LookupResultKind::Ambiguous:
1071 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1072 hasAnyAcceptableTemplateNames(R&: Result, /*AllowFunctionTemplates=*/true,
1073 /*AllowDependent=*/false)) {
1074 // C++ [temp.local]p3:
1075 // A lookup that finds an injected-class-name (10.2) can result in an
1076 // ambiguity in certain cases (for example, if it is found in more than
1077 // one base class). If all of the injected-class-names that are found
1078 // refer to specializations of the same class template, and if the name
1079 // is followed by a template-argument-list, the reference refers to the
1080 // class template itself and not a specialization thereof, and is not
1081 // ambiguous.
1082 //
1083 // This filtering can make an ambiguous result into an unambiguous one,
1084 // so try again after filtering out template names.
1085 FilterAcceptableTemplateNames(R&: Result);
1086 if (!Result.isAmbiguous()) {
1087 IsFilteredTemplateName = true;
1088 break;
1089 }
1090 }
1091
1092 // Diagnose the ambiguity and return an error.
1093 return NameClassification::Error();
1094 }
1095
1096 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1097 (IsFilteredTemplateName ||
1098 hasAnyAcceptableTemplateNames(
1099 R&: Result, /*AllowFunctionTemplates=*/true,
1100 /*AllowDependent=*/false,
1101 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1102 getLangOpts().CPlusPlus20))) {
1103 // C++ [temp.names]p3:
1104 // After name lookup (3.4) finds that a name is a template-name or that
1105 // an operator-function-id or a literal- operator-id refers to a set of
1106 // overloaded functions any member of which is a function template if
1107 // this is followed by a <, the < is always taken as the delimiter of a
1108 // template-argument-list and never as the less-than operator.
1109 // C++2a [temp.names]p2:
1110 // A name is also considered to refer to a template if it is an
1111 // unqualified-id followed by a < and name lookup finds either one
1112 // or more functions or finds nothing.
1113 if (!IsFilteredTemplateName)
1114 FilterAcceptableTemplateNames(R&: Result);
1115
1116 bool IsFunctionTemplate;
1117 bool IsVarTemplate;
1118 TemplateName Template;
1119 if (Result.end() - Result.begin() > 1) {
1120 IsFunctionTemplate = true;
1121 Template = Context.getOverloadedTemplateName(Begin: Result.begin(),
1122 End: Result.end());
1123 } else if (!Result.empty()) {
1124 auto *TD = cast<TemplateDecl>(Val: getAsTemplateNameDecl(
1125 D: *Result.begin(), /*AllowFunctionTemplates=*/true,
1126 /*AllowDependent=*/false));
1127 IsFunctionTemplate = isa<FunctionTemplateDecl>(Val: TD);
1128 IsVarTemplate = isa<VarTemplateDecl>(Val: TD);
1129
1130 UsingShadowDecl *FoundUsingShadow =
1131 dyn_cast<UsingShadowDecl>(Val: *Result.begin());
1132 assert(!FoundUsingShadow ||
1133 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1134 Template = Context.getQualifiedTemplateName(
1135 NNS: SS.getScopeRep(),
1136 /*TemplateKeyword=*/false,
1137 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1138 } else {
1139 // All results were non-template functions. This is a function template
1140 // name.
1141 IsFunctionTemplate = true;
1142 Template = Context.getAssumedTemplateName(Name: NameInfo.getName());
1143 }
1144
1145 if (IsFunctionTemplate) {
1146 // Function templates always go through overload resolution, at which
1147 // point we'll perform the various checks (e.g., accessibility) we need
1148 // to based on which function we selected.
1149 Result.suppressDiagnostics();
1150
1151 return NameClassification::FunctionTemplate(Name: Template);
1152 }
1153
1154 return IsVarTemplate ? NameClassification::VarTemplate(Name: Template)
1155 : NameClassification::TypeTemplate(Name: Template);
1156 }
1157
1158 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1159 QualType T = Context.getTypeDeclType(Decl: Type);
1160 if (const auto *USD = dyn_cast<UsingShadowDecl>(Val: Found))
1161 T = Context.getUsingType(Found: USD, Underlying: T);
1162 return buildNamedType(S&: *this, SS: &SS, T, NameLoc);
1163 };
1164
1165 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1166 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: FirstDecl)) {
1167 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1168 MarkAnyDeclReferenced(Loc: Type->getLocation(), D: Type, /*OdrUse=*/MightBeOdrUse: false);
1169 return BuildTypeFor(Type, *Result.begin());
1170 }
1171
1172 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Val: FirstDecl);
1173 if (!Class) {
1174 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1175 if (ObjCCompatibleAliasDecl *Alias =
1176 dyn_cast<ObjCCompatibleAliasDecl>(Val: FirstDecl))
1177 Class = Alias->getClassInterface();
1178 }
1179
1180 if (Class) {
1181 DiagnoseUseOfDecl(D: Class, Locs: NameLoc);
1182
1183 if (NextToken.is(K: tok::period)) {
1184 // Interface. <something> is parsed as a property reference expression.
1185 // Just return "unknown" as a fall-through for now.
1186 Result.suppressDiagnostics();
1187 return NameClassification::Unknown();
1188 }
1189
1190 QualType T = Context.getObjCInterfaceType(Decl: Class);
1191 return ParsedType::make(P: T);
1192 }
1193
1194 if (isa<ConceptDecl>(Val: FirstDecl)) {
1195 // We want to preserve the UsingShadowDecl for concepts.
1196 if (auto *USD = dyn_cast<UsingShadowDecl>(Val: Result.getRepresentativeDecl()))
1197 return NameClassification::Concept(Name: TemplateName(USD));
1198 return NameClassification::Concept(
1199 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1200 }
1201
1202 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: FirstDecl)) {
1203 (void)DiagnoseUseOfDecl(D: EmptyD, Locs: NameLoc);
1204 return NameClassification::Error();
1205 }
1206
1207 // We can have a type template here if we're classifying a template argument.
1208 if (isa<TemplateDecl>(Val: FirstDecl) && !isa<FunctionTemplateDecl>(Val: FirstDecl) &&
1209 !isa<VarTemplateDecl>(Val: FirstDecl))
1210 return NameClassification::TypeTemplate(
1211 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1212
1213 // Check for a tag type hidden by a non-type decl in a few cases where it
1214 // seems likely a type is wanted instead of the non-type that was found.
1215 bool NextIsOp = NextToken.isOneOf(Ks: tok::amp, Ks: tok::star);
1216 if ((NextToken.is(K: tok::identifier) ||
1217 (NextIsOp &&
1218 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1219 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1220 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1221 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1222 return BuildTypeFor(Type, *Result.begin());
1223 }
1224
1225 // If we already know which single declaration is referenced, just annotate
1226 // that declaration directly. Defer resolving even non-overloaded class
1227 // member accesses, as we need to defer certain access checks until we know
1228 // the context.
1229 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1230 if (Result.isSingleResult() && !ADL &&
1231 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(Val: FirstDecl)))
1232 return NameClassification::NonType(D: Result.getRepresentativeDecl());
1233
1234 // Otherwise, this is an overload set that we will need to resolve later.
1235 Result.suppressDiagnostics();
1236 return NameClassification::OverloadSet(E: UnresolvedLookupExpr::Create(
1237 Context, NamingClass: Result.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
1238 NameInfo: Result.getLookupNameInfo(), RequiresADL: ADL, Begin: Result.begin(), End: Result.end(),
1239 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1240}
1241
1242ExprResult
1243Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1244 SourceLocation NameLoc) {
1245 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1246 CXXScopeSpec SS;
1247 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1248 return BuildDeclarationNameExpr(SS, R&: Result, /*ADL=*/NeedsADL: true);
1249}
1250
1251ExprResult
1252Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1253 IdentifierInfo *Name,
1254 SourceLocation NameLoc,
1255 bool IsAddressOfOperand) {
1256 DeclarationNameInfo NameInfo(Name, NameLoc);
1257 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1258 NameInfo, isAddressOfOperand: IsAddressOfOperand,
1259 /*TemplateArgs=*/nullptr);
1260}
1261
1262ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1263 NamedDecl *Found,
1264 SourceLocation NameLoc,
1265 const Token &NextToken) {
1266 if (getCurMethodDecl() && SS.isEmpty())
1267 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Val: Found->getUnderlyingDecl()))
1268 return ObjC().BuildIvarRefExpr(S, Loc: NameLoc, IV: Ivar);
1269
1270 // Reconstruct the lookup result.
1271 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1272 Result.addDecl(D: Found);
1273 Result.resolveKind();
1274
1275 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1276 return BuildDeclarationNameExpr(SS, R&: Result, NeedsADL: ADL, /*AcceptInvalidDecl=*/true);
1277}
1278
1279ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1280 // For an implicit class member access, transform the result into a member
1281 // access expression if necessary.
1282 auto *ULE = cast<UnresolvedLookupExpr>(Val: E);
1283 if ((*ULE->decls_begin())->isCXXClassMember()) {
1284 CXXScopeSpec SS;
1285 SS.Adopt(Other: ULE->getQualifierLoc());
1286
1287 // Reconstruct the lookup result.
1288 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1289 LookupOrdinaryName);
1290 Result.setNamingClass(ULE->getNamingClass());
1291 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1292 Result.addDecl(D: *I, AS: I.getAccess());
1293 Result.resolveKind();
1294 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc: SourceLocation(), R&: Result,
1295 TemplateArgs: nullptr, S);
1296 }
1297
1298 // Otherwise, this is already in the form we needed, and no further checks
1299 // are necessary.
1300 return ULE;
1301}
1302
1303Sema::TemplateNameKindForDiagnostics
1304Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1305 auto *TD = Name.getAsTemplateDecl();
1306 if (!TD)
1307 return TemplateNameKindForDiagnostics::DependentTemplate;
1308 if (isa<ClassTemplateDecl>(Val: TD))
1309 return TemplateNameKindForDiagnostics::ClassTemplate;
1310 if (isa<FunctionTemplateDecl>(Val: TD))
1311 return TemplateNameKindForDiagnostics::FunctionTemplate;
1312 if (isa<VarTemplateDecl>(Val: TD))
1313 return TemplateNameKindForDiagnostics::VarTemplate;
1314 if (isa<TypeAliasTemplateDecl>(Val: TD))
1315 return TemplateNameKindForDiagnostics::AliasTemplate;
1316 if (isa<TemplateTemplateParmDecl>(Val: TD))
1317 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1318 if (isa<ConceptDecl>(Val: TD))
1319 return TemplateNameKindForDiagnostics::Concept;
1320 return TemplateNameKindForDiagnostics::DependentTemplate;
1321}
1322
1323void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1324 assert(DC->getLexicalParent() == CurContext &&
1325 "The next DeclContext should be lexically contained in the current one.");
1326 CurContext = DC;
1327 S->setEntity(DC);
1328}
1329
1330void Sema::PopDeclContext() {
1331 assert(CurContext && "DeclContext imbalance!");
1332
1333 CurContext = CurContext->getLexicalParent();
1334 assert(CurContext && "Popped translation unit!");
1335}
1336
1337Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1338 Decl *D) {
1339 // Unlike PushDeclContext, the context to which we return is not necessarily
1340 // the containing DC of TD, because the new context will be some pre-existing
1341 // TagDecl definition instead of a fresh one.
1342 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1343 CurContext = cast<TagDecl>(Val: D)->getDefinition();
1344 assert(CurContext && "skipping definition of undefined tag");
1345 // Start lookups from the parent of the current context; we don't want to look
1346 // into the pre-existing complete definition.
1347 S->setEntity(CurContext->getLookupParent());
1348 return Result;
1349}
1350
1351void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1352 CurContext = static_cast<decltype(CurContext)>(Context);
1353}
1354
1355void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1356 // C++0x [basic.lookup.unqual]p13:
1357 // A name used in the definition of a static data member of class
1358 // X (after the qualified-id of the static member) is looked up as
1359 // if the name was used in a member function of X.
1360 // C++0x [basic.lookup.unqual]p14:
1361 // If a variable member of a namespace is defined outside of the
1362 // scope of its namespace then any name used in the definition of
1363 // the variable member (after the declarator-id) is looked up as
1364 // if the definition of the variable member occurred in its
1365 // namespace.
1366 // Both of these imply that we should push a scope whose context
1367 // is the semantic context of the declaration. We can't use
1368 // PushDeclContext here because that context is not necessarily
1369 // lexically contained in the current context. Fortunately,
1370 // the containing scope should have the appropriate information.
1371
1372 assert(!S->getEntity() && "scope already has entity");
1373
1374#ifndef NDEBUG
1375 Scope *Ancestor = S->getParent();
1376 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1377 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1378#endif
1379
1380 CurContext = DC;
1381 S->setEntity(DC);
1382
1383 if (S->getParent()->isTemplateParamScope()) {
1384 // Also set the corresponding entities for all immediately-enclosing
1385 // template parameter scopes.
1386 EnterTemplatedContext(S: S->getParent(), DC);
1387 }
1388}
1389
1390void Sema::ExitDeclaratorContext(Scope *S) {
1391 assert(S->getEntity() == CurContext && "Context imbalance!");
1392
1393 // Switch back to the lexical context. The safety of this is
1394 // enforced by an assert in EnterDeclaratorContext.
1395 Scope *Ancestor = S->getParent();
1396 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1397 CurContext = Ancestor->getEntity();
1398
1399 // We don't need to do anything with the scope, which is going to
1400 // disappear.
1401}
1402
1403void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1404 assert(S->isTemplateParamScope() &&
1405 "expected to be initializing a template parameter scope");
1406
1407 // C++20 [temp.local]p7:
1408 // In the definition of a member of a class template that appears outside
1409 // of the class template definition, the name of a member of the class
1410 // template hides the name of a template-parameter of any enclosing class
1411 // templates (but not a template-parameter of the member if the member is a
1412 // class or function template).
1413 // C++20 [temp.local]p9:
1414 // In the definition of a class template or in the definition of a member
1415 // of such a template that appears outside of the template definition, for
1416 // each non-dependent base class (13.8.2.1), if the name of the base class
1417 // or the name of a member of the base class is the same as the name of a
1418 // template-parameter, the base class name or member name hides the
1419 // template-parameter name (6.4.10).
1420 //
1421 // This means that a template parameter scope should be searched immediately
1422 // after searching the DeclContext for which it is a template parameter
1423 // scope. For example, for
1424 // template<typename T> template<typename U> template<typename V>
1425 // void N::A<T>::B<U>::f(...)
1426 // we search V then B<U> (and base classes) then U then A<T> (and base
1427 // classes) then T then N then ::.
1428 unsigned ScopeDepth = getTemplateDepth(S);
1429 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1430 DeclContext *SearchDCAfterScope = DC;
1431 for (; DC; DC = DC->getLookupParent()) {
1432 if (const TemplateParameterList *TPL =
1433 cast<Decl>(Val: DC)->getDescribedTemplateParams()) {
1434 unsigned DCDepth = TPL->getDepth() + 1;
1435 if (DCDepth > ScopeDepth)
1436 continue;
1437 if (ScopeDepth == DCDepth)
1438 SearchDCAfterScope = DC = DC->getLookupParent();
1439 break;
1440 }
1441 }
1442 S->setLookupEntity(SearchDCAfterScope);
1443 }
1444}
1445
1446void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1447 // We assume that the caller has already called
1448 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1449 FunctionDecl *FD = D->getAsFunction();
1450 if (!FD)
1451 return;
1452
1453 // Same implementation as PushDeclContext, but enters the context
1454 // from the lexical parent, rather than the top-level class.
1455 assert(CurContext == FD->getLexicalParent() &&
1456 "The next DeclContext should be lexically contained in the current one.");
1457 CurContext = FD;
1458 S->setEntity(CurContext);
1459
1460 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1461 ParmVarDecl *Param = FD->getParamDecl(i: P);
1462 // If the parameter has an identifier, then add it to the scope
1463 if (Param->getIdentifier()) {
1464 S->AddDecl(D: Param);
1465 IdResolver.AddDecl(D: Param);
1466 }
1467 }
1468}
1469
1470void Sema::ActOnExitFunctionContext() {
1471 // Same implementation as PopDeclContext, but returns to the lexical parent,
1472 // rather than the top-level class.
1473 assert(CurContext && "DeclContext imbalance!");
1474 CurContext = CurContext->getLexicalParent();
1475 assert(CurContext && "Popped translation unit!");
1476}
1477
1478/// Determine whether overloading is allowed for a new function
1479/// declaration considering prior declarations of the same name.
1480///
1481/// This routine determines whether overloading is possible, not
1482/// whether a new declaration actually overloads a previous one.
1483/// It will return true in C++ (where overloads are always permitted)
1484/// or, as a C extension, when either the new declaration or a
1485/// previous one is declared with the 'overloadable' attribute.
1486static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1487 ASTContext &Context,
1488 const FunctionDecl *New) {
1489 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1490 return true;
1491
1492 // Multiversion function declarations are not overloads in the
1493 // usual sense of that term, but lookup will report that an
1494 // overload set was found if more than one multiversion function
1495 // declaration is present for the same name. It is therefore
1496 // inadequate to assume that some prior declaration(s) had
1497 // the overloadable attribute; checking is required. Since one
1498 // declaration is permitted to omit the attribute, it is necessary
1499 // to check at least two; hence the 'any_of' check below. Note that
1500 // the overloadable attribute is implicitly added to declarations
1501 // that were required to have it but did not.
1502 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1503 return llvm::any_of(Range: Previous, P: [](const NamedDecl *ND) {
1504 return ND->hasAttr<OverloadableAttr>();
1505 });
1506 } else if (Previous.getResultKind() == LookupResultKind::Found)
1507 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1508
1509 return false;
1510}
1511
1512void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1513 // Move up the scope chain until we find the nearest enclosing
1514 // non-transparent context. The declaration will be introduced into this
1515 // scope.
1516 while (S->getEntity() && S->getEntity()->isTransparentContext())
1517 S = S->getParent();
1518
1519 // Add scoped declarations into their context, so that they can be
1520 // found later. Declarations without a context won't be inserted
1521 // into any context.
1522 if (AddToContext)
1523 CurContext->addDecl(D);
1524
1525 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1526 // are function-local declarations.
1527 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1528 return;
1529
1530 // Template instantiations should also not be pushed into scope.
1531 if (isa<FunctionDecl>(Val: D) &&
1532 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization())
1533 return;
1534
1535 if (isa<UsingEnumDecl>(Val: D) && D->getDeclName().isEmpty()) {
1536 S->AddDecl(D);
1537 return;
1538 }
1539 // If this replaces anything in the current scope,
1540 IdentifierResolver::iterator I = IdResolver.begin(Name: D->getDeclName()),
1541 IEnd = IdResolver.end();
1542 for (; I != IEnd; ++I) {
1543 if (S->isDeclScope(D: *I) && D->declarationReplaces(OldD: *I)) {
1544 S->RemoveDecl(D: *I);
1545 IdResolver.RemoveDecl(D: *I);
1546
1547 // Should only need to replace one decl.
1548 break;
1549 }
1550 }
1551
1552 S->AddDecl(D);
1553
1554 if (isa<LabelDecl>(Val: D) && !cast<LabelDecl>(Val: D)->isGnuLocal()) {
1555 // Implicitly-generated labels may end up getting generated in an order that
1556 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1557 // the label at the appropriate place in the identifier chain.
1558 for (I = IdResolver.begin(Name: D->getDeclName()); I != IEnd; ++I) {
1559 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1560 if (IDC == CurContext) {
1561 if (!S->isDeclScope(D: *I))
1562 continue;
1563 } else if (IDC->Encloses(DC: CurContext))
1564 break;
1565 }
1566
1567 IdResolver.InsertDeclAfter(Pos: I, D);
1568 } else {
1569 IdResolver.AddDecl(D);
1570 }
1571 warnOnReservedIdentifier(D);
1572}
1573
1574bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1575 bool AllowInlineNamespace) const {
1576 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1577}
1578
1579Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1580 DeclContext *TargetDC = DC->getPrimaryContext();
1581 do {
1582 if (DeclContext *ScopeDC = S->getEntity())
1583 if (ScopeDC->getPrimaryContext() == TargetDC)
1584 return S;
1585 } while ((S = S->getParent()));
1586
1587 return nullptr;
1588}
1589
1590static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1591 DeclContext*,
1592 ASTContext&);
1593
1594void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1595 bool ConsiderLinkage,
1596 bool AllowInlineNamespace) {
1597 LookupResult::Filter F = R.makeFilter();
1598 while (F.hasNext()) {
1599 NamedDecl *D = F.next();
1600
1601 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1602 continue;
1603
1604 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1605 continue;
1606
1607 F.erase();
1608 }
1609
1610 F.done();
1611}
1612
1613bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1614 // [module.interface]p7:
1615 // A declaration is attached to a module as follows:
1616 // - If the declaration is a non-dependent friend declaration that nominates a
1617 // function with a declarator-id that is a qualified-id or template-id or that
1618 // nominates a class other than with an elaborated-type-specifier with neither
1619 // a nested-name-specifier nor a simple-template-id, it is attached to the
1620 // module to which the friend is attached ([basic.link]).
1621 if (New->getFriendObjectKind() &&
1622 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1623 New->setLocalOwningModule(Old->getOwningModule());
1624 makeMergedDefinitionVisible(ND: New);
1625 return false;
1626 }
1627
1628 Module *NewM = New->getOwningModule();
1629 Module *OldM = Old->getOwningModule();
1630
1631 if (NewM && NewM->isPrivateModule())
1632 NewM = NewM->Parent;
1633 if (OldM && OldM->isPrivateModule())
1634 OldM = OldM->Parent;
1635
1636 if (NewM == OldM)
1637 return false;
1638
1639 if (NewM && OldM) {
1640 // A module implementation unit has visibility of the decls in its
1641 // implicitly imported interface.
1642 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1643 return false;
1644
1645 // Partitions are part of the module, but a partition could import another
1646 // module, so verify that the PMIs agree.
1647 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1648 getASTContext().isInSameModule(M1: NewM, M2: OldM))
1649 return false;
1650 }
1651
1652 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1653 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1654 if (NewIsModuleInterface || OldIsModuleInterface) {
1655 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1656 // if a declaration of D [...] appears in the purview of a module, all
1657 // other such declarations shall appear in the purview of the same module
1658 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_owning_module)
1659 << New
1660 << NewIsModuleInterface
1661 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1662 << OldIsModuleInterface
1663 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1664 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1665 New->setInvalidDecl();
1666 return true;
1667 }
1668
1669 return false;
1670}
1671
1672bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1673 // [module.interface]p1:
1674 // An export-declaration shall inhabit a namespace scope.
1675 //
1676 // So it is meaningless to talk about redeclaration which is not at namespace
1677 // scope.
1678 if (!New->getLexicalDeclContext()
1679 ->getNonTransparentContext()
1680 ->isFileContext() ||
1681 !Old->getLexicalDeclContext()
1682 ->getNonTransparentContext()
1683 ->isFileContext())
1684 return false;
1685
1686 bool IsNewExported = New->isInExportDeclContext();
1687 bool IsOldExported = Old->isInExportDeclContext();
1688
1689 // It should be irrevelant if both of them are not exported.
1690 if (!IsNewExported && !IsOldExported)
1691 return false;
1692
1693 if (IsOldExported)
1694 return false;
1695
1696 // If the Old declaration are not attached to named modules
1697 // and the New declaration are attached to global module.
1698 // It should be fine to allow the export since it doesn't change
1699 // the linkage of declarations. See
1700 // https://github.com/llvm/llvm-project/issues/98583 for details.
1701 if (!Old->isInNamedModule() && New->getOwningModule() &&
1702 New->getOwningModule()->isImplicitGlobalModule())
1703 return false;
1704
1705 assert(IsNewExported);
1706
1707 auto Lk = Old->getFormalLinkage();
1708 int S = 0;
1709 if (Lk == Linkage::Internal)
1710 S = 1;
1711 else if (Lk == Linkage::Module)
1712 S = 2;
1713 Diag(Loc: New->getLocation(), DiagID: diag::err_redeclaration_non_exported) << New << S;
1714 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1715 return true;
1716}
1717
1718bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1719 if (CheckRedeclarationModuleOwnership(New, Old))
1720 return true;
1721
1722 if (CheckRedeclarationExported(New, Old))
1723 return true;
1724
1725 return false;
1726}
1727
1728bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1729 const NamedDecl *Old) const {
1730 assert(getASTContext().isSameEntity(New, Old) &&
1731 "New and Old are not the same definition, we should diagnostic it "
1732 "immediately instead of checking it.");
1733 assert(const_cast<Sema *>(this)->isReachable(New) &&
1734 const_cast<Sema *>(this)->isReachable(Old) &&
1735 "We shouldn't see unreachable definitions here.");
1736
1737 Module *NewM = New->getOwningModule();
1738 Module *OldM = Old->getOwningModule();
1739
1740 // We only checks for named modules here. The header like modules is skipped.
1741 // FIXME: This is not right if we import the header like modules in the module
1742 // purview.
1743 //
1744 // For example, assuming "header.h" provides definition for `D`.
1745 // ```C++
1746 // //--- M.cppm
1747 // export module M;
1748 // import "header.h"; // or #include "header.h" but import it by clang modules
1749 // actually.
1750 //
1751 // //--- Use.cpp
1752 // import M;
1753 // import "header.h"; // or uses clang modules.
1754 // ```
1755 //
1756 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1757 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1758 // reject it. But the current implementation couldn't detect the case since we
1759 // don't record the information about the importee modules.
1760 //
1761 // But this might not be painful in practice. Since the design of C++20 Named
1762 // Modules suggests us to use headers in global module fragment instead of
1763 // module purview.
1764 if (NewM && NewM->isHeaderLikeModule())
1765 NewM = nullptr;
1766 if (OldM && OldM->isHeaderLikeModule())
1767 OldM = nullptr;
1768
1769 if (!NewM && !OldM)
1770 return true;
1771
1772 // [basic.def.odr]p14.3
1773 // Each such definition shall not be attached to a named module
1774 // ([module.unit]).
1775 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1776 return true;
1777
1778 // Then New and Old lives in the same TU if their share one same module unit.
1779 if (NewM)
1780 NewM = NewM->getTopLevelModule();
1781 if (OldM)
1782 OldM = OldM->getTopLevelModule();
1783 return OldM == NewM;
1784}
1785
1786static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1787 if (D->getDeclContext()->isFileContext())
1788 return false;
1789
1790 return isa<UsingShadowDecl>(Val: D) ||
1791 isa<UnresolvedUsingTypenameDecl>(Val: D) ||
1792 isa<UnresolvedUsingValueDecl>(Val: D);
1793}
1794
1795/// Removes using shadow declarations not at class scope from the lookup
1796/// results.
1797static void RemoveUsingDecls(LookupResult &R) {
1798 LookupResult::Filter F = R.makeFilter();
1799 while (F.hasNext())
1800 if (isUsingDeclNotAtClassScope(D: F.next()))
1801 F.erase();
1802
1803 F.done();
1804}
1805
1806/// Check for this common pattern:
1807/// @code
1808/// class S {
1809/// S(const S&); // DO NOT IMPLEMENT
1810/// void operator=(const S&); // DO NOT IMPLEMENT
1811/// };
1812/// @endcode
1813static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1814 // FIXME: Should check for private access too but access is set after we get
1815 // the decl here.
1816 if (D->doesThisDeclarationHaveABody())
1817 return false;
1818
1819 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: D))
1820 return CD->isCopyConstructor();
1821 return D->isCopyAssignmentOperator();
1822}
1823
1824bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1825 const DeclContext *DC = D->getDeclContext();
1826 while (!DC->isTranslationUnit()) {
1827 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Val: DC)){
1828 if (!RD->hasNameForLinkage())
1829 return true;
1830 }
1831 DC = DC->getParent();
1832 }
1833
1834 return !D->isExternallyVisible();
1835}
1836
1837// FIXME: This needs to be refactored; some other isInMainFile users want
1838// these semantics.
1839static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1840 if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1841 return false;
1842 return S.SourceMgr.isInMainFile(Loc);
1843}
1844
1845bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1846 assert(D);
1847
1848 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1849 return false;
1850
1851 // Ignore all entities declared within templates, and out-of-line definitions
1852 // of members of class templates.
1853 if (D->getDeclContext()->isDependentContext() ||
1854 D->getLexicalDeclContext()->isDependentContext())
1855 return false;
1856
1857 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1858 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1859 return false;
1860 // A non-out-of-line declaration of a member specialization was implicitly
1861 // instantiated; it's the out-of-line declaration that we're interested in.
1862 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1863 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1864 return false;
1865
1866 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
1867 if (MD->isVirtual() || IsDisallowedCopyOrAssign(D: MD))
1868 return false;
1869 } else {
1870 // 'static inline' functions are defined in headers; don't warn.
1871 if (FD->isInlined() && !isMainFileLoc(S: *this, Loc: FD->getLocation()))
1872 return false;
1873 }
1874
1875 if (FD->doesThisDeclarationHaveABody() &&
1876 Context.DeclMustBeEmitted(D: FD))
1877 return false;
1878 } else if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1879 // Constants and utility variables are defined in headers with internal
1880 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1881 // like "inline".)
1882 if (!isMainFileLoc(S: *this, Loc: VD->getLocation()))
1883 return false;
1884
1885 if (Context.DeclMustBeEmitted(D: VD))
1886 return false;
1887
1888 if (VD->isStaticDataMember() &&
1889 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1890 return false;
1891 if (VD->isStaticDataMember() &&
1892 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1893 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1894 return false;
1895
1896 if (VD->isInline() && !isMainFileLoc(S: *this, Loc: VD->getLocation()))
1897 return false;
1898 } else {
1899 return false;
1900 }
1901
1902 // Only warn for unused decls internal to the translation unit.
1903 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1904 // for inline functions defined in the main source file, for instance.
1905 return mightHaveNonExternalLinkage(D);
1906}
1907
1908void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1909 if (!D)
1910 return;
1911
1912 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1913 const FunctionDecl *First = FD->getFirstDecl();
1914 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
1915 return; // First should already be in the vector.
1916 }
1917
1918 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1919 const VarDecl *First = VD->getFirstDecl();
1920 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
1921 return; // First should already be in the vector.
1922 }
1923
1924 if (ShouldWarnIfUnusedFileScopedDecl(D))
1925 UnusedFileScopedDecls.push_back(LocalValue: D);
1926}
1927
1928static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1929 const NamedDecl *D) {
1930 if (D->isInvalidDecl())
1931 return false;
1932
1933 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: D)) {
1934 // For a decomposition declaration, warn if none of the bindings are
1935 // referenced, instead of if the variable itself is referenced (which
1936 // it is, by the bindings' expressions).
1937 bool IsAllIgnored = true;
1938 for (const auto *BD : DD->bindings()) {
1939 if (BD->isReferenced())
1940 return false;
1941 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
1942 BD->hasAttr<UnusedAttr>());
1943 }
1944 if (IsAllIgnored)
1945 return false;
1946 } else if (!D->getDeclName()) {
1947 return false;
1948 } else if (D->isReferenced() || D->isUsed()) {
1949 return false;
1950 }
1951
1952 if (D->isPlaceholderVar(LangOpts))
1953 return false;
1954
1955 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1956 D->hasAttr<CleanupAttr>())
1957 return false;
1958
1959 if (isa<LabelDecl>(Val: D))
1960 return true;
1961
1962 // Except for labels, we only care about unused decls that are local to
1963 // functions.
1964 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1965 if (const auto *R = dyn_cast<CXXRecordDecl>(Val: D->getDeclContext()))
1966 // For dependent types, the diagnostic is deferred.
1967 WithinFunction =
1968 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1969 if (!WithinFunction)
1970 return false;
1971
1972 if (isa<TypedefNameDecl>(Val: D))
1973 return true;
1974
1975 // White-list anything that isn't a local variable.
1976 if (!isa<VarDecl>(Val: D) || isa<ParmVarDecl>(Val: D) || isa<ImplicitParamDecl>(Val: D))
1977 return false;
1978
1979 // Types of valid local variables should be complete, so this should succeed.
1980 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1981
1982 const Expr *Init = VD->getInit();
1983 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Val: Init))
1984 Init = Cleanups->getSubExpr();
1985
1986 const auto *Ty = VD->getType().getTypePtr();
1987
1988 // Only look at the outermost level of typedef.
1989 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1990 // Allow anything marked with __attribute__((unused)).
1991 if (TT->getDecl()->hasAttr<UnusedAttr>())
1992 return false;
1993 }
1994
1995 // Warn for reference variables whose initializtion performs lifetime
1996 // extension.
1997 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Val: Init);
1998 MTE && MTE->getExtendingDecl()) {
1999 Ty = VD->getType().getNonReferenceType().getTypePtr();
2000 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2001 }
2002
2003 // If we failed to complete the type for some reason, or if the type is
2004 // dependent, don't diagnose the variable.
2005 if (Ty->isIncompleteType() || Ty->isDependentType())
2006 return false;
2007
2008 // Look at the element type to ensure that the warning behaviour is
2009 // consistent for both scalars and arrays.
2010 Ty = Ty->getBaseElementTypeUnsafe();
2011
2012 if (const TagType *TT = Ty->getAs<TagType>()) {
2013 const TagDecl *Tag = TT->getDecl();
2014 if (Tag->hasAttr<UnusedAttr>())
2015 return false;
2016
2017 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
2018 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2019 return false;
2020
2021 if (Init) {
2022 const auto *Construct =
2023 dyn_cast<CXXConstructExpr>(Val: Init->IgnoreImpCasts());
2024 if (Construct && !Construct->isElidable()) {
2025 const CXXConstructorDecl *CD = Construct->getConstructor();
2026 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2027 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2028 return false;
2029 }
2030
2031 // Suppress the warning if we don't know how this is constructed, and
2032 // it could possibly be non-trivial constructor.
2033 if (Init->isTypeDependent()) {
2034 for (const CXXConstructorDecl *Ctor : RD->ctors())
2035 if (!Ctor->isTrivial())
2036 return false;
2037 }
2038
2039 // Suppress the warning if the constructor is unresolved because
2040 // its arguments are dependent.
2041 if (isa<CXXUnresolvedConstructExpr>(Val: Init))
2042 return false;
2043 }
2044 }
2045 }
2046
2047 // TODO: __attribute__((unused)) templates?
2048 }
2049
2050 return true;
2051}
2052
2053static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2054 FixItHint &Hint) {
2055 if (isa<LabelDecl>(Val: D)) {
2056 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2057 loc: D->getEndLoc(), TKind: tok::colon, SM: Ctx.getSourceManager(), LangOpts: Ctx.getLangOpts(),
2058 /*SkipTrailingWhitespaceAndNewline=*/SkipTrailingWhitespaceAndNewLine: false);
2059 if (AfterColon.isInvalid())
2060 return;
2061 Hint = FixItHint::CreateRemoval(
2062 RemoveRange: CharSourceRange::getCharRange(B: D->getBeginLoc(), E: AfterColon));
2063 }
2064}
2065
2066void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2067 DiagnoseUnusedNestedTypedefs(
2068 D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2069}
2070
2071void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2072 DiagReceiverTy DiagReceiver) {
2073 if (D->getTypeForDecl()->isDependentType())
2074 return;
2075
2076 for (auto *TmpD : D->decls()) {
2077 if (const auto *T = dyn_cast<TypedefNameDecl>(Val: TmpD))
2078 DiagnoseUnusedDecl(ND: T, DiagReceiver);
2079 else if(const auto *R = dyn_cast<RecordDecl>(Val: TmpD))
2080 DiagnoseUnusedNestedTypedefs(D: R, DiagReceiver);
2081 }
2082}
2083
2084void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2085 DiagnoseUnusedDecl(
2086 ND: D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2087}
2088
2089void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2090 if (!ShouldDiagnoseUnusedDecl(LangOpts: getLangOpts(), D))
2091 return;
2092
2093 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
2094 // typedefs can be referenced later on, so the diagnostics are emitted
2095 // at end-of-translation-unit.
2096 UnusedLocalTypedefNameCandidates.insert(X: TD);
2097 return;
2098 }
2099
2100 FixItHint Hint;
2101 GenerateFixForUnusedDecl(D, Ctx&: Context, Hint);
2102
2103 unsigned DiagID;
2104 if (isa<VarDecl>(Val: D) && cast<VarDecl>(Val: D)->isExceptionVariable())
2105 DiagID = diag::warn_unused_exception_param;
2106 else if (isa<LabelDecl>(Val: D))
2107 DiagID = diag::warn_unused_label;
2108 else
2109 DiagID = diag::warn_unused_variable;
2110
2111 SourceLocation DiagLoc = D->getLocation();
2112 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2113}
2114
2115void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2116 DiagReceiverTy DiagReceiver) {
2117 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2118 // it's not really unused.
2119 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2120 return;
2121
2122 // In C++, `_` variables behave as if they were maybe_unused
2123 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(LangOpts: getLangOpts()))
2124 return;
2125
2126 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2127
2128 if (Ty->isReferenceType() || Ty->isDependentType())
2129 return;
2130
2131 if (const TagType *TT = Ty->getAs<TagType>()) {
2132 const TagDecl *Tag = TT->getDecl();
2133 if (Tag->hasAttr<UnusedAttr>())
2134 return;
2135 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2136 // mimic gcc's behavior.
2137 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag);
2138 RD && !RD->hasAttr<WarnUnusedAttr>())
2139 return;
2140 }
2141
2142 // Don't warn about __block Objective-C pointer variables, as they might
2143 // be assigned in the block but not used elsewhere for the purpose of lifetime
2144 // extension.
2145 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2146 return;
2147
2148 // Don't warn about Objective-C pointer variables with precise lifetime
2149 // semantics; they can be used to ensure ARC releases the object at a known
2150 // time, which may mean assignment but no other references.
2151 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2152 return;
2153
2154 auto iter = RefsMinusAssignments.find(Val: VD);
2155 if (iter == RefsMinusAssignments.end())
2156 return;
2157
2158 assert(iter->getSecond() >= 0 &&
2159 "Found a negative number of references to a VarDecl");
2160 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2161 // Assume the given VarDecl is "used" if its ref count stored in
2162 // `RefMinusAssignments` is positive, with one exception.
2163 //
2164 // For a C++ variable whose decl (with initializer) entirely consist the
2165 // condition expression of a if/while/for construct,
2166 // Clang creates a DeclRefExpr for the condition expression rather than a
2167 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2168 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2169 // used in the body of the if/while/for construct.
2170 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2171 if (!UnusedCXXCondDecl)
2172 return;
2173 }
2174
2175 unsigned DiagID = isa<ParmVarDecl>(Val: VD) ? diag::warn_unused_but_set_parameter
2176 : diag::warn_unused_but_set_variable;
2177 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2178}
2179
2180static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2181 Sema::DiagReceiverTy DiagReceiver) {
2182 // Verify that we have no forward references left. If so, there was a goto
2183 // or address of a label taken, but no definition of it. Label fwd
2184 // definitions are indicated with a null substmt which is also not a resolved
2185 // MS inline assembly label name.
2186 bool Diagnose = false;
2187 if (L->isMSAsmLabel())
2188 Diagnose = !L->isResolvedMSAsmLabel();
2189 else
2190 Diagnose = L->getStmt() == nullptr;
2191 if (Diagnose)
2192 DiagReceiver(L->getLocation(), S.PDiag(DiagID: diag::err_undeclared_label_use)
2193 << L);
2194}
2195
2196void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2197 S->applyNRVO();
2198
2199 if (S->decl_empty()) return;
2200 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2201 "Scope shouldn't contain decls!");
2202
2203 /// We visit the decls in non-deterministic order, but we want diagnostics
2204 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2205 /// and sort the diagnostics before emitting them, after we visited all decls.
2206 struct LocAndDiag {
2207 SourceLocation Loc;
2208 std::optional<SourceLocation> PreviousDeclLoc;
2209 PartialDiagnostic PD;
2210 };
2211 SmallVector<LocAndDiag, 16> DeclDiags;
2212 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2213 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: std::nullopt, .PD: std::move(PD)});
2214 };
2215 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2216 SourceLocation PreviousDeclLoc,
2217 PartialDiagnostic PD) {
2218 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: PreviousDeclLoc, .PD: std::move(PD)});
2219 };
2220
2221 for (auto *TmpD : S->decls()) {
2222 assert(TmpD && "This decl didn't get pushed??");
2223
2224 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2225 NamedDecl *D = cast<NamedDecl>(Val: TmpD);
2226
2227 // Diagnose unused variables in this scope.
2228 if (!S->hasUnrecoverableErrorOccurred()) {
2229 DiagnoseUnusedDecl(D, DiagReceiver: addDiag);
2230 if (const auto *RD = dyn_cast<RecordDecl>(Val: D))
2231 DiagnoseUnusedNestedTypedefs(D: RD, DiagReceiver: addDiag);
2232 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2233 DiagnoseUnusedButSetDecl(VD, DiagReceiver: addDiag);
2234 RefsMinusAssignments.erase(Val: VD);
2235 }
2236 }
2237
2238 if (!D->getDeclName()) continue;
2239
2240 // If this was a forward reference to a label, verify it was defined.
2241 if (LabelDecl *LD = dyn_cast<LabelDecl>(Val: D))
2242 CheckPoppedLabel(L: LD, S&: *this, DiagReceiver: addDiag);
2243
2244 // Partial translation units that are created in incremental processing must
2245 // not clean up the IdResolver because PTUs should take into account the
2246 // declarations that came from previous PTUs.
2247 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2248 getLangOpts().CPlusPlus)
2249 IdResolver.RemoveDecl(D);
2250
2251 // Warn on it if we are shadowing a declaration.
2252 auto ShadowI = ShadowingDecls.find(Val: D);
2253 if (ShadowI != ShadowingDecls.end()) {
2254 if (const auto *FD = dyn_cast<FieldDecl>(Val: ShadowI->second)) {
2255 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2256 PDiag(DiagID: diag::warn_ctor_parm_shadows_field)
2257 << D << FD << FD->getParent());
2258 }
2259 ShadowingDecls.erase(I: ShadowI);
2260 }
2261 }
2262
2263 llvm::sort(C&: DeclDiags,
2264 Comp: [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2265 // The particular order for diagnostics is not important, as long
2266 // as the order is deterministic. Using the raw location is going
2267 // to generally be in source order unless there are macro
2268 // expansions involved.
2269 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2270 });
2271 for (const LocAndDiag &D : DeclDiags) {
2272 Diag(Loc: D.Loc, PD: D.PD);
2273 if (D.PreviousDeclLoc)
2274 Diag(Loc: *D.PreviousDeclLoc, DiagID: diag::note_previous_declaration);
2275 }
2276}
2277
2278Scope *Sema::getNonFieldDeclScope(Scope *S) {
2279 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2280 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2281 (S->isClassScope() && !getLangOpts().CPlusPlus))
2282 S = S->getParent();
2283 return S;
2284}
2285
2286static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2287 ASTContext::GetBuiltinTypeError Error) {
2288 switch (Error) {
2289 case ASTContext::GE_None:
2290 return "";
2291 case ASTContext::GE_Missing_type:
2292 return BuiltinInfo.getHeaderName(ID);
2293 case ASTContext::GE_Missing_stdio:
2294 return "stdio.h";
2295 case ASTContext::GE_Missing_setjmp:
2296 return "setjmp.h";
2297 case ASTContext::GE_Missing_ucontext:
2298 return "ucontext.h";
2299 }
2300 llvm_unreachable("unhandled error kind");
2301}
2302
2303FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2304 unsigned ID, SourceLocation Loc) {
2305 DeclContext *Parent = Context.getTranslationUnitDecl();
2306
2307 if (getLangOpts().CPlusPlus) {
2308 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2309 C&: Context, DC: Parent, ExternLoc: Loc, LangLoc: Loc, Lang: LinkageSpecLanguageIDs::C, HasBraces: false);
2310 CLinkageDecl->setImplicit();
2311 Parent->addDecl(D: CLinkageDecl);
2312 Parent = CLinkageDecl;
2313 }
2314
2315 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified;
2316 if (Context.BuiltinInfo.isImmediate(ID)) {
2317 assert(getLangOpts().CPlusPlus20 &&
2318 "consteval builtins should only be available in C++20 mode");
2319 ConstexprKind = ConstexprSpecKind::Consteval;
2320 }
2321
2322 FunctionDecl *New = FunctionDecl::Create(
2323 C&: Context, DC: Parent, StartLoc: Loc, NLoc: Loc, N: II, T: Type, /*TInfo=*/nullptr, SC: SC_Extern,
2324 UsesFPIntrin: getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2325 hasWrittenPrototype: Type->isFunctionProtoType(), ConstexprKind);
2326 New->setImplicit();
2327 New->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID));
2328
2329 // Create Decl objects for each parameter, adding them to the
2330 // FunctionDecl.
2331 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: Type)) {
2332 SmallVector<ParmVarDecl *, 16> Params;
2333 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2334 ParmVarDecl *parm = ParmVarDecl::Create(
2335 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
2336 T: FT->getParamType(i), /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
2337 parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
2338 Params.push_back(Elt: parm);
2339 }
2340 New->setParams(Params);
2341 }
2342
2343 AddKnownFunctionAttributes(FD: New);
2344 return New;
2345}
2346
2347NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2348 Scope *S, bool ForRedeclaration,
2349 SourceLocation Loc) {
2350 LookupNecessaryTypesForBuiltin(S, ID);
2351
2352 ASTContext::GetBuiltinTypeError Error;
2353 QualType R = Context.GetBuiltinType(ID, Error);
2354 if (Error) {
2355 if (!ForRedeclaration)
2356 return nullptr;
2357
2358 // If we have a builtin without an associated type we should not emit a
2359 // warning when we were not able to find a type for it.
2360 if (Error == ASTContext::GE_Missing_type ||
2361 Context.BuiltinInfo.allowTypeMismatch(ID))
2362 return nullptr;
2363
2364 // If we could not find a type for setjmp it is because the jmp_buf type was
2365 // not defined prior to the setjmp declaration.
2366 if (Error == ASTContext::GE_Missing_setjmp) {
2367 Diag(Loc, DiagID: diag::warn_implicit_decl_no_jmp_buf)
2368 << Context.BuiltinInfo.getName(ID);
2369 return nullptr;
2370 }
2371
2372 // Generally, we emit a warning that the declaration requires the
2373 // appropriate header.
2374 Diag(Loc, DiagID: diag::warn_implicit_decl_requires_sysheader)
2375 << getHeaderName(BuiltinInfo&: Context.BuiltinInfo, ID, Error)
2376 << Context.BuiltinInfo.getName(ID);
2377 return nullptr;
2378 }
2379
2380 if (!ForRedeclaration &&
2381 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2382 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2383 Diag(Loc, DiagID: LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2384 : diag::ext_implicit_lib_function_decl)
2385 << Context.BuiltinInfo.getName(ID) << R;
2386 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2387 Diag(Loc, DiagID: diag::note_include_header_or_declare)
2388 << Header << Context.BuiltinInfo.getName(ID);
2389 }
2390
2391 if (R.isNull())
2392 return nullptr;
2393
2394 FunctionDecl *New = CreateBuiltin(II, Type: R, ID, Loc);
2395 RegisterLocallyScopedExternCDecl(ND: New, S);
2396
2397 // TUScope is the translation-unit scope to insert this function into.
2398 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2399 // relate Scopes to DeclContexts, and probably eliminate CurContext
2400 // entirely, but we're not there yet.
2401 DeclContext *SavedContext = CurContext;
2402 CurContext = New->getDeclContext();
2403 PushOnScopeChains(D: New, S: TUScope);
2404 CurContext = SavedContext;
2405 return New;
2406}
2407
2408/// Typedef declarations don't have linkage, but they still denote the same
2409/// entity if their types are the same.
2410/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2411/// isSameEntity.
2412static void
2413filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl,
2414 LookupResult &Previous) {
2415 // This is only interesting when modules are enabled.
2416 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2417 return;
2418
2419 // Empty sets are uninteresting.
2420 if (Previous.empty())
2421 return;
2422
2423 LookupResult::Filter Filter = Previous.makeFilter();
2424 while (Filter.hasNext()) {
2425 NamedDecl *Old = Filter.next();
2426
2427 // Non-hidden declarations are never ignored.
2428 if (S.isVisible(D: Old))
2429 continue;
2430
2431 // Declarations of the same entity are not ignored, even if they have
2432 // different linkages.
2433 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2434 if (S.Context.hasSameType(T1: OldTD->getUnderlyingType(),
2435 T2: Decl->getUnderlyingType()))
2436 continue;
2437
2438 // If both declarations give a tag declaration a typedef name for linkage
2439 // purposes, then they declare the same entity.
2440 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2441 Decl->getAnonDeclWithTypedefName())
2442 continue;
2443 }
2444
2445 Filter.erase();
2446 }
2447
2448 Filter.done();
2449}
2450
2451bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) {
2452 QualType OldType;
2453 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Val: Old))
2454 OldType = OldTypedef->getUnderlyingType();
2455 else
2456 OldType = Context.getTypeDeclType(Decl: Old);
2457 QualType NewType = New->getUnderlyingType();
2458
2459 if (NewType->isVariablyModifiedType()) {
2460 // Must not redefine a typedef with a variably-modified type.
2461 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2462 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_variably_modified_typedef)
2463 << Kind << NewType;
2464 if (Old->getLocation().isValid())
2465 notePreviousDefinition(Old, New: New->getLocation());
2466 New->setInvalidDecl();
2467 return true;
2468 }
2469
2470 if (OldType != NewType &&
2471 !OldType->isDependentType() &&
2472 !NewType->isDependentType() &&
2473 !Context.hasSameType(T1: OldType, T2: NewType)) {
2474 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2475 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_typedef)
2476 << Kind << NewType << OldType;
2477 if (Old->getLocation().isValid())
2478 notePreviousDefinition(Old, New: New->getLocation());
2479 New->setInvalidDecl();
2480 return true;
2481 }
2482 return false;
2483}
2484
2485void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2486 LookupResult &OldDecls) {
2487 // If the new decl is known invalid already, don't bother doing any
2488 // merging checks.
2489 if (New->isInvalidDecl()) return;
2490
2491 // Allow multiple definitions for ObjC built-in typedefs.
2492 // FIXME: Verify the underlying types are equivalent!
2493 if (getLangOpts().ObjC) {
2494 const IdentifierInfo *TypeID = New->getIdentifier();
2495 switch (TypeID->getLength()) {
2496 default: break;
2497 case 2:
2498 {
2499 if (!TypeID->isStr(Str: "id"))
2500 break;
2501 QualType T = New->getUnderlyingType();
2502 if (!T->isPointerType())
2503 break;
2504 if (!T->isVoidPointerType()) {
2505 QualType PT = T->castAs<PointerType>()->getPointeeType();
2506 if (!PT->isStructureType())
2507 break;
2508 }
2509 Context.setObjCIdRedefinitionType(T);
2510 // Install the built-in type for 'id', ignoring the current definition.
2511 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2512 return;
2513 }
2514 case 5:
2515 if (!TypeID->isStr(Str: "Class"))
2516 break;
2517 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2518 // Install the built-in type for 'Class', ignoring the current definition.
2519 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2520 return;
2521 case 3:
2522 if (!TypeID->isStr(Str: "SEL"))
2523 break;
2524 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2525 // Install the built-in type for 'SEL', ignoring the current definition.
2526 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2527 return;
2528 }
2529 // Fall through - the typedef name was not a builtin type.
2530 }
2531
2532 // Verify the old decl was also a type.
2533 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2534 if (!Old) {
2535 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
2536 << New->getDeclName();
2537
2538 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2539 if (OldD->getLocation().isValid())
2540 notePreviousDefinition(Old: OldD, New: New->getLocation());
2541
2542 return New->setInvalidDecl();
2543 }
2544
2545 // If the old declaration is invalid, just give up here.
2546 if (Old->isInvalidDecl())
2547 return New->setInvalidDecl();
2548
2549 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2550 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2551 auto *NewTag = New->getAnonDeclWithTypedefName();
2552 NamedDecl *Hidden = nullptr;
2553 if (OldTag && NewTag &&
2554 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2555 !hasVisibleDefinition(D: OldTag, Suggested: &Hidden)) {
2556 // There is a definition of this tag, but it is not visible. Use it
2557 // instead of our tag.
2558 New->setTypeForDecl(OldTD->getTypeForDecl());
2559 if (OldTD->isModed())
2560 New->setModedTypeSourceInfo(unmodedTSI: OldTD->getTypeSourceInfo(),
2561 modedTy: OldTD->getUnderlyingType());
2562 else
2563 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2564
2565 // Make the old tag definition visible.
2566 makeMergedDefinitionVisible(ND: Hidden);
2567
2568 CleanupMergedEnum(S, New: NewTag);
2569 }
2570 }
2571
2572 // If the typedef types are not identical, reject them in all languages and
2573 // with any extensions enabled.
2574 if (isIncompatibleTypedef(Old, New))
2575 return;
2576
2577 // The types match. Link up the redeclaration chain and merge attributes if
2578 // the old declaration was a typedef.
2579 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Val: Old)) {
2580 New->setPreviousDecl(Typedef);
2581 mergeDeclAttributes(New, Old);
2582 }
2583
2584 if (getLangOpts().MicrosoftExt)
2585 return;
2586
2587 if (getLangOpts().CPlusPlus) {
2588 // C++ [dcl.typedef]p2:
2589 // In a given non-class scope, a typedef specifier can be used to
2590 // redefine the name of any type declared in that scope to refer
2591 // to the type to which it already refers.
2592 if (!isa<CXXRecordDecl>(Val: CurContext))
2593 return;
2594
2595 // C++0x [dcl.typedef]p4:
2596 // In a given class scope, a typedef specifier can be used to redefine
2597 // any class-name declared in that scope that is not also a typedef-name
2598 // to refer to the type to which it already refers.
2599 //
2600 // This wording came in via DR424, which was a correction to the
2601 // wording in DR56, which accidentally banned code like:
2602 //
2603 // struct S {
2604 // typedef struct A { } A;
2605 // };
2606 //
2607 // in the C++03 standard. We implement the C++0x semantics, which
2608 // allow the above but disallow
2609 //
2610 // struct S {
2611 // typedef int I;
2612 // typedef int I;
2613 // };
2614 //
2615 // since that was the intent of DR56.
2616 if (!isa<TypedefNameDecl>(Val: Old))
2617 return;
2618
2619 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition)
2620 << New->getDeclName();
2621 notePreviousDefinition(Old, New: New->getLocation());
2622 return New->setInvalidDecl();
2623 }
2624
2625 // Modules always permit redefinition of typedefs, as does C11.
2626 if (getLangOpts().Modules || getLangOpts().C11)
2627 return;
2628
2629 // If we have a redefinition of a typedef in C, emit a warning. This warning
2630 // is normally mapped to an error, but can be controlled with
2631 // -Wtypedef-redefinition. If either the original or the redefinition is
2632 // in a system header, don't emit this for compatibility with GCC.
2633 if (getDiagnostics().getSuppressSystemWarnings() &&
2634 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2635 (Old->isImplicit() ||
2636 Context.getSourceManager().isInSystemHeader(Loc: Old->getLocation()) ||
2637 Context.getSourceManager().isInSystemHeader(Loc: New->getLocation())))
2638 return;
2639
2640 Diag(Loc: New->getLocation(), DiagID: diag::ext_redefinition_of_typedef)
2641 << New->getDeclName();
2642 notePreviousDefinition(Old, New: New->getLocation());
2643}
2644
2645void Sema::CleanupMergedEnum(Scope *S, Decl *New) {
2646 // If this was an unscoped enumeration, yank all of its enumerators
2647 // out of the scope.
2648 if (auto *ED = dyn_cast<EnumDecl>(Val: New); ED && !ED->isScoped()) {
2649 Scope *EnumScope = getNonFieldDeclScope(S);
2650 for (auto *ECD : ED->enumerators()) {
2651 assert(EnumScope->isDeclScope(ECD));
2652 EnumScope->RemoveDecl(D: ECD);
2653 IdResolver.RemoveDecl(D: ECD);
2654 }
2655 }
2656}
2657
2658/// DeclhasAttr - returns true if decl Declaration already has the target
2659/// attribute.
2660static bool DeclHasAttr(const Decl *D, const Attr *A) {
2661 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(Val: A);
2662 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(Val: A);
2663 for (const auto *i : D->attrs())
2664 if (i->getKind() == A->getKind()) {
2665 if (Ann) {
2666 if (Ann->getAnnotation() == cast<AnnotateAttr>(Val: i)->getAnnotation())
2667 return true;
2668 continue;
2669 }
2670 // FIXME: Don't hardcode this check
2671 if (OA && isa<OwnershipAttr>(Val: i))
2672 return OA->getOwnKind() == cast<OwnershipAttr>(Val: i)->getOwnKind();
2673 return true;
2674 }
2675
2676 return false;
2677}
2678
2679static bool isAttributeTargetADefinition(Decl *D) {
2680 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D))
2681 return VD->isThisDeclarationADefinition();
2682 if (TagDecl *TD = dyn_cast<TagDecl>(Val: D))
2683 return TD->isCompleteDefinition() || TD->isBeingDefined();
2684 return true;
2685}
2686
2687/// Merge alignment attributes from \p Old to \p New, taking into account the
2688/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2689///
2690/// \return \c true if any attributes were added to \p New.
2691static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2692 // Look for alignas attributes on Old, and pick out whichever attribute
2693 // specifies the strictest alignment requirement.
2694 AlignedAttr *OldAlignasAttr = nullptr;
2695 AlignedAttr *OldStrictestAlignAttr = nullptr;
2696 unsigned OldAlign = 0;
2697 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2698 // FIXME: We have no way of representing inherited dependent alignments
2699 // in a case like:
2700 // template<int A, int B> struct alignas(A) X;
2701 // template<int A, int B> struct alignas(B) X {};
2702 // For now, we just ignore any alignas attributes which are not on the
2703 // definition in such a case.
2704 if (I->isAlignmentDependent())
2705 return false;
2706
2707 if (I->isAlignas())
2708 OldAlignasAttr = I;
2709
2710 unsigned Align = I->getAlignment(Ctx&: S.Context);
2711 if (Align > OldAlign) {
2712 OldAlign = Align;
2713 OldStrictestAlignAttr = I;
2714 }
2715 }
2716
2717 // Look for alignas attributes on New.
2718 AlignedAttr *NewAlignasAttr = nullptr;
2719 unsigned NewAlign = 0;
2720 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2721 if (I->isAlignmentDependent())
2722 return false;
2723
2724 if (I->isAlignas())
2725 NewAlignasAttr = I;
2726
2727 unsigned Align = I->getAlignment(Ctx&: S.Context);
2728 if (Align > NewAlign)
2729 NewAlign = Align;
2730 }
2731
2732 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2733 // Both declarations have 'alignas' attributes. We require them to match.
2734 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2735 // fall short. (If two declarations both have alignas, they must both match
2736 // every definition, and so must match each other if there is a definition.)
2737
2738 // If either declaration only contains 'alignas(0)' specifiers, then it
2739 // specifies the natural alignment for the type.
2740 if (OldAlign == 0 || NewAlign == 0) {
2741 QualType Ty;
2742 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: New))
2743 Ty = VD->getType();
2744 else
2745 Ty = S.Context.getTagDeclType(Decl: cast<TagDecl>(Val: New));
2746
2747 if (OldAlign == 0)
2748 OldAlign = S.Context.getTypeAlign(T: Ty);
2749 if (NewAlign == 0)
2750 NewAlign = S.Context.getTypeAlign(T: Ty);
2751 }
2752
2753 if (OldAlign != NewAlign) {
2754 S.Diag(Loc: NewAlignasAttr->getLocation(), DiagID: diag::err_alignas_mismatch)
2755 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: OldAlign).getQuantity()
2756 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: NewAlign).getQuantity();
2757 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_previous_declaration);
2758 }
2759 }
2760
2761 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(D: New)) {
2762 // C++11 [dcl.align]p6:
2763 // if any declaration of an entity has an alignment-specifier,
2764 // every defining declaration of that entity shall specify an
2765 // equivalent alignment.
2766 // C11 6.7.5/7:
2767 // If the definition of an object does not have an alignment
2768 // specifier, any other declaration of that object shall also
2769 // have no alignment specifier.
2770 S.Diag(Loc: New->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
2771 << OldAlignasAttr;
2772 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_alignas_on_declaration)
2773 << OldAlignasAttr;
2774 }
2775
2776 bool AnyAdded = false;
2777
2778 // Ensure we have an attribute representing the strictest alignment.
2779 if (OldAlign > NewAlign) {
2780 AlignedAttr *Clone = OldStrictestAlignAttr->clone(C&: S.Context);
2781 Clone->setInherited(true);
2782 New->addAttr(A: Clone);
2783 AnyAdded = true;
2784 }
2785
2786 // Ensure we have an alignas attribute if the old declaration had one.
2787 if (OldAlignasAttr && !NewAlignasAttr &&
2788 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2789 AlignedAttr *Clone = OldAlignasAttr->clone(C&: S.Context);
2790 Clone->setInherited(true);
2791 New->addAttr(A: Clone);
2792 AnyAdded = true;
2793 }
2794
2795 return AnyAdded;
2796}
2797
2798#define WANT_DECL_MERGE_LOGIC
2799#include "clang/Sema/AttrParsedAttrImpl.inc"
2800#undef WANT_DECL_MERGE_LOGIC
2801
2802static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2803 const InheritableAttr *Attr,
2804 AvailabilityMergeKind AMK) {
2805 // Diagnose any mutual exclusions between the attribute that we want to add
2806 // and attributes that already exist on the declaration.
2807 if (!DiagnoseMutualExclusions(S, D, A: Attr))
2808 return false;
2809
2810 // This function copies an attribute Attr from a previous declaration to the
2811 // new declaration D if the new declaration doesn't itself have that attribute
2812 // yet or if that attribute allows duplicates.
2813 // If you're adding a new attribute that requires logic different from
2814 // "use explicit attribute on decl if present, else use attribute from
2815 // previous decl", for example if the attribute needs to be consistent
2816 // between redeclarations, you need to call a custom merge function here.
2817 InheritableAttr *NewAttr = nullptr;
2818 if (const auto *AA = dyn_cast<AvailabilityAttr>(Val: Attr))
2819 NewAttr = S.mergeAvailabilityAttr(
2820 D, CI: *AA, Platform: AA->getPlatform(), Implicit: AA->isImplicit(), Introduced: AA->getIntroduced(),
2821 Deprecated: AA->getDeprecated(), Obsoleted: AA->getObsoleted(), IsUnavailable: AA->getUnavailable(),
2822 Message: AA->getMessage(), IsStrict: AA->getStrict(), Replacement: AA->getReplacement(), AMK,
2823 Priority: AA->getPriority(), IIEnvironment: AA->getEnvironment());
2824 else if (const auto *VA = dyn_cast<VisibilityAttr>(Val: Attr))
2825 NewAttr = S.mergeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2826 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Val: Attr))
2827 NewAttr = S.mergeTypeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2828 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Val: Attr))
2829 NewAttr = S.mergeDLLImportAttr(D, CI: *ImportA);
2830 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Val: Attr))
2831 NewAttr = S.mergeDLLExportAttr(D, CI: *ExportA);
2832 else if (const auto *EA = dyn_cast<ErrorAttr>(Val: Attr))
2833 NewAttr = S.mergeErrorAttr(D, CI: *EA, NewUserDiagnostic: EA->getUserDiagnostic());
2834 else if (const auto *FA = dyn_cast<FormatAttr>(Val: Attr))
2835 NewAttr = S.mergeFormatAttr(D, CI: *FA, Format: FA->getType(), FormatIdx: FA->getFormatIdx(),
2836 FirstArg: FA->getFirstArg());
2837 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Val: Attr))
2838 NewAttr = S.mergeFormatMatchesAttr(
2839 D, CI: *FMA, Format: FMA->getType(), FormatIdx: FMA->getFormatIdx(), FormatStr: FMA->getFormatString());
2840 else if (const auto *SA = dyn_cast<SectionAttr>(Val: Attr))
2841 NewAttr = S.mergeSectionAttr(D, CI: *SA, Name: SA->getName());
2842 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Val: Attr))
2843 NewAttr = S.mergeCodeSegAttr(D, CI: *CSA, Name: CSA->getName());
2844 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Val: Attr))
2845 NewAttr = S.mergeMSInheritanceAttr(D, CI: *IA, BestCase: IA->getBestCase(),
2846 Model: IA->getInheritanceModel());
2847 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Val: Attr))
2848 NewAttr = S.mergeAlwaysInlineAttr(D, CI: *AA,
2849 Ident: &S.Context.Idents.get(Name: AA->getSpelling()));
2850 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(Val: D) &&
2851 (isa<CUDAHostAttr>(Val: Attr) || isa<CUDADeviceAttr>(Val: Attr) ||
2852 isa<CUDAGlobalAttr>(Val: Attr))) {
2853 // CUDA target attributes are part of function signature for
2854 // overloading purposes and must not be merged.
2855 return false;
2856 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Val: Attr))
2857 NewAttr = S.mergeMinSizeAttr(D, CI: *MA);
2858 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Val: Attr))
2859 NewAttr = S.Swift().mergeNameAttr(D, SNA: *SNA, Name: SNA->getName());
2860 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Val: Attr))
2861 NewAttr = S.mergeOptimizeNoneAttr(D, CI: *OA);
2862 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Val: Attr))
2863 NewAttr = S.mergeInternalLinkageAttr(D, AL: *InternalLinkageA);
2864 else if (isa<AlignedAttr>(Val: Attr))
2865 // AlignedAttrs are handled separately, because we need to handle all
2866 // such attributes on a declaration at the same time.
2867 NewAttr = nullptr;
2868 else if ((isa<DeprecatedAttr>(Val: Attr) || isa<UnavailableAttr>(Val: Attr)) &&
2869 (AMK == AvailabilityMergeKind::Override ||
2870 AMK == AvailabilityMergeKind::ProtocolImplementation ||
2871 AMK == AvailabilityMergeKind::OptionalProtocolImplementation))
2872 NewAttr = nullptr;
2873 else if (const auto *UA = dyn_cast<UuidAttr>(Val: Attr))
2874 NewAttr = S.mergeUuidAttr(D, CI: *UA, UuidAsWritten: UA->getGuid(), GuidDecl: UA->getGuidDecl());
2875 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Val: Attr))
2876 NewAttr = S.Wasm().mergeImportModuleAttr(D, AL: *IMA);
2877 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Val: Attr))
2878 NewAttr = S.Wasm().mergeImportNameAttr(D, AL: *INA);
2879 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Val: Attr))
2880 NewAttr = S.mergeEnforceTCBAttr(D, AL: *TCBA);
2881 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Val: Attr))
2882 NewAttr = S.mergeEnforceTCBLeafAttr(D, AL: *TCBLA);
2883 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Val: Attr))
2884 NewAttr = S.mergeBTFDeclTagAttr(D, AL: *BTFA);
2885 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Val: Attr))
2886 NewAttr = S.HLSL().mergeNumThreadsAttr(D, AL: *NT, X: NT->getX(), Y: NT->getY(),
2887 Z: NT->getZ());
2888 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Val: Attr))
2889 NewAttr = S.HLSL().mergeWaveSizeAttr(D, AL: *WS, Min: WS->getMin(), Max: WS->getMax(),
2890 Preferred: WS->getPreferred(),
2891 SpelledArgsCount: WS->getSpelledArgsCount());
2892 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Val: Attr))
2893 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, AL: *CI, Id: CI->getId());
2894 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Val: Attr))
2895 NewAttr = S.HLSL().mergeShaderAttr(D, AL: *SA, ShaderType: SA->getType());
2896 else if (isa<SuppressAttr>(Val: Attr))
2897 // Do nothing. Each redeclaration should be suppressed separately.
2898 NewAttr = nullptr;
2899 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Val: Attr))
2900 NewAttr = S.OpenACC().mergeRoutineDeclAttr(Old: *RD);
2901 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, A: Attr))
2902 NewAttr = cast<InheritableAttr>(Val: Attr->clone(C&: S.Context));
2903
2904 if (NewAttr) {
2905 NewAttr->setInherited(true);
2906 D->addAttr(A: NewAttr);
2907 if (isa<MSInheritanceAttr>(Val: NewAttr))
2908 S.Consumer.AssignInheritanceModel(RD: cast<CXXRecordDecl>(Val: D));
2909 return true;
2910 }
2911
2912 return false;
2913}
2914
2915static const NamedDecl *getDefinition(const Decl *D) {
2916 if (const TagDecl *TD = dyn_cast<TagDecl>(Val: D))
2917 return TD->getDefinition();
2918 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2919 const VarDecl *Def = VD->getDefinition();
2920 if (Def)
2921 return Def;
2922 return VD->getActingDefinition();
2923 }
2924 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
2925 const FunctionDecl *Def = nullptr;
2926 if (FD->isDefined(Definition&: Def, CheckForPendingFriendDefinition: true))
2927 return Def;
2928 }
2929 return nullptr;
2930}
2931
2932static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2933 for (const auto *Attribute : D->attrs())
2934 if (Attribute->getKind() == Kind)
2935 return true;
2936 return false;
2937}
2938
2939/// checkNewAttributesAfterDef - If we already have a definition, check that
2940/// there are no new attributes in this declaration.
2941static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2942 if (!New->hasAttrs())
2943 return;
2944
2945 const NamedDecl *Def = getDefinition(D: Old);
2946 if (!Def || Def == New)
2947 return;
2948
2949 AttrVec &NewAttributes = New->getAttrs();
2950 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2951 Attr *NewAttribute = NewAttributes[I];
2952
2953 if (isa<AliasAttr>(Val: NewAttribute) || isa<IFuncAttr>(Val: NewAttribute)) {
2954 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: New)) {
2955 SkipBodyInfo SkipBody;
2956 S.CheckForFunctionRedefinition(FD, EffectiveDefinition: cast<FunctionDecl>(Val: Def), SkipBody: &SkipBody);
2957
2958 // If we're skipping this definition, drop the "alias" attribute.
2959 if (SkipBody.ShouldSkip) {
2960 NewAttributes.erase(CI: NewAttributes.begin() + I);
2961 --E;
2962 continue;
2963 }
2964 } else {
2965 VarDecl *VD = cast<VarDecl>(Val: New);
2966 unsigned Diag = cast<VarDecl>(Val: Def)->isThisDeclarationADefinition() ==
2967 VarDecl::TentativeDefinition
2968 ? diag::err_alias_after_tentative
2969 : diag::err_redefinition;
2970 S.Diag(Loc: VD->getLocation(), DiagID: Diag) << VD->getDeclName();
2971 if (Diag == diag::err_redefinition)
2972 S.notePreviousDefinition(Old: Def, New: VD->getLocation());
2973 else
2974 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
2975 VD->setInvalidDecl();
2976 }
2977 ++I;
2978 continue;
2979 }
2980
2981 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: Def)) {
2982 // Tentative definitions are only interesting for the alias check above.
2983 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2984 ++I;
2985 continue;
2986 }
2987 }
2988
2989 if (hasAttribute(D: Def, Kind: NewAttribute->getKind())) {
2990 ++I;
2991 continue; // regular attr merging will take care of validating this.
2992 }
2993
2994 if (isa<C11NoReturnAttr>(Val: NewAttribute)) {
2995 // C's _Noreturn is allowed to be added to a function after it is defined.
2996 ++I;
2997 continue;
2998 } else if (isa<UuidAttr>(Val: NewAttribute)) {
2999 // msvc will allow a subsequent definition to add an uuid to a class
3000 ++I;
3001 continue;
3002 } else if (isa<DeprecatedAttr, WarnUnusedResultAttr, UnusedAttr>(
3003 Val: NewAttribute) &&
3004 NewAttribute->isStandardAttributeSyntax()) {
3005 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3006 // deprecated attribute can later be re-declared with the attribute and
3007 // vice-versa.
3008 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3009 // maybe_unused attribute can later be redeclared with the attribute and
3010 // vice versa.
3011 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3012 // nodiscard attribute can later be redeclared with the attribute and
3013 // vice-versa.
3014 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3015 ++I;
3016 continue;
3017 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(Val: NewAttribute)) {
3018 if (AA->isAlignas()) {
3019 // C++11 [dcl.align]p6:
3020 // if any declaration of an entity has an alignment-specifier,
3021 // every defining declaration of that entity shall specify an
3022 // equivalent alignment.
3023 // C11 6.7.5/7:
3024 // If the definition of an object does not have an alignment
3025 // specifier, any other declaration of that object shall also
3026 // have no alignment specifier.
3027 S.Diag(Loc: Def->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
3028 << AA;
3029 S.Diag(Loc: NewAttribute->getLocation(), DiagID: diag::note_alignas_on_declaration)
3030 << AA;
3031 NewAttributes.erase(CI: NewAttributes.begin() + I);
3032 --E;
3033 continue;
3034 }
3035 } else if (isa<LoaderUninitializedAttr>(Val: NewAttribute)) {
3036 // If there is a C definition followed by a redeclaration with this
3037 // attribute then there are two different definitions. In C++, prefer the
3038 // standard diagnostics.
3039 if (!S.getLangOpts().CPlusPlus) {
3040 S.Diag(Loc: NewAttribute->getLocation(),
3041 DiagID: diag::err_loader_uninitialized_redeclaration);
3042 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3043 NewAttributes.erase(CI: NewAttributes.begin() + I);
3044 --E;
3045 continue;
3046 }
3047 } else if (isa<SelectAnyAttr>(Val: NewAttribute) &&
3048 cast<VarDecl>(Val: New)->isInline() &&
3049 !cast<VarDecl>(Val: New)->isInlineSpecified()) {
3050 // Don't warn about applying selectany to implicitly inline variables.
3051 // Older compilers and language modes would require the use of selectany
3052 // to make such variables inline, and it would have no effect if we
3053 // honored it.
3054 ++I;
3055 continue;
3056 } else if (isa<OMPDeclareVariantAttr>(Val: NewAttribute)) {
3057 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3058 // declarations after definitions.
3059 ++I;
3060 continue;
3061 } else if (isa<SYCLKernelEntryPointAttr>(Val: NewAttribute)) {
3062 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3063 // error since the definition will have already been created without
3064 // the semantic effects of the attribute having been applied.
3065 S.Diag(Loc: NewAttribute->getLocation(),
3066 DiagID: diag::err_sycl_entry_point_after_definition);
3067 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3068 cast<SYCLKernelEntryPointAttr>(Val: NewAttribute)->setInvalidAttr();
3069 ++I;
3070 continue;
3071 }
3072
3073 S.Diag(Loc: NewAttribute->getLocation(),
3074 DiagID: diag::warn_attribute_precede_definition);
3075 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3076 NewAttributes.erase(CI: NewAttributes.begin() + I);
3077 --E;
3078 }
3079}
3080
3081static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3082 const ConstInitAttr *CIAttr,
3083 bool AttrBeforeInit) {
3084 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3085
3086 // Figure out a good way to write this specifier on the old declaration.
3087 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3088 // enough of the attribute list spelling information to extract that without
3089 // heroics.
3090 std::string SuitableSpelling;
3091 if (S.getLangOpts().CPlusPlus20)
3092 SuitableSpelling = std::string(
3093 S.PP.getLastMacroWithSpelling(Loc: InsertLoc, Tokens: {tok::kw_constinit}));
3094 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3095 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3096 Loc: InsertLoc, Tokens: {tok::l_square, tok::l_square,
3097 S.PP.getIdentifierInfo(Name: "clang"), tok::coloncolon,
3098 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3099 tok::r_square, tok::r_square}));
3100 if (SuitableSpelling.empty())
3101 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3102 Loc: InsertLoc, Tokens: {tok::kw___attribute, tok::l_paren, tok::r_paren,
3103 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3104 tok::r_paren, tok::r_paren}));
3105 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3106 SuitableSpelling = "constinit";
3107 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3108 SuitableSpelling = "[[clang::require_constant_initialization]]";
3109 if (SuitableSpelling.empty())
3110 SuitableSpelling = "__attribute__((require_constant_initialization))";
3111 SuitableSpelling += " ";
3112
3113 if (AttrBeforeInit) {
3114 // extern constinit int a;
3115 // int a = 0; // error (missing 'constinit'), accepted as extension
3116 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3117 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::ext_constinit_missing)
3118 << InitDecl << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3119 S.Diag(Loc: CIAttr->getLocation(), DiagID: diag::note_constinit_specified_here);
3120 } else {
3121 // int a = 0;
3122 // constinit extern int a; // error (missing 'constinit')
3123 S.Diag(Loc: CIAttr->getLocation(),
3124 DiagID: CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3125 : diag::warn_require_const_init_added_too_late)
3126 << FixItHint::CreateRemoval(RemoveRange: SourceRange(CIAttr->getLocation()));
3127 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::note_constinit_missing_here)
3128 << CIAttr->isConstinit()
3129 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3130 }
3131}
3132
3133void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3134 AvailabilityMergeKind AMK) {
3135 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3136 UsedAttr *NewAttr = OldAttr->clone(C&: Context);
3137 NewAttr->setInherited(true);
3138 New->addAttr(A: NewAttr);
3139 }
3140 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3141 RetainAttr *NewAttr = OldAttr->clone(C&: Context);
3142 NewAttr->setInherited(true);
3143 New->addAttr(A: NewAttr);
3144 }
3145
3146 if (!Old->hasAttrs() && !New->hasAttrs())
3147 return;
3148
3149 // [dcl.constinit]p1:
3150 // If the [constinit] specifier is applied to any declaration of a
3151 // variable, it shall be applied to the initializing declaration.
3152 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3153 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3154 if (bool(OldConstInit) != bool(NewConstInit)) {
3155 const auto *OldVD = cast<VarDecl>(Val: Old);
3156 auto *NewVD = cast<VarDecl>(Val: New);
3157
3158 // Find the initializing declaration. Note that we might not have linked
3159 // the new declaration into the redeclaration chain yet.
3160 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3161 if (!InitDecl &&
3162 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3163 InitDecl = NewVD;
3164
3165 if (InitDecl == NewVD) {
3166 // This is the initializing declaration. If it would inherit 'constinit',
3167 // that's ill-formed. (Note that we do not apply this to the attribute
3168 // form).
3169 if (OldConstInit && OldConstInit->isConstinit())
3170 diagnoseMissingConstinit(S&: *this, InitDecl: NewVD, CIAttr: OldConstInit,
3171 /*AttrBeforeInit=*/true);
3172 } else if (NewConstInit) {
3173 // This is the first time we've been told that this declaration should
3174 // have a constant initializer. If we already saw the initializing
3175 // declaration, this is too late.
3176 if (InitDecl && InitDecl != NewVD) {
3177 diagnoseMissingConstinit(S&: *this, InitDecl, CIAttr: NewConstInit,
3178 /*AttrBeforeInit=*/false);
3179 NewVD->dropAttr<ConstInitAttr>();
3180 }
3181 }
3182 }
3183
3184 // Attributes declared post-definition are currently ignored.
3185 checkNewAttributesAfterDef(S&: *this, New, Old);
3186
3187 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3188 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3189 if (!OldA->isEquivalent(Other: NewA)) {
3190 // This redeclaration changes __asm__ label.
3191 Diag(Loc: New->getLocation(), DiagID: diag::err_different_asm_label);
3192 Diag(Loc: OldA->getLocation(), DiagID: diag::note_previous_declaration);
3193 }
3194 } else if (Old->isUsed()) {
3195 // This redeclaration adds an __asm__ label to a declaration that has
3196 // already been ODR-used.
3197 Diag(Loc: New->getLocation(), DiagID: diag::err_late_asm_label_name)
3198 << isa<FunctionDecl>(Val: Old) << New->getAttr<AsmLabelAttr>()->getRange();
3199 }
3200 }
3201
3202 // Re-declaration cannot add abi_tag's.
3203 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3204 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3205 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3206 if (!llvm::is_contained(Range: OldAbiTagAttr->tags(), Element: NewTag)) {
3207 Diag(Loc: NewAbiTagAttr->getLocation(),
3208 DiagID: diag::err_new_abi_tag_on_redeclaration)
3209 << NewTag;
3210 Diag(Loc: OldAbiTagAttr->getLocation(), DiagID: diag::note_previous_declaration);
3211 }
3212 }
3213 } else {
3214 Diag(Loc: NewAbiTagAttr->getLocation(), DiagID: diag::err_abi_tag_on_redeclaration);
3215 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3216 }
3217 }
3218
3219 // This redeclaration adds a section attribute.
3220 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3221 if (auto *VD = dyn_cast<VarDecl>(Val: New)) {
3222 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3223 Diag(Loc: New->getLocation(), DiagID: diag::warn_attribute_section_on_redeclaration);
3224 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3225 }
3226 }
3227 }
3228
3229 // Redeclaration adds code-seg attribute.
3230 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3231 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3232 !NewCSA->isImplicit() && isa<CXXMethodDecl>(Val: New)) {
3233 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_section)
3234 << 0 /*codeseg*/;
3235 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3236 }
3237
3238 if (!Old->hasAttrs())
3239 return;
3240
3241 bool foundAny = New->hasAttrs();
3242
3243 // Ensure that any moving of objects within the allocated map is done before
3244 // we process them.
3245 if (!foundAny) New->setAttrs(AttrVec());
3246
3247 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3248 // Ignore deprecated/unavailable/availability attributes if requested.
3249 AvailabilityMergeKind LocalAMK = AvailabilityMergeKind::None;
3250 if (isa<DeprecatedAttr>(Val: I) ||
3251 isa<UnavailableAttr>(Val: I) ||
3252 isa<AvailabilityAttr>(Val: I)) {
3253 switch (AMK) {
3254 case AvailabilityMergeKind::None:
3255 continue;
3256
3257 case AvailabilityMergeKind::Redeclaration:
3258 case AvailabilityMergeKind::Override:
3259 case AvailabilityMergeKind::ProtocolImplementation:
3260 case AvailabilityMergeKind::OptionalProtocolImplementation:
3261 LocalAMK = AMK;
3262 break;
3263 }
3264 }
3265
3266 // Already handled.
3267 if (isa<UsedAttr>(Val: I) || isa<RetainAttr>(Val: I))
3268 continue;
3269
3270 if (isa<InferredNoReturnAttr>(Val: I)) {
3271 if (auto *FD = dyn_cast<FunctionDecl>(Val: New)) {
3272 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3273 continue; // Don't propagate inferred noreturn attributes to explicit
3274 // specializations.
3275 }
3276 }
3277
3278 if (mergeDeclAttribute(S&: *this, D: New, Attr: I, AMK: LocalAMK))
3279 foundAny = true;
3280 }
3281
3282 if (mergeAlignedAttrs(S&: *this, New, Old))
3283 foundAny = true;
3284
3285 if (!foundAny) New->dropAttrs();
3286}
3287
3288// Returns the number of added attributes.
3289template <class T>
3290static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3291 Sema &S) {
3292 unsigned found = 0;
3293 for (const auto *I : From->specific_attrs<T>()) {
3294 if (!DeclHasAttr(To, I)) {
3295 T *newAttr = cast<T>(I->clone(S.Context));
3296 newAttr->setInherited(true);
3297 To->addAttr(A: newAttr);
3298 ++found;
3299 }
3300 }
3301 return found;
3302}
3303
3304template <class F>
3305static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3306 F &&propagator) {
3307 if (!From->hasAttrs()) {
3308 return;
3309 }
3310
3311 bool foundAny = To->hasAttrs();
3312
3313 // Ensure that any moving of objects within the allocated map is
3314 // done before we process them.
3315 if (!foundAny)
3316 To->setAttrs(AttrVec());
3317
3318 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3319
3320 if (!foundAny)
3321 To->dropAttrs();
3322}
3323
3324/// mergeParamDeclAttributes - Copy attributes from the old parameter
3325/// to the new one.
3326static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3327 const ParmVarDecl *oldDecl,
3328 Sema &S) {
3329 // C++11 [dcl.attr.depend]p2:
3330 // The first declaration of a function shall specify the
3331 // carries_dependency attribute for its declarator-id if any declaration
3332 // of the function specifies the carries_dependency attribute.
3333 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3334 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3335 S.Diag(Loc: CDA->getLocation(),
3336 DiagID: diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3337 // Find the first declaration of the parameter.
3338 // FIXME: Should we build redeclaration chains for function parameters?
3339 const FunctionDecl *FirstFD =
3340 cast<FunctionDecl>(Val: oldDecl->getDeclContext())->getFirstDecl();
3341 const ParmVarDecl *FirstVD =
3342 FirstFD->getParamDecl(i: oldDecl->getFunctionScopeIndex());
3343 S.Diag(Loc: FirstVD->getLocation(),
3344 DiagID: diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3345 }
3346
3347 propagateAttributes(
3348 To: newDecl, From: oldDecl, propagator: [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3349 unsigned found = 0;
3350 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3351 // Propagate the lifetimebound attribute from parameters to the
3352 // most recent declaration. Note that this doesn't include the implicit
3353 // 'this' parameter, as the attribute is applied to the function type in
3354 // that case.
3355 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3356 return found;
3357 });
3358}
3359
3360static bool EquivalentArrayTypes(QualType Old, QualType New,
3361 const ASTContext &Ctx) {
3362
3363 auto NoSizeInfo = [&Ctx](QualType Ty) {
3364 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3365 return true;
3366 if (const auto *VAT = Ctx.getAsVariableArrayType(T: Ty))
3367 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3368 return false;
3369 };
3370
3371 // `type[]` is equivalent to `type *` and `type[*]`.
3372 if (NoSizeInfo(Old) && NoSizeInfo(New))
3373 return true;
3374
3375 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3376 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3377 const auto *OldVAT = Ctx.getAsVariableArrayType(T: Old);
3378 const auto *NewVAT = Ctx.getAsVariableArrayType(T: New);
3379 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3380 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3381 return false;
3382 return true;
3383 }
3384
3385 // Only compare size, ignore Size modifiers and CVR.
3386 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3387 return Ctx.getAsConstantArrayType(T: Old)->getSize() ==
3388 Ctx.getAsConstantArrayType(T: New)->getSize();
3389 }
3390
3391 // Don't try to compare dependent sized array
3392 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3393 return true;
3394 }
3395
3396 return Old == New;
3397}
3398
3399static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3400 const ParmVarDecl *OldParam,
3401 Sema &S) {
3402 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3403 if (auto Newnullability = NewParam->getType()->getNullability()) {
3404 if (*Oldnullability != *Newnullability) {
3405 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_mismatched_nullability_attr)
3406 << DiagNullabilityKind(
3407 *Newnullability,
3408 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3409 != 0))
3410 << DiagNullabilityKind(
3411 *Oldnullability,
3412 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3413 != 0));
3414 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration);
3415 }
3416 } else {
3417 QualType NewT = NewParam->getType();
3418 NewT = S.Context.getAttributedType(nullability: *Oldnullability, modifiedType: NewT, equivalentType: NewT);
3419 NewParam->setType(NewT);
3420 }
3421 }
3422 const auto *OldParamDT = dyn_cast<DecayedType>(Val: OldParam->getType());
3423 const auto *NewParamDT = dyn_cast<DecayedType>(Val: NewParam->getType());
3424 if (OldParamDT && NewParamDT &&
3425 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3426 QualType OldParamOT = OldParamDT->getOriginalType();
3427 QualType NewParamOT = NewParamDT->getOriginalType();
3428 if (!EquivalentArrayTypes(Old: OldParamOT, New: NewParamOT, Ctx: S.getASTContext())) {
3429 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_inconsistent_array_form)
3430 << NewParam << NewParamOT;
3431 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration_as)
3432 << OldParamOT;
3433 }
3434 }
3435}
3436
3437namespace {
3438
3439/// Used in MergeFunctionDecl to keep track of function parameters in
3440/// C.
3441struct GNUCompatibleParamWarning {
3442 ParmVarDecl *OldParm;
3443 ParmVarDecl *NewParm;
3444 QualType PromotedType;
3445};
3446
3447} // end anonymous namespace
3448
3449// Determine whether the previous declaration was a definition, implicit
3450// declaration, or a declaration.
3451template <typename T>
3452static std::pair<diag::kind, SourceLocation>
3453getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3454 diag::kind PrevDiag;
3455 SourceLocation OldLocation = Old->getLocation();
3456 if (Old->isThisDeclarationADefinition())
3457 PrevDiag = diag::note_previous_definition;
3458 else if (Old->isImplicit()) {
3459 PrevDiag = diag::note_previous_implicit_declaration;
3460 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3461 if (FD->getBuiltinID())
3462 PrevDiag = diag::note_previous_builtin_declaration;
3463 }
3464 if (OldLocation.isInvalid())
3465 OldLocation = New->getLocation();
3466 } else
3467 PrevDiag = diag::note_previous_declaration;
3468 return std::make_pair(x&: PrevDiag, y&: OldLocation);
3469}
3470
3471/// canRedefineFunction - checks if a function can be redefined. Currently,
3472/// only extern inline functions can be redefined, and even then only in
3473/// GNU89 mode.
3474static bool canRedefineFunction(const FunctionDecl *FD,
3475 const LangOptions& LangOpts) {
3476 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3477 !LangOpts.CPlusPlus &&
3478 FD->isInlineSpecified() &&
3479 FD->getStorageClass() == SC_Extern);
3480}
3481
3482const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3483 const AttributedType *AT = T->getAs<AttributedType>();
3484 while (AT && !AT->isCallingConv())
3485 AT = AT->getModifiedType()->getAs<AttributedType>();
3486 return AT;
3487}
3488
3489template <typename T>
3490static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3491 const DeclContext *DC = Old->getDeclContext();
3492 if (DC->isRecord())
3493 return false;
3494
3495 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3496 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3497 return true;
3498 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3499 return true;
3500 return false;
3501}
3502
3503template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3504static bool isExternC(VarTemplateDecl *) { return false; }
3505static bool isExternC(FunctionTemplateDecl *) { return false; }
3506
3507/// Check whether a redeclaration of an entity introduced by a
3508/// using-declaration is valid, given that we know it's not an overload
3509/// (nor a hidden tag declaration).
3510template<typename ExpectedDecl>
3511static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3512 ExpectedDecl *New) {
3513 // C++11 [basic.scope.declarative]p4:
3514 // Given a set of declarations in a single declarative region, each of
3515 // which specifies the same unqualified name,
3516 // -- they shall all refer to the same entity, or all refer to functions
3517 // and function templates; or
3518 // -- exactly one declaration shall declare a class name or enumeration
3519 // name that is not a typedef name and the other declarations shall all
3520 // refer to the same variable or enumerator, or all refer to functions
3521 // and function templates; in this case the class name or enumeration
3522 // name is hidden (3.3.10).
3523
3524 // C++11 [namespace.udecl]p14:
3525 // If a function declaration in namespace scope or block scope has the
3526 // same name and the same parameter-type-list as a function introduced
3527 // by a using-declaration, and the declarations do not declare the same
3528 // function, the program is ill-formed.
3529
3530 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3531 if (Old &&
3532 !Old->getDeclContext()->getRedeclContext()->Equals(
3533 New->getDeclContext()->getRedeclContext()) &&
3534 !(isExternC(Old) && isExternC(New)))
3535 Old = nullptr;
3536
3537 if (!Old) {
3538 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3539 S.Diag(Loc: OldS->getTargetDecl()->getLocation(), DiagID: diag::note_using_decl_target);
3540 S.Diag(Loc: OldS->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
3541 return true;
3542 }
3543 return false;
3544}
3545
3546static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3547 const FunctionDecl *B) {
3548 assert(A->getNumParams() == B->getNumParams());
3549
3550 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3551 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3552 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3553 if (AttrA == AttrB)
3554 return true;
3555 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3556 AttrA->isDynamic() == AttrB->isDynamic();
3557 };
3558
3559 return std::equal(first1: A->param_begin(), last1: A->param_end(), first2: B->param_begin(), binary_pred: AttrEq);
3560}
3561
3562/// If necessary, adjust the semantic declaration context for a qualified
3563/// declaration to name the correct inline namespace within the qualifier.
3564static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3565 DeclaratorDecl *OldD) {
3566 // The only case where we need to update the DeclContext is when
3567 // redeclaration lookup for a qualified name finds a declaration
3568 // in an inline namespace within the context named by the qualifier:
3569 //
3570 // inline namespace N { int f(); }
3571 // int ::f(); // Sema DC needs adjusting from :: to N::.
3572 //
3573 // For unqualified declarations, the semantic context *can* change
3574 // along the redeclaration chain (for local extern declarations,
3575 // extern "C" declarations, and friend declarations in particular).
3576 if (!NewD->getQualifier())
3577 return;
3578
3579 // NewD is probably already in the right context.
3580 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3581 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3582 if (NamedDC->Equals(DC: SemaDC))
3583 return;
3584
3585 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3586 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3587 "unexpected context for redeclaration");
3588
3589 auto *LexDC = NewD->getLexicalDeclContext();
3590 auto FixSemaDC = [=](NamedDecl *D) {
3591 if (!D)
3592 return;
3593 D->setDeclContext(SemaDC);
3594 D->setLexicalDeclContext(LexDC);
3595 };
3596
3597 FixSemaDC(NewD);
3598 if (auto *FD = dyn_cast<FunctionDecl>(Val: NewD))
3599 FixSemaDC(FD->getDescribedFunctionTemplate());
3600 else if (auto *VD = dyn_cast<VarDecl>(Val: NewD))
3601 FixSemaDC(VD->getDescribedVarTemplate());
3602}
3603
3604bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3605 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3606 // Verify the old decl was also a function.
3607 FunctionDecl *Old = OldD->getAsFunction();
3608 if (!Old) {
3609 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: OldD)) {
3610 if (New->getFriendObjectKind()) {
3611 Diag(Loc: New->getLocation(), DiagID: diag::err_using_decl_friend);
3612 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
3613 DiagID: diag::note_using_decl_target);
3614 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
3615 << 0;
3616 return true;
3617 }
3618
3619 // Check whether the two declarations might declare the same function or
3620 // function template.
3621 if (FunctionTemplateDecl *NewTemplate =
3622 New->getDescribedFunctionTemplate()) {
3623 if (checkUsingShadowRedecl<FunctionTemplateDecl>(S&: *this, OldS: Shadow,
3624 New: NewTemplate))
3625 return true;
3626 OldD = Old = cast<FunctionTemplateDecl>(Val: Shadow->getTargetDecl())
3627 ->getAsFunction();
3628 } else {
3629 if (checkUsingShadowRedecl<FunctionDecl>(S&: *this, OldS: Shadow, New))
3630 return true;
3631 OldD = Old = cast<FunctionDecl>(Val: Shadow->getTargetDecl());
3632 }
3633 } else {
3634 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
3635 << New->getDeclName();
3636 notePreviousDefinition(Old: OldD, New: New->getLocation());
3637 return true;
3638 }
3639 }
3640
3641 // If the old declaration was found in an inline namespace and the new
3642 // declaration was qualified, update the DeclContext to match.
3643 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
3644
3645 // If the old declaration is invalid, just give up here.
3646 if (Old->isInvalidDecl())
3647 return true;
3648
3649 // Disallow redeclaration of some builtins.
3650 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3651 Diag(Loc: New->getLocation(), DiagID: diag::err_builtin_redeclare) << Old->getDeclName();
3652 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_builtin_declaration)
3653 << Old << Old->getType();
3654 return true;
3655 }
3656
3657 diag::kind PrevDiag;
3658 SourceLocation OldLocation;
3659 std::tie(args&: PrevDiag, args&: OldLocation) =
3660 getNoteDiagForInvalidRedeclaration(Old, New);
3661
3662 // Don't complain about this if we're in GNU89 mode and the old function
3663 // is an extern inline function.
3664 // Don't complain about specializations. They are not supposed to have
3665 // storage classes.
3666 if (!isa<CXXMethodDecl>(Val: New) && !isa<CXXMethodDecl>(Val: Old) &&
3667 New->getStorageClass() == SC_Static &&
3668 Old->hasExternalFormalLinkage() &&
3669 !New->getTemplateSpecializationInfo() &&
3670 !canRedefineFunction(FD: Old, LangOpts: getLangOpts())) {
3671 if (getLangOpts().MicrosoftExt) {
3672 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static) << New;
3673 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3674 } else {
3675 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static) << New;
3676 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3677 return true;
3678 }
3679 }
3680
3681 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3682 if (!Old->hasAttr<InternalLinkageAttr>()) {
3683 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
3684 << ILA;
3685 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3686 New->dropAttr<InternalLinkageAttr>();
3687 }
3688
3689 if (auto *EA = New->getAttr<ErrorAttr>()) {
3690 if (!Old->hasAttr<ErrorAttr>()) {
3691 Diag(Loc: EA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl) << EA;
3692 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3693 New->dropAttr<ErrorAttr>();
3694 }
3695 }
3696
3697 if (CheckRedeclarationInModule(New, Old))
3698 return true;
3699
3700 if (!getLangOpts().CPlusPlus) {
3701 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3702 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3703 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_overloadable_mismatch)
3704 << New << OldOvl;
3705
3706 // Try our best to find a decl that actually has the overloadable
3707 // attribute for the note. In most cases (e.g. programs with only one
3708 // broken declaration/definition), this won't matter.
3709 //
3710 // FIXME: We could do this if we juggled some extra state in
3711 // OverloadableAttr, rather than just removing it.
3712 const Decl *DiagOld = Old;
3713 if (OldOvl) {
3714 auto OldIter = llvm::find_if(Range: Old->redecls(), P: [](const Decl *D) {
3715 const auto *A = D->getAttr<OverloadableAttr>();
3716 return A && !A->isImplicit();
3717 });
3718 // If we've implicitly added *all* of the overloadable attrs to this
3719 // chain, emitting a "previous redecl" note is pointless.
3720 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3721 }
3722
3723 if (DiagOld)
3724 Diag(Loc: DiagOld->getLocation(),
3725 DiagID: diag::note_attribute_overloadable_prev_overload)
3726 << OldOvl;
3727
3728 if (OldOvl)
3729 New->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
3730 else
3731 New->dropAttr<OverloadableAttr>();
3732 }
3733 }
3734
3735 // It is not permitted to redeclare an SME function with different SME
3736 // attributes.
3737 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
3738 Diag(Loc: New->getLocation(), DiagID: diag::err_sme_attr_mismatch)
3739 << New->getType() << Old->getType();
3740 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3741 return true;
3742 }
3743
3744 // If a function is first declared with a calling convention, but is later
3745 // declared or defined without one, all following decls assume the calling
3746 // convention of the first.
3747 //
3748 // It's OK if a function is first declared without a calling convention,
3749 // but is later declared or defined with the default calling convention.
3750 //
3751 // To test if either decl has an explicit calling convention, we look for
3752 // AttributedType sugar nodes on the type as written. If they are missing or
3753 // were canonicalized away, we assume the calling convention was implicit.
3754 //
3755 // Note also that we DO NOT return at this point, because we still have
3756 // other tests to run.
3757 QualType OldQType = Context.getCanonicalType(T: Old->getType());
3758 QualType NewQType = Context.getCanonicalType(T: New->getType());
3759 const FunctionType *OldType = cast<FunctionType>(Val&: OldQType);
3760 const FunctionType *NewType = cast<FunctionType>(Val&: NewQType);
3761 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3762 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3763 bool RequiresAdjustment = false;
3764
3765 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3766 FunctionDecl *First = Old->getFirstDecl();
3767 const FunctionType *FT =
3768 First->getType().getCanonicalType()->castAs<FunctionType>();
3769 FunctionType::ExtInfo FI = FT->getExtInfo();
3770 bool NewCCExplicit = getCallingConvAttributedType(T: New->getType());
3771 if (!NewCCExplicit) {
3772 // Inherit the CC from the previous declaration if it was specified
3773 // there but not here.
3774 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3775 RequiresAdjustment = true;
3776 } else if (Old->getBuiltinID()) {
3777 // Builtin attribute isn't propagated to the new one yet at this point,
3778 // so we check if the old one is a builtin.
3779
3780 // Calling Conventions on a Builtin aren't really useful and setting a
3781 // default calling convention and cdecl'ing some builtin redeclarations is
3782 // common, so warn and ignore the calling convention on the redeclaration.
3783 Diag(Loc: New->getLocation(), DiagID: diag::warn_cconv_unsupported)
3784 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3785 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3786 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3787 RequiresAdjustment = true;
3788 } else {
3789 // Calling conventions aren't compatible, so complain.
3790 bool FirstCCExplicit = getCallingConvAttributedType(T: First->getType());
3791 Diag(Loc: New->getLocation(), DiagID: diag::err_cconv_change)
3792 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3793 << !FirstCCExplicit
3794 << (!FirstCCExplicit ? "" :
3795 FunctionType::getNameForCallConv(CC: FI.getCC()));
3796
3797 // Put the note on the first decl, since it is the one that matters.
3798 Diag(Loc: First->getLocation(), DiagID: diag::note_previous_declaration);
3799 return true;
3800 }
3801 }
3802
3803 // FIXME: diagnose the other way around?
3804 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3805 NewTypeInfo = NewTypeInfo.withNoReturn(noReturn: true);
3806 RequiresAdjustment = true;
3807 }
3808
3809 // Merge regparm attribute.
3810 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3811 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3812 if (NewTypeInfo.getHasRegParm()) {
3813 Diag(Loc: New->getLocation(), DiagID: diag::err_regparm_mismatch)
3814 << NewType->getRegParmType()
3815 << OldType->getRegParmType();
3816 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3817 return true;
3818 }
3819
3820 NewTypeInfo = NewTypeInfo.withRegParm(RegParm: OldTypeInfo.getRegParm());
3821 RequiresAdjustment = true;
3822 }
3823
3824 // Merge ns_returns_retained attribute.
3825 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3826 if (NewTypeInfo.getProducesResult()) {
3827 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch)
3828 << "'ns_returns_retained'";
3829 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3830 return true;
3831 }
3832
3833 NewTypeInfo = NewTypeInfo.withProducesResult(producesResult: true);
3834 RequiresAdjustment = true;
3835 }
3836
3837 if (OldTypeInfo.getNoCallerSavedRegs() !=
3838 NewTypeInfo.getNoCallerSavedRegs()) {
3839 if (NewTypeInfo.getNoCallerSavedRegs()) {
3840 AnyX86NoCallerSavedRegistersAttr *Attr =
3841 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3842 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch) << Attr;
3843 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3844 return true;
3845 }
3846
3847 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(noCallerSavedRegs: true);
3848 RequiresAdjustment = true;
3849 }
3850
3851 if (RequiresAdjustment) {
3852 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3853 AdjustedType = Context.adjustFunctionType(Fn: AdjustedType, EInfo: NewTypeInfo);
3854 New->setType(QualType(AdjustedType, 0));
3855 NewQType = Context.getCanonicalType(T: New->getType());
3856 }
3857
3858 // If this redeclaration makes the function inline, we may need to add it to
3859 // UndefinedButUsed.
3860 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
3861 !getLangOpts().GNUInline && Old->isUsed(CheckUsedAttr: false) && !Old->isDefined() &&
3862 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
3863 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
3864 y: SourceLocation()));
3865
3866 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3867 // about it.
3868 if (New->hasAttr<GNUInlineAttr>() &&
3869 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3870 UndefinedButUsed.erase(Key: Old->getCanonicalDecl());
3871 }
3872
3873 // If pass_object_size params don't match up perfectly, this isn't a valid
3874 // redeclaration.
3875 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3876 !hasIdenticalPassObjectSizeAttrs(A: Old, B: New)) {
3877 Diag(Loc: New->getLocation(), DiagID: diag::err_different_pass_object_size_params)
3878 << New->getDeclName();
3879 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3880 return true;
3881 }
3882
3883 QualType OldQTypeForComparison = OldQType;
3884 if (Context.hasAnyFunctionEffects()) {
3885 const auto OldFX = Old->getFunctionEffects();
3886 const auto NewFX = New->getFunctionEffects();
3887 if (OldFX != NewFX) {
3888 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
3889 for (const auto &Diff : Diffs) {
3890 if (Diff.shouldDiagnoseRedeclaration(OldFunction: *Old, OldFX, NewFunction: *New, NewFX)) {
3891 Diag(Loc: New->getLocation(),
3892 DiagID: diag::warn_mismatched_func_effect_redeclaration)
3893 << Diff.effectName();
3894 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3895 }
3896 }
3897 // Following a warning, we could skip merging effects from the previous
3898 // declaration, but that would trigger an additional "conflicting types"
3899 // error.
3900 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
3901 FunctionEffectSet::Conflicts MergeErrs;
3902 FunctionEffectSet MergedFX =
3903 FunctionEffectSet::getUnion(LHS: OldFX, RHS: NewFX, Errs&: MergeErrs);
3904 if (!MergeErrs.empty())
3905 diagnoseFunctionEffectMergeConflicts(Errs: MergeErrs, NewLoc: New->getLocation(),
3906 OldLoc: Old->getLocation());
3907
3908 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
3909 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3910 QualType ModQT = Context.getFunctionType(ResultTy: NewFPT->getReturnType(),
3911 Args: NewFPT->getParamTypes(), EPI);
3912
3913 New->setType(ModQT);
3914 NewQType = New->getType();
3915
3916 // Revise OldQTForComparison to include the merged effects,
3917 // so as not to fail due to differences later.
3918 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
3919 EPI = OldFPT->getExtProtoInfo();
3920 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3921 OldQTypeForComparison = Context.getFunctionType(
3922 ResultTy: OldFPT->getReturnType(), Args: OldFPT->getParamTypes(), EPI);
3923 }
3924 if (OldFX.empty()) {
3925 // A redeclaration may add the attribute to a previously seen function
3926 // body which needs to be verified.
3927 maybeAddDeclWithEffects(D: Old, FX: MergedFX);
3928 }
3929 }
3930 }
3931 }
3932
3933 if (getLangOpts().CPlusPlus) {
3934 OldQType = Context.getCanonicalType(T: Old->getType());
3935 NewQType = Context.getCanonicalType(T: New->getType());
3936
3937 // Go back to the type source info to compare the declared return types,
3938 // per C++1y [dcl.type.auto]p13:
3939 // Redeclarations or specializations of a function or function template
3940 // with a declared return type that uses a placeholder type shall also
3941 // use that placeholder, not a deduced type.
3942 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3943 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3944 if (!Context.hasSameType(T1: OldDeclaredReturnType, T2: NewDeclaredReturnType) &&
3945 canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewDeclaredReturnType,
3946 OldT: OldDeclaredReturnType)) {
3947 QualType ResQT;
3948 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3949 OldDeclaredReturnType->isObjCObjectPointerType())
3950 // FIXME: This does the wrong thing for a deduced return type.
3951 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3952 if (ResQT.isNull()) {
3953 if (New->isCXXClassMember() && New->isOutOfLine())
3954 Diag(Loc: New->getLocation(), DiagID: diag::err_member_def_does_not_match_ret_type)
3955 << New << New->getReturnTypeSourceRange();
3956 else if (Old->isExternC() && New->isExternC() &&
3957 !Old->hasAttr<OverloadableAttr>() &&
3958 !New->hasAttr<OverloadableAttr>())
3959 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
3960 else
3961 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_diff_return_type)
3962 << New->getReturnTypeSourceRange();
3963 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType()
3964 << Old->getReturnTypeSourceRange();
3965 return true;
3966 }
3967 else
3968 NewQType = ResQT;
3969 }
3970
3971 QualType OldReturnType = OldType->getReturnType();
3972 QualType NewReturnType = cast<FunctionType>(Val&: NewQType)->getReturnType();
3973 if (OldReturnType != NewReturnType) {
3974 // If this function has a deduced return type and has already been
3975 // defined, copy the deduced value from the old declaration.
3976 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3977 if (OldAT && OldAT->isDeduced()) {
3978 QualType DT = OldAT->getDeducedType();
3979 if (DT.isNull()) {
3980 New->setType(SubstAutoTypeDependent(TypeWithAuto: New->getType()));
3981 NewQType = Context.getCanonicalType(T: SubstAutoTypeDependent(TypeWithAuto: NewQType));
3982 } else {
3983 New->setType(SubstAutoType(TypeWithAuto: New->getType(), Replacement: DT));
3984 NewQType = Context.getCanonicalType(T: SubstAutoType(TypeWithAuto: NewQType, Replacement: DT));
3985 }
3986 }
3987 }
3988
3989 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
3990 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
3991 if (OldMethod && NewMethod) {
3992 // Preserve triviality.
3993 NewMethod->setTrivial(OldMethod->isTrivial());
3994
3995 // MSVC allows explicit template specialization at class scope:
3996 // 2 CXXMethodDecls referring to the same function will be injected.
3997 // We don't want a redeclaration error.
3998 bool IsClassScopeExplicitSpecialization =
3999 OldMethod->isFunctionTemplateSpecialization() &&
4000 NewMethod->isFunctionTemplateSpecialization();
4001 bool isFriend = NewMethod->getFriendObjectKind();
4002
4003 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4004 !IsClassScopeExplicitSpecialization) {
4005 // -- Member function declarations with the same name and the
4006 // same parameter types cannot be overloaded if any of them
4007 // is a static member function declaration.
4008 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4009 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_static_nonstatic_member);
4010 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4011 return true;
4012 }
4013
4014 // C++ [class.mem]p1:
4015 // [...] A member shall not be declared twice in the
4016 // member-specification, except that a nested class or member
4017 // class template can be declared and then later defined.
4018 if (!inTemplateInstantiation()) {
4019 unsigned NewDiag;
4020 if (isa<CXXConstructorDecl>(Val: OldMethod))
4021 NewDiag = diag::err_constructor_redeclared;
4022 else if (isa<CXXDestructorDecl>(Val: NewMethod))
4023 NewDiag = diag::err_destructor_redeclared;
4024 else if (isa<CXXConversionDecl>(Val: NewMethod))
4025 NewDiag = diag::err_conv_function_redeclared;
4026 else
4027 NewDiag = diag::err_member_redeclared;
4028
4029 Diag(Loc: New->getLocation(), DiagID: NewDiag);
4030 } else {
4031 Diag(Loc: New->getLocation(), DiagID: diag::err_member_redeclared_in_instantiation)
4032 << New << New->getType();
4033 }
4034 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4035 return true;
4036
4037 // Complain if this is an explicit declaration of a special
4038 // member that was initially declared implicitly.
4039 //
4040 // As an exception, it's okay to befriend such methods in order
4041 // to permit the implicit constructor/destructor/operator calls.
4042 } else if (OldMethod->isImplicit()) {
4043 if (isFriend) {
4044 NewMethod->setImplicit();
4045 } else {
4046 Diag(Loc: NewMethod->getLocation(),
4047 DiagID: diag::err_definition_of_implicitly_declared_member)
4048 << New << getSpecialMember(MD: OldMethod);
4049 return true;
4050 }
4051 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4052 Diag(Loc: NewMethod->getLocation(),
4053 DiagID: diag::err_definition_of_explicitly_defaulted_member)
4054 << getSpecialMember(MD: OldMethod);
4055 return true;
4056 }
4057 }
4058
4059 // C++1z [over.load]p2
4060 // Certain function declarations cannot be overloaded:
4061 // -- Function declarations that differ only in the return type,
4062 // the exception specification, or both cannot be overloaded.
4063
4064 // Check the exception specifications match. This may recompute the type of
4065 // both Old and New if it resolved exception specifications, so grab the
4066 // types again after this. Because this updates the type, we do this before
4067 // any of the other checks below, which may update the "de facto" NewQType
4068 // but do not necessarily update the type of New.
4069 if (CheckEquivalentExceptionSpec(Old, New))
4070 return true;
4071
4072 // C++11 [dcl.attr.noreturn]p1:
4073 // The first declaration of a function shall specify the noreturn
4074 // attribute if any declaration of that function specifies the noreturn
4075 // attribute.
4076 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4077 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4078 Diag(Loc: NRA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4079 << NRA;
4080 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4081 }
4082
4083 // C++11 [dcl.attr.depend]p2:
4084 // The first declaration of a function shall specify the
4085 // carries_dependency attribute for its declarator-id if any declaration
4086 // of the function specifies the carries_dependency attribute.
4087 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4088 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4089 Diag(Loc: CDA->getLocation(),
4090 DiagID: diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4091 Diag(Loc: Old->getFirstDecl()->getLocation(),
4092 DiagID: diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4093 }
4094
4095 // (C++98 8.3.5p3):
4096 // All declarations for a function shall agree exactly in both the
4097 // return type and the parameter-type-list.
4098 // We also want to respect all the extended bits except noreturn.
4099
4100 // noreturn should now match unless the old type info didn't have it.
4101 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4102 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4103 const FunctionType *OldTypeForComparison
4104 = Context.adjustFunctionType(Fn: OldType, EInfo: OldTypeInfo.withNoReturn(noReturn: true));
4105 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4106 assert(OldQTypeForComparison.isCanonical());
4107 }
4108
4109 if (haveIncompatibleLanguageLinkages(Old, New)) {
4110 // As a special case, retain the language linkage from previous
4111 // declarations of a friend function as an extension.
4112 //
4113 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4114 // and is useful because there's otherwise no way to specify language
4115 // linkage within class scope.
4116 //
4117 // Check cautiously as the friend object kind isn't yet complete.
4118 if (New->getFriendObjectKind() != Decl::FOK_None) {
4119 Diag(Loc: New->getLocation(), DiagID: diag::ext_retained_language_linkage) << New;
4120 Diag(Loc: OldLocation, DiagID: PrevDiag);
4121 } else {
4122 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4123 Diag(Loc: OldLocation, DiagID: PrevDiag);
4124 return true;
4125 }
4126 }
4127
4128 // HLSL check parameters for matching ABI specifications.
4129 if (getLangOpts().HLSL) {
4130 if (HLSL().CheckCompatibleParameterABI(New, Old))
4131 return true;
4132
4133 // If no errors are generated when checking parameter ABIs we can check if
4134 // the two declarations have the same type ignoring the ABIs and if so,
4135 // the declarations can be merged. This case for merging is only valid in
4136 // HLSL because there are no valid cases of merging mismatched parameter
4137 // ABIs except the HLSL implicit in and explicit in.
4138 if (Context.hasSameFunctionTypeIgnoringParamABI(T: OldQTypeForComparison,
4139 U: NewQType))
4140 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4141 // Fall through for conflicting redeclarations and redefinitions.
4142 }
4143
4144 // If the function types are compatible, merge the declarations. Ignore the
4145 // exception specifier because it was already checked above in
4146 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4147 // about incompatible types under -fms-compatibility.
4148 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(T: OldQTypeForComparison,
4149 U: NewQType))
4150 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4151
4152 // If the types are imprecise (due to dependent constructs in friends or
4153 // local extern declarations), it's OK if they differ. We'll check again
4154 // during instantiation.
4155 if (!canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewQType, OldT: OldQType))
4156 return false;
4157
4158 // Fall through for conflicting redeclarations and redefinitions.
4159 }
4160
4161 // C: Function types need to be compatible, not identical. This handles
4162 // duplicate function decls like "void f(int); void f(enum X);" properly.
4163 if (!getLangOpts().CPlusPlus) {
4164 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4165 // type is specified by a function definition that contains a (possibly
4166 // empty) identifier list, both shall agree in the number of parameters
4167 // and the type of each parameter shall be compatible with the type that
4168 // results from the application of default argument promotions to the
4169 // type of the corresponding identifier. ...
4170 // This cannot be handled by ASTContext::typesAreCompatible() because that
4171 // doesn't know whether the function type is for a definition or not when
4172 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4173 // we need to cover here is that the number of arguments agree as the
4174 // default argument promotion rules were already checked by
4175 // ASTContext::typesAreCompatible().
4176 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4177 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4178 if (Old->hasInheritedPrototype())
4179 Old = Old->getCanonicalDecl();
4180 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4181 Diag(Loc: Old->getLocation(), DiagID: PrevDiag) << Old << Old->getType();
4182 return true;
4183 }
4184
4185 // If we are merging two functions where only one of them has a prototype,
4186 // we may have enough information to decide to issue a diagnostic that the
4187 // function without a prototype will change behavior in C23. This handles
4188 // cases like:
4189 // void i(); void i(int j);
4190 // void i(int j); void i();
4191 // void i(); void i(int j) {}
4192 // See ActOnFinishFunctionBody() for other cases of the behavior change
4193 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4194 // type without a prototype.
4195 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4196 !New->isImplicit() && !Old->isImplicit()) {
4197 const FunctionDecl *WithProto, *WithoutProto;
4198 if (New->hasWrittenPrototype()) {
4199 WithProto = New;
4200 WithoutProto = Old;
4201 } else {
4202 WithProto = Old;
4203 WithoutProto = New;
4204 }
4205
4206 if (WithProto->getNumParams() != 0) {
4207 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4208 // The one without the prototype will be changing behavior in C23, so
4209 // warn about that one so long as it's a user-visible declaration.
4210 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4211 if (WithoutProto == New)
4212 IsWithoutProtoADef = NewDeclIsDefn;
4213 else
4214 IsWithProtoADef = NewDeclIsDefn;
4215 Diag(Loc: WithoutProto->getLocation(),
4216 DiagID: diag::warn_non_prototype_changes_behavior)
4217 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4218 << (WithoutProto == Old) << IsWithProtoADef;
4219
4220 // The reason the one without the prototype will be changing behavior
4221 // is because of the one with the prototype, so note that so long as
4222 // it's a user-visible declaration. There is one exception to this:
4223 // when the new declaration is a definition without a prototype, the
4224 // old declaration with a prototype is not the cause of the issue,
4225 // and that does not need to be noted because the one with a
4226 // prototype will not change behavior in C23.
4227 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4228 !IsWithoutProtoADef)
4229 Diag(Loc: WithProto->getLocation(), DiagID: diag::note_conflicting_prototype);
4230 }
4231 }
4232 }
4233
4234 if (Context.typesAreCompatible(T1: OldQType, T2: NewQType)) {
4235 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4236 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4237 const FunctionProtoType *OldProto = nullptr;
4238 if (MergeTypeWithOld && isa<FunctionNoProtoType>(Val: NewFuncType) &&
4239 (OldProto = dyn_cast<FunctionProtoType>(Val: OldFuncType))) {
4240 // The old declaration provided a function prototype, but the
4241 // new declaration does not. Merge in the prototype.
4242 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4243 NewQType = Context.getFunctionType(ResultTy: NewFuncType->getReturnType(),
4244 Args: OldProto->getParamTypes(),
4245 EPI: OldProto->getExtProtoInfo());
4246 New->setType(NewQType);
4247 New->setHasInheritedPrototype();
4248
4249 // Synthesize parameters with the same types.
4250 SmallVector<ParmVarDecl *, 16> Params;
4251 for (const auto &ParamType : OldProto->param_types()) {
4252 ParmVarDecl *Param = ParmVarDecl::Create(
4253 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
4254 T: ParamType, /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
4255 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
4256 Param->setImplicit();
4257 Params.push_back(Elt: Param);
4258 }
4259
4260 New->setParams(Params);
4261 }
4262
4263 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4264 }
4265 }
4266
4267 // Check if the function types are compatible when pointer size address
4268 // spaces are ignored.
4269 if (Context.hasSameFunctionTypeIgnoringPtrSizes(T: OldQType, U: NewQType))
4270 return false;
4271
4272 // GNU C permits a K&R definition to follow a prototype declaration
4273 // if the declared types of the parameters in the K&R definition
4274 // match the types in the prototype declaration, even when the
4275 // promoted types of the parameters from the K&R definition differ
4276 // from the types in the prototype. GCC then keeps the types from
4277 // the prototype.
4278 //
4279 // If a variadic prototype is followed by a non-variadic K&R definition,
4280 // the K&R definition becomes variadic. This is sort of an edge case, but
4281 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4282 // C99 6.9.1p8.
4283 if (!getLangOpts().CPlusPlus &&
4284 Old->hasPrototype() && !New->hasPrototype() &&
4285 New->getType()->getAs<FunctionProtoType>() &&
4286 Old->getNumParams() == New->getNumParams()) {
4287 SmallVector<QualType, 16> ArgTypes;
4288 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4289 const FunctionProtoType *OldProto
4290 = Old->getType()->getAs<FunctionProtoType>();
4291 const FunctionProtoType *NewProto
4292 = New->getType()->getAs<FunctionProtoType>();
4293
4294 // Determine whether this is the GNU C extension.
4295 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4296 NewProto->getReturnType());
4297 bool LooseCompatible = !MergedReturn.isNull();
4298 for (unsigned Idx = 0, End = Old->getNumParams();
4299 LooseCompatible && Idx != End; ++Idx) {
4300 ParmVarDecl *OldParm = Old->getParamDecl(i: Idx);
4301 ParmVarDecl *NewParm = New->getParamDecl(i: Idx);
4302 if (Context.typesAreCompatible(T1: OldParm->getType(),
4303 T2: NewProto->getParamType(i: Idx))) {
4304 ArgTypes.push_back(Elt: NewParm->getType());
4305 } else if (Context.typesAreCompatible(T1: OldParm->getType(),
4306 T2: NewParm->getType(),
4307 /*CompareUnqualified=*/true)) {
4308 GNUCompatibleParamWarning Warn = { .OldParm: OldParm, .NewParm: NewParm,
4309 .PromotedType: NewProto->getParamType(i: Idx) };
4310 Warnings.push_back(Elt: Warn);
4311 ArgTypes.push_back(Elt: NewParm->getType());
4312 } else
4313 LooseCompatible = false;
4314 }
4315
4316 if (LooseCompatible) {
4317 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4318 Diag(Loc: Warnings[Warn].NewParm->getLocation(),
4319 DiagID: diag::ext_param_promoted_not_compatible_with_prototype)
4320 << Warnings[Warn].PromotedType
4321 << Warnings[Warn].OldParm->getType();
4322 if (Warnings[Warn].OldParm->getLocation().isValid())
4323 Diag(Loc: Warnings[Warn].OldParm->getLocation(),
4324 DiagID: diag::note_previous_declaration);
4325 }
4326
4327 if (MergeTypeWithOld)
4328 New->setType(Context.getFunctionType(ResultTy: MergedReturn, Args: ArgTypes,
4329 EPI: OldProto->getExtProtoInfo()));
4330 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4331 }
4332
4333 // Fall through to diagnose conflicting types.
4334 }
4335
4336 // A function that has already been declared has been redeclared or
4337 // defined with a different type; show an appropriate diagnostic.
4338
4339 // If the previous declaration was an implicitly-generated builtin
4340 // declaration, then at the very least we should use a specialized note.
4341 unsigned BuiltinID;
4342 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4343 // If it's actually a library-defined builtin function like 'malloc'
4344 // or 'printf', just warn about the incompatible redeclaration.
4345 if (Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) {
4346 Diag(Loc: New->getLocation(), DiagID: diag::warn_redecl_library_builtin) << New;
4347 Diag(Loc: OldLocation, DiagID: diag::note_previous_builtin_declaration)
4348 << Old << Old->getType();
4349 return false;
4350 }
4351
4352 PrevDiag = diag::note_previous_builtin_declaration;
4353 }
4354
4355 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New->getDeclName();
4356 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4357 return true;
4358}
4359
4360bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4361 Scope *S, bool MergeTypeWithOld) {
4362 // Merge the attributes
4363 mergeDeclAttributes(New, Old);
4364
4365 // Merge "pure" flag.
4366 if (Old->isPureVirtual())
4367 New->setIsPureVirtual();
4368
4369 // Merge "used" flag.
4370 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4371 New->setIsUsed();
4372
4373 // Merge attributes from the parameters. These can mismatch with K&R
4374 // declarations.
4375 if (New->getNumParams() == Old->getNumParams())
4376 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4377 ParmVarDecl *NewParam = New->getParamDecl(i);
4378 ParmVarDecl *OldParam = Old->getParamDecl(i);
4379 mergeParamDeclAttributes(newDecl: NewParam, oldDecl: OldParam, S&: *this);
4380 mergeParamDeclTypes(NewParam, OldParam, S&: *this);
4381 }
4382
4383 if (getLangOpts().CPlusPlus)
4384 return MergeCXXFunctionDecl(New, Old, S);
4385
4386 // Merge the function types so the we get the composite types for the return
4387 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4388 // was visible.
4389 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4390 if (!Merged.isNull() && MergeTypeWithOld)
4391 New->setType(Merged);
4392
4393 return false;
4394}
4395
4396void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4397 ObjCMethodDecl *oldMethod) {
4398 // Merge the attributes, including deprecated/unavailable
4399 AvailabilityMergeKind MergeKind =
4400 isa<ObjCProtocolDecl>(Val: oldMethod->getDeclContext())
4401 ? (oldMethod->isOptional()
4402 ? AvailabilityMergeKind::OptionalProtocolImplementation
4403 : AvailabilityMergeKind::ProtocolImplementation)
4404 : isa<ObjCImplDecl>(Val: newMethod->getDeclContext())
4405 ? AvailabilityMergeKind::Redeclaration
4406 : AvailabilityMergeKind::Override;
4407
4408 mergeDeclAttributes(New: newMethod, Old: oldMethod, AMK: MergeKind);
4409
4410 // Merge attributes from the parameters.
4411 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4412 oe = oldMethod->param_end();
4413 for (ObjCMethodDecl::param_iterator
4414 ni = newMethod->param_begin(), ne = newMethod->param_end();
4415 ni != ne && oi != oe; ++ni, ++oi)
4416 mergeParamDeclAttributes(newDecl: *ni, oldDecl: *oi, S&: *this);
4417
4418 ObjC().CheckObjCMethodOverride(NewMethod: newMethod, Overridden: oldMethod);
4419}
4420
4421static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4422 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4423
4424 S.Diag(Loc: New->getLocation(), DiagID: New->isThisDeclarationADefinition()
4425 ? diag::err_redefinition_different_type
4426 : diag::err_redeclaration_different_type)
4427 << New->getDeclName() << New->getType() << Old->getType();
4428
4429 diag::kind PrevDiag;
4430 SourceLocation OldLocation;
4431 std::tie(args&: PrevDiag, args&: OldLocation)
4432 = getNoteDiagForInvalidRedeclaration(Old, New);
4433 S.Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4434 New->setInvalidDecl();
4435}
4436
4437void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4438 bool MergeTypeWithOld) {
4439 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4440 return;
4441
4442 QualType MergedT;
4443 if (getLangOpts().CPlusPlus) {
4444 if (New->getType()->isUndeducedType()) {
4445 // We don't know what the new type is until the initializer is attached.
4446 return;
4447 } else if (Context.hasSameType(T1: New->getType(), T2: Old->getType())) {
4448 // These could still be something that needs exception specs checked.
4449 return MergeVarDeclExceptionSpecs(New, Old);
4450 }
4451 // C++ [basic.link]p10:
4452 // [...] the types specified by all declarations referring to a given
4453 // object or function shall be identical, except that declarations for an
4454 // array object can specify array types that differ by the presence or
4455 // absence of a major array bound (8.3.4).
4456 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4457 const ArrayType *OldArray = Context.getAsArrayType(T: Old->getType());
4458 const ArrayType *NewArray = Context.getAsArrayType(T: New->getType());
4459
4460 // We are merging a variable declaration New into Old. If it has an array
4461 // bound, and that bound differs from Old's bound, we should diagnose the
4462 // mismatch.
4463 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4464 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4465 PrevVD = PrevVD->getPreviousDecl()) {
4466 QualType PrevVDTy = PrevVD->getType();
4467 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4468 continue;
4469
4470 if (!Context.hasSameType(T1: New->getType(), T2: PrevVDTy))
4471 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old: PrevVD);
4472 }
4473 }
4474
4475 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4476 if (Context.hasSameType(T1: OldArray->getElementType(),
4477 T2: NewArray->getElementType()))
4478 MergedT = New->getType();
4479 }
4480 // FIXME: Check visibility. New is hidden but has a complete type. If New
4481 // has no array bound, it should not inherit one from Old, if Old is not
4482 // visible.
4483 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4484 if (Context.hasSameType(T1: OldArray->getElementType(),
4485 T2: NewArray->getElementType()))
4486 MergedT = Old->getType();
4487 }
4488 }
4489 else if (New->getType()->isObjCObjectPointerType() &&
4490 Old->getType()->isObjCObjectPointerType()) {
4491 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4492 Old->getType());
4493 }
4494 } else {
4495 // C 6.2.7p2:
4496 // All declarations that refer to the same object or function shall have
4497 // compatible type.
4498 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4499 }
4500 if (MergedT.isNull()) {
4501 // It's OK if we couldn't merge types if either type is dependent, for a
4502 // block-scope variable. In other cases (static data members of class
4503 // templates, variable templates, ...), we require the types to be
4504 // equivalent.
4505 // FIXME: The C++ standard doesn't say anything about this.
4506 if ((New->getType()->isDependentType() ||
4507 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4508 // If the old type was dependent, we can't merge with it, so the new type
4509 // becomes dependent for now. We'll reproduce the original type when we
4510 // instantiate the TypeSourceInfo for the variable.
4511 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4512 New->setType(Context.DependentTy);
4513 return;
4514 }
4515 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old);
4516 }
4517
4518 // Don't actually update the type on the new declaration if the old
4519 // declaration was an extern declaration in a different scope.
4520 if (MergeTypeWithOld)
4521 New->setType(MergedT);
4522}
4523
4524static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4525 LookupResult &Previous) {
4526 // C11 6.2.7p4:
4527 // For an identifier with internal or external linkage declared
4528 // in a scope in which a prior declaration of that identifier is
4529 // visible, if the prior declaration specifies internal or
4530 // external linkage, the type of the identifier at the later
4531 // declaration becomes the composite type.
4532 //
4533 // If the variable isn't visible, we do not merge with its type.
4534 if (Previous.isShadowed())
4535 return false;
4536
4537 if (S.getLangOpts().CPlusPlus) {
4538 // C++11 [dcl.array]p3:
4539 // If there is a preceding declaration of the entity in the same
4540 // scope in which the bound was specified, an omitted array bound
4541 // is taken to be the same as in that earlier declaration.
4542 return NewVD->isPreviousDeclInSameBlockScope() ||
4543 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4544 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4545 } else {
4546 // If the old declaration was function-local, don't merge with its
4547 // type unless we're in the same function.
4548 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4549 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4550 }
4551}
4552
4553void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4554 // If the new decl is already invalid, don't do any other checking.
4555 if (New->isInvalidDecl())
4556 return;
4557
4558 if (!shouldLinkPossiblyHiddenDecl(Old&: Previous, New))
4559 return;
4560
4561 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4562
4563 // Verify the old decl was also a variable or variable template.
4564 VarDecl *Old = nullptr;
4565 VarTemplateDecl *OldTemplate = nullptr;
4566 if (Previous.isSingleResult()) {
4567 if (NewTemplate) {
4568 OldTemplate = dyn_cast<VarTemplateDecl>(Val: Previous.getFoundDecl());
4569 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4570
4571 if (auto *Shadow =
4572 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4573 if (checkUsingShadowRedecl<VarTemplateDecl>(S&: *this, OldS: Shadow, New: NewTemplate))
4574 return New->setInvalidDecl();
4575 } else {
4576 Old = dyn_cast<VarDecl>(Val: Previous.getFoundDecl());
4577
4578 if (auto *Shadow =
4579 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4580 if (checkUsingShadowRedecl<VarDecl>(S&: *this, OldS: Shadow, New))
4581 return New->setInvalidDecl();
4582 }
4583 }
4584 if (!Old) {
4585 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
4586 << New->getDeclName();
4587 notePreviousDefinition(Old: Previous.getRepresentativeDecl(),
4588 New: New->getLocation());
4589 return New->setInvalidDecl();
4590 }
4591
4592 // If the old declaration was found in an inline namespace and the new
4593 // declaration was qualified, update the DeclContext to match.
4594 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
4595
4596 // Ensure the template parameters are compatible.
4597 if (NewTemplate &&
4598 !TemplateParameterListsAreEqual(New: NewTemplate->getTemplateParameters(),
4599 Old: OldTemplate->getTemplateParameters(),
4600 /*Complain=*/true, Kind: TPL_TemplateMatch))
4601 return New->setInvalidDecl();
4602
4603 // C++ [class.mem]p1:
4604 // A member shall not be declared twice in the member-specification [...]
4605 //
4606 // Here, we need only consider static data members.
4607 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4608 Diag(Loc: New->getLocation(), DiagID: diag::err_duplicate_member)
4609 << New->getIdentifier();
4610 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4611 New->setInvalidDecl();
4612 }
4613
4614 mergeDeclAttributes(New, Old);
4615 // Warn if an already-defined variable is made a weak_import in a subsequent
4616 // declaration
4617 if (New->hasAttr<WeakImportAttr>())
4618 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4619 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4620 Diag(Loc: New->getLocation(), DiagID: diag::warn_weak_import) << New->getDeclName();
4621 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
4622 // Remove weak_import attribute on new declaration.
4623 New->dropAttr<WeakImportAttr>();
4624 break;
4625 }
4626 }
4627
4628 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4629 if (!Old->hasAttr<InternalLinkageAttr>()) {
4630 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4631 << ILA;
4632 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4633 New->dropAttr<InternalLinkageAttr>();
4634 }
4635
4636 // Merge the types.
4637 VarDecl *MostRecent = Old->getMostRecentDecl();
4638 if (MostRecent != Old) {
4639 MergeVarDeclTypes(New, Old: MostRecent,
4640 MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: MostRecent, Previous));
4641 if (New->isInvalidDecl())
4642 return;
4643 }
4644
4645 MergeVarDeclTypes(New, Old, MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: Old, Previous));
4646 if (New->isInvalidDecl())
4647 return;
4648
4649 diag::kind PrevDiag;
4650 SourceLocation OldLocation;
4651 std::tie(args&: PrevDiag, args&: OldLocation) =
4652 getNoteDiagForInvalidRedeclaration(Old, New);
4653
4654 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4655 if (New->getStorageClass() == SC_Static &&
4656 !New->isStaticDataMember() &&
4657 Old->hasExternalFormalLinkage()) {
4658 if (getLangOpts().MicrosoftExt) {
4659 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static)
4660 << New->getDeclName();
4661 Diag(Loc: OldLocation, DiagID: PrevDiag);
4662 } else {
4663 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static)
4664 << New->getDeclName();
4665 Diag(Loc: OldLocation, DiagID: PrevDiag);
4666 return New->setInvalidDecl();
4667 }
4668 }
4669 // C99 6.2.2p4:
4670 // For an identifier declared with the storage-class specifier
4671 // extern in a scope in which a prior declaration of that
4672 // identifier is visible,23) if the prior declaration specifies
4673 // internal or external linkage, the linkage of the identifier at
4674 // the later declaration is the same as the linkage specified at
4675 // the prior declaration. If no prior declaration is visible, or
4676 // if the prior declaration specifies no linkage, then the
4677 // identifier has external linkage.
4678 if (New->hasExternalStorage() && Old->hasLinkage())
4679 /* Okay */;
4680 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4681 !New->isStaticDataMember() &&
4682 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4683 Diag(Loc: New->getLocation(), DiagID: diag::err_non_static_static) << New->getDeclName();
4684 Diag(Loc: OldLocation, DiagID: PrevDiag);
4685 return New->setInvalidDecl();
4686 }
4687
4688 // Check if extern is followed by non-extern and vice-versa.
4689 if (New->hasExternalStorage() &&
4690 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4691 Diag(Loc: New->getLocation(), DiagID: diag::err_extern_non_extern) << New->getDeclName();
4692 Diag(Loc: OldLocation, DiagID: PrevDiag);
4693 return New->setInvalidDecl();
4694 }
4695 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4696 !New->hasExternalStorage()) {
4697 Diag(Loc: New->getLocation(), DiagID: diag::err_non_extern_extern) << New->getDeclName();
4698 Diag(Loc: OldLocation, DiagID: PrevDiag);
4699 return New->setInvalidDecl();
4700 }
4701
4702 if (CheckRedeclarationInModule(New, Old))
4703 return;
4704
4705 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4706
4707 // FIXME: The test for external storage here seems wrong? We still
4708 // need to check for mismatches.
4709 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4710 // Don't complain about out-of-line definitions of static members.
4711 !(Old->getLexicalDeclContext()->isRecord() &&
4712 !New->getLexicalDeclContext()->isRecord())) {
4713 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New->getDeclName();
4714 Diag(Loc: OldLocation, DiagID: PrevDiag);
4715 return New->setInvalidDecl();
4716 }
4717
4718 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4719 if (VarDecl *Def = Old->getDefinition()) {
4720 // C++1z [dcl.fcn.spec]p4:
4721 // If the definition of a variable appears in a translation unit before
4722 // its first declaration as inline, the program is ill-formed.
4723 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
4724 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
4725 }
4726 }
4727
4728 // If this redeclaration makes the variable inline, we may need to add it to
4729 // UndefinedButUsed.
4730 if (!Old->isInline() && New->isInline() && Old->isUsed(CheckUsedAttr: false) &&
4731 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4732 !Old->isInAnotherModuleUnit())
4733 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4734 y: SourceLocation()));
4735
4736 if (New->getTLSKind() != Old->getTLSKind()) {
4737 if (!Old->getTLSKind()) {
4738 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_non_thread) << New->getDeclName();
4739 Diag(Loc: OldLocation, DiagID: PrevDiag);
4740 } else if (!New->getTLSKind()) {
4741 Diag(Loc: New->getLocation(), DiagID: diag::err_non_thread_thread) << New->getDeclName();
4742 Diag(Loc: OldLocation, DiagID: PrevDiag);
4743 } else {
4744 // Do not allow redeclaration to change the variable between requiring
4745 // static and dynamic initialization.
4746 // FIXME: GCC allows this, but uses the TLS keyword on the first
4747 // declaration to determine the kind. Do we need to be compatible here?
4748 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_thread_different_kind)
4749 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4750 Diag(Loc: OldLocation, DiagID: PrevDiag);
4751 }
4752 }
4753
4754 // C++ doesn't have tentative definitions, so go right ahead and check here.
4755 if (getLangOpts().CPlusPlus) {
4756 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4757 Old->getCanonicalDecl()->isConstexpr()) {
4758 // This definition won't be a definition any more once it's been merged.
4759 Diag(Loc: New->getLocation(),
4760 DiagID: diag::warn_deprecated_redundant_constexpr_static_def);
4761 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4762 VarDecl *Def = Old->getDefinition();
4763 if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New))
4764 return;
4765 }
4766 } else {
4767 // C++ may not have a tentative definition rule, but it has a different
4768 // rule about what constitutes a definition in the first place. See
4769 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4770 // contains the extern specifier and doesn't have an initializer, it's fine
4771 // in C++.
4772 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4773 Diag(Loc: New->getLocation(), DiagID: diag::warn_cxx_compat_tentative_definition)
4774 << New;
4775 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4776 }
4777 }
4778
4779 if (haveIncompatibleLanguageLinkages(Old, New)) {
4780 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4781 Diag(Loc: OldLocation, DiagID: PrevDiag);
4782 New->setInvalidDecl();
4783 return;
4784 }
4785
4786 // Merge "used" flag.
4787 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4788 New->setIsUsed();
4789
4790 // Keep a chain of previous declarations.
4791 New->setPreviousDecl(Old);
4792 if (NewTemplate)
4793 NewTemplate->setPreviousDecl(OldTemplate);
4794
4795 // Inherit access appropriately.
4796 New->setAccess(Old->getAccess());
4797 if (NewTemplate)
4798 NewTemplate->setAccess(New->getAccess());
4799
4800 if (Old->isInline())
4801 New->setImplicitlyInline();
4802}
4803
4804void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4805 SourceManager &SrcMgr = getSourceManager();
4806 auto FNewDecLoc = SrcMgr.getDecomposedLoc(Loc: New);
4807 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Loc: Old->getLocation());
4808 auto *FNew = SrcMgr.getFileEntryForID(FID: FNewDecLoc.first);
4809 auto FOld = SrcMgr.getFileEntryRefForID(FID: FOldDecLoc.first);
4810 auto &HSI = PP.getHeaderSearchInfo();
4811 StringRef HdrFilename =
4812 SrcMgr.getFilename(SpellingLoc: SrcMgr.getSpellingLoc(Loc: Old->getLocation()));
4813
4814 auto noteFromModuleOrInclude = [&](Module *Mod,
4815 SourceLocation IncLoc) -> bool {
4816 // Redefinition errors with modules are common with non modular mapped
4817 // headers, example: a non-modular header H in module A that also gets
4818 // included directly in a TU. Pointing twice to the same header/definition
4819 // is confusing, try to get better diagnostics when modules is on.
4820 if (IncLoc.isValid()) {
4821 if (Mod) {
4822 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_modules_same_file)
4823 << HdrFilename.str() << Mod->getFullModuleName();
4824 if (!Mod->DefinitionLoc.isInvalid())
4825 Diag(Loc: Mod->DefinitionLoc, DiagID: diag::note_defined_here)
4826 << Mod->getFullModuleName();
4827 } else {
4828 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_include_same_file)
4829 << HdrFilename.str();
4830 }
4831 return true;
4832 }
4833
4834 return false;
4835 };
4836
4837 // Is it the same file and same offset? Provide more information on why
4838 // this leads to a redefinition error.
4839 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4840 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FID: FOldDecLoc.first);
4841 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FID: FNewDecLoc.first);
4842 bool EmittedDiag =
4843 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4844 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4845
4846 // If the header has no guards, emit a note suggesting one.
4847 if (FOld && !HSI.isFileMultipleIncludeGuarded(File: *FOld))
4848 Diag(Loc: Old->getLocation(), DiagID: diag::note_use_ifdef_guards);
4849
4850 if (EmittedDiag)
4851 return;
4852 }
4853
4854 // Redefinition coming from different files or couldn't do better above.
4855 if (Old->getLocation().isValid())
4856 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
4857}
4858
4859bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4860 if (!hasVisibleDefinition(D: Old) &&
4861 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4862 isa<VarTemplateSpecializationDecl>(Val: New) ||
4863 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4864 New->getDeclContext()->isDependentContext() ||
4865 New->hasAttr<SelectAnyAttr>())) {
4866 // The previous definition is hidden, and multiple definitions are
4867 // permitted (in separate TUs). Demote this to a declaration.
4868 New->demoteThisDefinitionToDeclaration();
4869
4870 // Make the canonical definition visible.
4871 if (auto *OldTD = Old->getDescribedVarTemplate())
4872 makeMergedDefinitionVisible(ND: OldTD);
4873 makeMergedDefinitionVisible(ND: Old);
4874 return false;
4875 } else {
4876 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New;
4877 notePreviousDefinition(Old, New: New->getLocation());
4878 New->setInvalidDecl();
4879 return true;
4880 }
4881}
4882
4883Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4884 DeclSpec &DS,
4885 const ParsedAttributesView &DeclAttrs,
4886 RecordDecl *&AnonRecord) {
4887 return ParsedFreeStandingDeclSpec(
4888 S, AS, DS, DeclAttrs, TemplateParams: MultiTemplateParamsArg(), IsExplicitInstantiation: false, AnonRecord);
4889}
4890
4891// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4892// disambiguate entities defined in different scopes.
4893// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4894// compatibility.
4895// We will pick our mangling number depending on which version of MSVC is being
4896// targeted.
4897static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4898 return LO.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015)
4899 ? S->getMSCurManglingNumber()
4900 : S->getMSLastManglingNumber();
4901}
4902
4903void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4904 if (!Context.getLangOpts().CPlusPlus)
4905 return;
4906
4907 if (isa<CXXRecordDecl>(Val: Tag->getParent())) {
4908 // If this tag is the direct child of a class, number it if
4909 // it is anonymous.
4910 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4911 return;
4912 MangleNumberingContext &MCtx =
4913 Context.getManglingNumberContext(DC: Tag->getParent());
4914 Context.setManglingNumber(
4915 ND: Tag, Number: MCtx.getManglingNumber(
4916 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
4917 return;
4918 }
4919
4920 // If this tag isn't a direct child of a class, number it if it is local.
4921 MangleNumberingContext *MCtx;
4922 Decl *ManglingContextDecl;
4923 std::tie(args&: MCtx, args&: ManglingContextDecl) =
4924 getCurrentMangleNumberContext(DC: Tag->getDeclContext());
4925 if (MCtx) {
4926 Context.setManglingNumber(
4927 ND: Tag, Number: MCtx->getManglingNumber(
4928 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
4929 }
4930}
4931
4932namespace {
4933struct NonCLikeKind {
4934 enum {
4935 None,
4936 BaseClass,
4937 DefaultMemberInit,
4938 Lambda,
4939 Friend,
4940 OtherMember,
4941 Invalid,
4942 } Kind = None;
4943 SourceRange Range;
4944
4945 explicit operator bool() { return Kind != None; }
4946};
4947}
4948
4949/// Determine whether a class is C-like, according to the rules of C++
4950/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4951static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4952 if (RD->isInvalidDecl())
4953 return {.Kind: NonCLikeKind::Invalid, .Range: {}};
4954
4955 // C++ [dcl.typedef]p9: [P1766R1]
4956 // An unnamed class with a typedef name for linkage purposes shall not
4957 //
4958 // -- have any base classes
4959 if (RD->getNumBases())
4960 return {.Kind: NonCLikeKind::BaseClass,
4961 .Range: SourceRange(RD->bases_begin()->getBeginLoc(),
4962 RD->bases_end()[-1].getEndLoc())};
4963 bool Invalid = false;
4964 for (Decl *D : RD->decls()) {
4965 // Don't complain about things we already diagnosed.
4966 if (D->isInvalidDecl()) {
4967 Invalid = true;
4968 continue;
4969 }
4970
4971 // -- have any [...] default member initializers
4972 if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
4973 if (FD->hasInClassInitializer()) {
4974 auto *Init = FD->getInClassInitializer();
4975 return {.Kind: NonCLikeKind::DefaultMemberInit,
4976 .Range: Init ? Init->getSourceRange() : D->getSourceRange()};
4977 }
4978 continue;
4979 }
4980
4981 // FIXME: We don't allow friend declarations. This violates the wording of
4982 // P1766, but not the intent.
4983 if (isa<FriendDecl>(Val: D))
4984 return {.Kind: NonCLikeKind::Friend, .Range: D->getSourceRange()};
4985
4986 // -- declare any members other than non-static data members, member
4987 // enumerations, or member classes,
4988 if (isa<StaticAssertDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D) ||
4989 isa<EnumDecl>(Val: D))
4990 continue;
4991 auto *MemberRD = dyn_cast<CXXRecordDecl>(Val: D);
4992 if (!MemberRD) {
4993 if (D->isImplicit())
4994 continue;
4995 return {.Kind: NonCLikeKind::OtherMember, .Range: D->getSourceRange()};
4996 }
4997
4998 // -- contain a lambda-expression,
4999 if (MemberRD->isLambda())
5000 return {.Kind: NonCLikeKind::Lambda, .Range: MemberRD->getSourceRange()};
5001
5002 // and all member classes shall also satisfy these requirements
5003 // (recursively).
5004 if (MemberRD->isThisDeclarationADefinition()) {
5005 if (auto Kind = getNonCLikeKindForAnonymousStruct(RD: MemberRD))
5006 return Kind;
5007 }
5008 }
5009
5010 return {.Kind: Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, .Range: {}};
5011}
5012
5013void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5014 TypedefNameDecl *NewTD) {
5015 if (TagFromDeclSpec->isInvalidDecl())
5016 return;
5017
5018 // Do nothing if the tag already has a name for linkage purposes.
5019 if (TagFromDeclSpec->hasNameForLinkage())
5020 return;
5021
5022 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5023 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5024
5025 // The type must match the tag exactly; no qualifiers allowed.
5026 if (!Context.hasSameType(T1: NewTD->getUnderlyingType(),
5027 T2: Context.getTagDeclType(Decl: TagFromDeclSpec))) {
5028 if (getLangOpts().CPlusPlus)
5029 Context.addTypedefNameForUnnamedTagDecl(TD: TagFromDeclSpec, TND: NewTD);
5030 return;
5031 }
5032
5033 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5034 // An unnamed class with a typedef name for linkage purposes shall [be
5035 // C-like].
5036 //
5037 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5038 // shouldn't happen, but there are constructs that the language rule doesn't
5039 // disallow for which we can't reasonably avoid computing linkage early.
5040 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TagFromDeclSpec);
5041 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5042 : NonCLikeKind();
5043 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5044 if (NonCLike || ChangesLinkage) {
5045 if (NonCLike.Kind == NonCLikeKind::Invalid)
5046 return;
5047
5048 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5049 if (ChangesLinkage) {
5050 // If the linkage changes, we can't accept this as an extension.
5051 if (NonCLike.Kind == NonCLikeKind::None)
5052 DiagID = diag::err_typedef_changes_linkage;
5053 else
5054 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5055 }
5056
5057 SourceLocation FixitLoc =
5058 getLocForEndOfToken(Loc: TagFromDeclSpec->getInnerLocStart());
5059 llvm::SmallString<40> TextToInsert;
5060 TextToInsert += ' ';
5061 TextToInsert += NewTD->getIdentifier()->getName();
5062
5063 Diag(Loc: FixitLoc, DiagID)
5064 << isa<TypeAliasDecl>(Val: NewTD)
5065 << FixItHint::CreateInsertion(InsertionLoc: FixitLoc, Code: TextToInsert);
5066 if (NonCLike.Kind != NonCLikeKind::None) {
5067 Diag(Loc: NonCLike.Range.getBegin(), DiagID: diag::note_non_c_like_anon_struct)
5068 << NonCLike.Kind - 1 << NonCLike.Range;
5069 }
5070 Diag(Loc: NewTD->getLocation(), DiagID: diag::note_typedef_for_linkage_here)
5071 << NewTD << isa<TypeAliasDecl>(Val: NewTD);
5072
5073 if (ChangesLinkage)
5074 return;
5075 }
5076
5077 // Otherwise, set this as the anon-decl typedef for the tag.
5078 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5079
5080 // Now that we have a name for the tag, process API notes again.
5081 ProcessAPINotes(D: TagFromDeclSpec);
5082}
5083
5084static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5085 DeclSpec::TST T = DS.getTypeSpecType();
5086 switch (T) {
5087 case DeclSpec::TST_class:
5088 return 0;
5089 case DeclSpec::TST_struct:
5090 return 1;
5091 case DeclSpec::TST_interface:
5092 return 2;
5093 case DeclSpec::TST_union:
5094 return 3;
5095 case DeclSpec::TST_enum:
5096 if (const auto *ED = dyn_cast<EnumDecl>(Val: DS.getRepAsDecl())) {
5097 if (ED->isScopedUsingClassTag())
5098 return 5;
5099 if (ED->isScoped())
5100 return 6;
5101 }
5102 return 4;
5103 default:
5104 llvm_unreachable("unexpected type specifier");
5105 }
5106}
5107
5108Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5109 DeclSpec &DS,
5110 const ParsedAttributesView &DeclAttrs,
5111 MultiTemplateParamsArg TemplateParams,
5112 bool IsExplicitInstantiation,
5113 RecordDecl *&AnonRecord,
5114 SourceLocation EllipsisLoc) {
5115 Decl *TagD = nullptr;
5116 TagDecl *Tag = nullptr;
5117 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5118 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5119 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5120 DS.getTypeSpecType() == DeclSpec::TST_union ||
5121 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5122 TagD = DS.getRepAsDecl();
5123
5124 if (!TagD) // We probably had an error
5125 return nullptr;
5126
5127 // Note that the above type specs guarantee that the
5128 // type rep is a Decl, whereas in many of the others
5129 // it's a Type.
5130 if (isa<TagDecl>(Val: TagD))
5131 Tag = cast<TagDecl>(Val: TagD);
5132 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: TagD))
5133 Tag = CTD->getTemplatedDecl();
5134 }
5135
5136 if (Tag) {
5137 handleTagNumbering(Tag, TagScope: S);
5138 Tag->setFreeStanding();
5139 if (Tag->isInvalidDecl())
5140 return Tag;
5141 }
5142
5143 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5144 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5145 // or incomplete types shall not be restrict-qualified."
5146 if (TypeQuals & DeclSpec::TQ_restrict)
5147 Diag(Loc: DS.getRestrictSpecLoc(),
5148 DiagID: diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5149 << DS.getSourceRange();
5150 }
5151
5152 if (DS.isInlineSpecified())
5153 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
5154 << getLangOpts().CPlusPlus17;
5155
5156 if (DS.hasConstexprSpecifier()) {
5157 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5158 // and definitions of functions and variables.
5159 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5160 // the declaration of a function or function template
5161 if (Tag)
5162 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_tag)
5163 << GetDiagnosticTypeSpecifierID(DS)
5164 << static_cast<int>(DS.getConstexprSpecifier());
5165 else if (getLangOpts().C23)
5166 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_c23_constexpr_not_variable);
5167 else
5168 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_wrong_decl_kind)
5169 << static_cast<int>(DS.getConstexprSpecifier());
5170 // Don't emit warnings after this error.
5171 return TagD;
5172 }
5173
5174 DiagnoseFunctionSpecifiers(DS);
5175
5176 if (DS.isFriendSpecified()) {
5177 // If we're dealing with a decl but not a TagDecl, assume that
5178 // whatever routines created it handled the friendship aspect.
5179 if (TagD && !Tag)
5180 return nullptr;
5181 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5182 }
5183
5184 assert(EllipsisLoc.isInvalid() &&
5185 "Friend ellipsis but not friend-specified?");
5186
5187 // Track whether this decl-specifier declares anything.
5188 bool DeclaresAnything = true;
5189
5190 // Handle anonymous struct definitions.
5191 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Val: Tag)) {
5192 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5193 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5194 if (getLangOpts().CPlusPlus ||
5195 Record->getDeclContext()->isRecord()) {
5196 // If CurContext is a DeclContext that can contain statements,
5197 // RecursiveASTVisitor won't visit the decls that
5198 // BuildAnonymousStructOrUnion() will put into CurContext.
5199 // Also store them here so that they can be part of the
5200 // DeclStmt that gets created in this case.
5201 // FIXME: Also return the IndirectFieldDecls created by
5202 // BuildAnonymousStructOr union, for the same reason?
5203 if (CurContext->isFunctionOrMethod())
5204 AnonRecord = Record;
5205 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5206 Policy: Context.getPrintingPolicy());
5207 }
5208
5209 DeclaresAnything = false;
5210 }
5211 }
5212
5213 // C11 6.7.2.1p2:
5214 // A struct-declaration that does not declare an anonymous structure or
5215 // anonymous union shall contain a struct-declarator-list.
5216 //
5217 // This rule also existed in C89 and C99; the grammar for struct-declaration
5218 // did not permit a struct-declaration without a struct-declarator-list.
5219 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5220 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5221 // Check for Microsoft C extension: anonymous struct/union member.
5222 // Handle 2 kinds of anonymous struct/union:
5223 // struct STRUCT;
5224 // union UNION;
5225 // and
5226 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5227 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5228 if ((Tag && Tag->getDeclName()) ||
5229 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5230 RecordDecl *Record = nullptr;
5231 if (Tag)
5232 Record = dyn_cast<RecordDecl>(Val: Tag);
5233 else if (const RecordType *RT =
5234 DS.getRepAsType().get()->getAsStructureType())
5235 Record = RT->getDecl();
5236 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5237 Record = UT->getDecl();
5238
5239 if (Record && getLangOpts().MicrosoftExt) {
5240 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_ms_anonymous_record)
5241 << Record->isUnion() << DS.getSourceRange();
5242 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5243 }
5244
5245 DeclaresAnything = false;
5246 }
5247 }
5248
5249 // Skip all the checks below if we have a type error.
5250 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5251 (TagD && TagD->isInvalidDecl()))
5252 return TagD;
5253
5254 if (getLangOpts().CPlusPlus &&
5255 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5256 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Val: Tag))
5257 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5258 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5259 DeclaresAnything = false;
5260
5261 if (!DS.isMissingDeclaratorOk()) {
5262 // Customize diagnostic for a typedef missing a name.
5263 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5264 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_typedef_without_a_name)
5265 << DS.getSourceRange();
5266 else
5267 DeclaresAnything = false;
5268 }
5269
5270 if (DS.isModulePrivateSpecified() &&
5271 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5272 Diag(Loc: DS.getModulePrivateSpecLoc(), DiagID: diag::err_module_private_local_class)
5273 << Tag->getTagKind()
5274 << FixItHint::CreateRemoval(RemoveRange: DS.getModulePrivateSpecLoc());
5275
5276 ActOnDocumentableDecl(D: TagD);
5277
5278 // C 6.7/2:
5279 // A declaration [...] shall declare at least a declarator [...], a tag,
5280 // or the members of an enumeration.
5281 // C++ [dcl.dcl]p3:
5282 // [If there are no declarators], and except for the declaration of an
5283 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5284 // names into the program, or shall redeclare a name introduced by a
5285 // previous declaration.
5286 if (!DeclaresAnything) {
5287 // In C, we allow this as a (popular) extension / bug. Don't bother
5288 // producing further diagnostics for redundant qualifiers after this.
5289 Diag(Loc: DS.getBeginLoc(), DiagID: (IsExplicitInstantiation || !TemplateParams.empty())
5290 ? diag::err_no_declarators
5291 : diag::ext_no_declarators)
5292 << DS.getSourceRange();
5293 return TagD;
5294 }
5295
5296 // C++ [dcl.stc]p1:
5297 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5298 // init-declarator-list of the declaration shall not be empty.
5299 // C++ [dcl.fct.spec]p1:
5300 // If a cv-qualifier appears in a decl-specifier-seq, the
5301 // init-declarator-list of the declaration shall not be empty.
5302 //
5303 // Spurious qualifiers here appear to be valid in C.
5304 unsigned DiagID = diag::warn_standalone_specifier;
5305 if (getLangOpts().CPlusPlus)
5306 DiagID = diag::ext_standalone_specifier;
5307
5308 // Note that a linkage-specification sets a storage class, but
5309 // 'extern "C" struct foo;' is actually valid and not theoretically
5310 // useless.
5311 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5312 if (SCS == DeclSpec::SCS_mutable)
5313 // Since mutable is not a viable storage class specifier in C, there is
5314 // no reason to treat it as an extension. Instead, diagnose as an error.
5315 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_nonmember);
5316 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5317 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID)
5318 << DeclSpec::getSpecifierName(S: SCS);
5319 }
5320
5321 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5322 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID)
5323 << DeclSpec::getSpecifierName(S: TSCS);
5324 if (DS.getTypeQualifiers()) {
5325 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5326 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "const";
5327 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5328 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "volatile";
5329 // Restrict is covered above.
5330 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5331 Diag(Loc: DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5332 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5333 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5334 }
5335
5336 // Warn about ignored type attributes, for example:
5337 // __attribute__((aligned)) struct A;
5338 // Attributes should be placed after tag to apply to type declaration.
5339 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5340 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5341 if (TypeSpecType == DeclSpec::TST_class ||
5342 TypeSpecType == DeclSpec::TST_struct ||
5343 TypeSpecType == DeclSpec::TST_interface ||
5344 TypeSpecType == DeclSpec::TST_union ||
5345 TypeSpecType == DeclSpec::TST_enum) {
5346
5347 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5348 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5349 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5350 DiagnosticId = diag::warn_attribute_ignored;
5351 else if (AL.isRegularKeywordAttribute())
5352 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5353 else
5354 DiagnosticId = diag::warn_declspec_attribute_ignored;
5355 Diag(Loc: AL.getLoc(), DiagID: DiagnosticId)
5356 << AL << GetDiagnosticTypeSpecifierID(DS);
5357 };
5358
5359 llvm::for_each(Range&: DS.getAttributes(), F: EmitAttributeDiagnostic);
5360 llvm::for_each(Range: DeclAttrs, F: EmitAttributeDiagnostic);
5361 }
5362 }
5363
5364 return TagD;
5365}
5366
5367/// We are trying to inject an anonymous member into the given scope;
5368/// check if there's an existing declaration that can't be overloaded.
5369///
5370/// \return true if this is a forbidden redeclaration
5371static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5372 DeclContext *Owner,
5373 DeclarationName Name,
5374 SourceLocation NameLoc, bool IsUnion,
5375 StorageClass SC) {
5376 LookupResult R(SemaRef, Name, NameLoc,
5377 Owner->isRecord() ? Sema::LookupMemberName
5378 : Sema::LookupOrdinaryName,
5379 RedeclarationKind::ForVisibleRedeclaration);
5380 if (!SemaRef.LookupName(R, S)) return false;
5381
5382 // Pick a representative declaration.
5383 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5384 assert(PrevDecl && "Expected a non-null Decl");
5385
5386 if (!SemaRef.isDeclInScope(D: PrevDecl, Ctx: Owner, S))
5387 return false;
5388
5389 if (SC == StorageClass::SC_None &&
5390 PrevDecl->isPlaceholderVar(LangOpts: SemaRef.getLangOpts()) &&
5391 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5392 if (!Owner->isRecord())
5393 SemaRef.DiagPlaceholderVariableDefinition(Loc: NameLoc);
5394 return false;
5395 }
5396
5397 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_anonymous_record_member_redecl)
5398 << IsUnion << Name;
5399 SemaRef.Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
5400
5401 return true;
5402}
5403
5404void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5405 if (auto *RD = dyn_cast_if_present<RecordDecl>(Val: D))
5406 DiagPlaceholderFieldDeclDefinitions(Record: RD);
5407}
5408
5409void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5410 if (!getLangOpts().CPlusPlus)
5411 return;
5412
5413 // This function can be parsed before we have validated the
5414 // structure as an anonymous struct
5415 if (Record->isAnonymousStructOrUnion())
5416 return;
5417
5418 const NamedDecl *First = 0;
5419 for (const Decl *D : Record->decls()) {
5420 const NamedDecl *ND = dyn_cast<NamedDecl>(Val: D);
5421 if (!ND || !ND->isPlaceholderVar(LangOpts: getLangOpts()))
5422 continue;
5423 if (!First)
5424 First = ND;
5425 else
5426 DiagPlaceholderVariableDefinition(Loc: ND->getLocation());
5427 }
5428}
5429
5430/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5431/// anonymous struct or union AnonRecord into the owning context Owner
5432/// and scope S. This routine will be invoked just after we realize
5433/// that an unnamed union or struct is actually an anonymous union or
5434/// struct, e.g.,
5435///
5436/// @code
5437/// union {
5438/// int i;
5439/// float f;
5440/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5441/// // f into the surrounding scope.x
5442/// @endcode
5443///
5444/// This routine is recursive, injecting the names of nested anonymous
5445/// structs/unions into the owning context and scope as well.
5446static bool
5447InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5448 RecordDecl *AnonRecord, AccessSpecifier AS,
5449 StorageClass SC,
5450 SmallVectorImpl<NamedDecl *> &Chaining) {
5451 bool Invalid = false;
5452
5453 // Look every FieldDecl and IndirectFieldDecl with a name.
5454 for (auto *D : AnonRecord->decls()) {
5455 if ((isa<FieldDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D)) &&
5456 cast<NamedDecl>(Val: D)->getDeclName()) {
5457 ValueDecl *VD = cast<ValueDecl>(Val: D);
5458 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, Name: VD->getDeclName(),
5459 NameLoc: VD->getLocation(), IsUnion: AnonRecord->isUnion(),
5460 SC)) {
5461 // C++ [class.union]p2:
5462 // The names of the members of an anonymous union shall be
5463 // distinct from the names of any other entity in the
5464 // scope in which the anonymous union is declared.
5465 Invalid = true;
5466 } else {
5467 // C++ [class.union]p2:
5468 // For the purpose of name lookup, after the anonymous union
5469 // definition, the members of the anonymous union are
5470 // considered to have been defined in the scope in which the
5471 // anonymous union is declared.
5472 unsigned OldChainingSize = Chaining.size();
5473 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(Val: VD))
5474 Chaining.append(in_start: IF->chain_begin(), in_end: IF->chain_end());
5475 else
5476 Chaining.push_back(Elt: VD);
5477
5478 assert(Chaining.size() >= 2);
5479 NamedDecl **NamedChain =
5480 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5481 for (unsigned i = 0; i < Chaining.size(); i++)
5482 NamedChain[i] = Chaining[i];
5483
5484 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5485 C&: SemaRef.Context, DC: Owner, L: VD->getLocation(), Id: VD->getIdentifier(),
5486 T: VD->getType(), CH: {NamedChain, Chaining.size()});
5487
5488 for (const auto *Attr : VD->attrs())
5489 IndirectField->addAttr(A: Attr->clone(C&: SemaRef.Context));
5490
5491 IndirectField->setAccess(AS);
5492 IndirectField->setImplicit();
5493 SemaRef.PushOnScopeChains(D: IndirectField, S);
5494
5495 // That includes picking up the appropriate access specifier.
5496 if (AS != AS_none) IndirectField->setAccess(AS);
5497
5498 Chaining.resize(N: OldChainingSize);
5499 }
5500 }
5501 }
5502
5503 return Invalid;
5504}
5505
5506/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5507/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5508/// illegal input values are mapped to SC_None.
5509static StorageClass
5510StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5511 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5512 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5513 "Parser allowed 'typedef' as storage class VarDecl.");
5514 switch (StorageClassSpec) {
5515 case DeclSpec::SCS_unspecified: return SC_None;
5516 case DeclSpec::SCS_extern:
5517 if (DS.isExternInLinkageSpec())
5518 return SC_None;
5519 return SC_Extern;
5520 case DeclSpec::SCS_static: return SC_Static;
5521 case DeclSpec::SCS_auto: return SC_Auto;
5522 case DeclSpec::SCS_register: return SC_Register;
5523 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5524 // Illegal SCSs map to None: error reporting is up to the caller.
5525 case DeclSpec::SCS_mutable: // Fall through.
5526 case DeclSpec::SCS_typedef: return SC_None;
5527 }
5528 llvm_unreachable("unknown storage class specifier");
5529}
5530
5531static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5532 assert(Record->hasInClassInitializer());
5533
5534 for (const auto *I : Record->decls()) {
5535 const auto *FD = dyn_cast<FieldDecl>(Val: I);
5536 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
5537 FD = IFD->getAnonField();
5538 if (FD && FD->hasInClassInitializer())
5539 return FD->getLocation();
5540 }
5541
5542 llvm_unreachable("couldn't find in-class initializer");
5543}
5544
5545static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5546 SourceLocation DefaultInitLoc) {
5547 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5548 return;
5549
5550 S.Diag(Loc: DefaultInitLoc, DiagID: diag::err_multiple_mem_union_initialization);
5551 S.Diag(Loc: findDefaultInitializer(Record: Parent), DiagID: diag::note_previous_initializer) << 0;
5552}
5553
5554static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5555 CXXRecordDecl *AnonUnion) {
5556 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5557 return;
5558
5559 checkDuplicateDefaultInit(S, Parent, DefaultInitLoc: findDefaultInitializer(Record: AnonUnion));
5560}
5561
5562Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5563 AccessSpecifier AS,
5564 RecordDecl *Record,
5565 const PrintingPolicy &Policy) {
5566 DeclContext *Owner = Record->getDeclContext();
5567
5568 // Diagnose whether this anonymous struct/union is an extension.
5569 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5570 Diag(Loc: Record->getLocation(), DiagID: diag::ext_anonymous_union);
5571 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5572 Diag(Loc: Record->getLocation(), DiagID: diag::ext_gnu_anonymous_struct);
5573 else if (!Record->isUnion() && !getLangOpts().C11)
5574 Diag(Loc: Record->getLocation(), DiagID: diag::ext_c11_anonymous_struct);
5575
5576 // C and C++ require different kinds of checks for anonymous
5577 // structs/unions.
5578 bool Invalid = false;
5579 if (getLangOpts().CPlusPlus) {
5580 const char *PrevSpec = nullptr;
5581 if (Record->isUnion()) {
5582 // C++ [class.union]p6:
5583 // C++17 [class.union.anon]p2:
5584 // Anonymous unions declared in a named namespace or in the
5585 // global namespace shall be declared static.
5586 unsigned DiagID;
5587 DeclContext *OwnerScope = Owner->getRedeclContext();
5588 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5589 (OwnerScope->isTranslationUnit() ||
5590 (OwnerScope->isNamespace() &&
5591 !cast<NamespaceDecl>(Val: OwnerScope)->isAnonymousNamespace()))) {
5592 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_union_not_static)
5593 << FixItHint::CreateInsertion(InsertionLoc: Record->getLocation(), Code: "static ");
5594
5595 // Recover by adding 'static'.
5596 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_static, Loc: SourceLocation(),
5597 PrevSpec, DiagID, Policy);
5598 }
5599 // C++ [class.union]p6:
5600 // A storage class is not allowed in a declaration of an
5601 // anonymous union in a class scope.
5602 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5603 isa<RecordDecl>(Val: Owner)) {
5604 Diag(Loc: DS.getStorageClassSpecLoc(),
5605 DiagID: diag::err_anonymous_union_with_storage_spec)
5606 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
5607
5608 // Recover by removing the storage specifier.
5609 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_unspecified,
5610 Loc: SourceLocation(),
5611 PrevSpec, DiagID, Policy: Context.getPrintingPolicy());
5612 }
5613 }
5614
5615 // Ignore const/volatile/restrict qualifiers.
5616 if (DS.getTypeQualifiers()) {
5617 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5618 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::ext_anonymous_struct_union_qualified)
5619 << Record->isUnion() << "const"
5620 << FixItHint::CreateRemoval(RemoveRange: DS.getConstSpecLoc());
5621 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5622 Diag(Loc: DS.getVolatileSpecLoc(),
5623 DiagID: diag::ext_anonymous_struct_union_qualified)
5624 << Record->isUnion() << "volatile"
5625 << FixItHint::CreateRemoval(RemoveRange: DS.getVolatileSpecLoc());
5626 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5627 Diag(Loc: DS.getRestrictSpecLoc(),
5628 DiagID: diag::ext_anonymous_struct_union_qualified)
5629 << Record->isUnion() << "restrict"
5630 << FixItHint::CreateRemoval(RemoveRange: DS.getRestrictSpecLoc());
5631 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5632 Diag(Loc: DS.getAtomicSpecLoc(),
5633 DiagID: diag::ext_anonymous_struct_union_qualified)
5634 << Record->isUnion() << "_Atomic"
5635 << FixItHint::CreateRemoval(RemoveRange: DS.getAtomicSpecLoc());
5636 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5637 Diag(Loc: DS.getUnalignedSpecLoc(),
5638 DiagID: diag::ext_anonymous_struct_union_qualified)
5639 << Record->isUnion() << "__unaligned"
5640 << FixItHint::CreateRemoval(RemoveRange: DS.getUnalignedSpecLoc());
5641
5642 DS.ClearTypeQualifiers();
5643 }
5644
5645 // C++ [class.union]p2:
5646 // The member-specification of an anonymous union shall only
5647 // define non-static data members. [Note: nested types and
5648 // functions cannot be declared within an anonymous union. ]
5649 for (auto *Mem : Record->decls()) {
5650 // Ignore invalid declarations; we already diagnosed them.
5651 if (Mem->isInvalidDecl())
5652 continue;
5653
5654 if (auto *FD = dyn_cast<FieldDecl>(Val: Mem)) {
5655 // C++ [class.union]p3:
5656 // An anonymous union shall not have private or protected
5657 // members (clause 11).
5658 assert(FD->getAccess() != AS_none);
5659 if (FD->getAccess() != AS_public) {
5660 Diag(Loc: FD->getLocation(), DiagID: diag::err_anonymous_record_nonpublic_member)
5661 << Record->isUnion() << (FD->getAccess() == AS_protected);
5662 Invalid = true;
5663 }
5664
5665 // C++ [class.union]p1
5666 // An object of a class with a non-trivial constructor, a non-trivial
5667 // copy constructor, a non-trivial destructor, or a non-trivial copy
5668 // assignment operator cannot be a member of a union, nor can an
5669 // array of such objects.
5670 if (CheckNontrivialField(FD))
5671 Invalid = true;
5672 } else if (Mem->isImplicit()) {
5673 // Any implicit members are fine.
5674 } else if (isa<TagDecl>(Val: Mem) && Mem->getDeclContext() != Record) {
5675 // This is a type that showed up in an
5676 // elaborated-type-specifier inside the anonymous struct or
5677 // union, but which actually declares a type outside of the
5678 // anonymous struct or union. It's okay.
5679 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Val: Mem)) {
5680 if (!MemRecord->isAnonymousStructOrUnion() &&
5681 MemRecord->getDeclName()) {
5682 // Visual C++ allows type definition in anonymous struct or union.
5683 if (getLangOpts().MicrosoftExt)
5684 Diag(Loc: MemRecord->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5685 << Record->isUnion();
5686 else {
5687 // This is a nested type declaration.
5688 Diag(Loc: MemRecord->getLocation(), DiagID: diag::err_anonymous_record_with_type)
5689 << Record->isUnion();
5690 Invalid = true;
5691 }
5692 } else {
5693 // This is an anonymous type definition within another anonymous type.
5694 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5695 // not part of standard C++.
5696 Diag(Loc: MemRecord->getLocation(),
5697 DiagID: diag::ext_anonymous_record_with_anonymous_type)
5698 << Record->isUnion();
5699 }
5700 } else if (isa<AccessSpecDecl>(Val: Mem)) {
5701 // Any access specifier is fine.
5702 } else if (isa<StaticAssertDecl>(Val: Mem)) {
5703 // In C++1z, static_assert declarations are also fine.
5704 } else {
5705 // We have something that isn't a non-static data
5706 // member. Complain about it.
5707 unsigned DK = diag::err_anonymous_record_bad_member;
5708 if (isa<TypeDecl>(Val: Mem))
5709 DK = diag::err_anonymous_record_with_type;
5710 else if (isa<FunctionDecl>(Val: Mem))
5711 DK = diag::err_anonymous_record_with_function;
5712 else if (isa<VarDecl>(Val: Mem))
5713 DK = diag::err_anonymous_record_with_static;
5714
5715 // Visual C++ allows type definition in anonymous struct or union.
5716 if (getLangOpts().MicrosoftExt &&
5717 DK == diag::err_anonymous_record_with_type)
5718 Diag(Loc: Mem->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5719 << Record->isUnion();
5720 else {
5721 Diag(Loc: Mem->getLocation(), DiagID: DK) << Record->isUnion();
5722 Invalid = true;
5723 }
5724 }
5725 }
5726
5727 // C++11 [class.union]p8 (DR1460):
5728 // At most one variant member of a union may have a
5729 // brace-or-equal-initializer.
5730 if (cast<CXXRecordDecl>(Val: Record)->hasInClassInitializer() &&
5731 Owner->isRecord())
5732 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Owner),
5733 AnonUnion: cast<CXXRecordDecl>(Val: Record));
5734 }
5735
5736 if (!Record->isUnion() && !Owner->isRecord()) {
5737 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_struct_not_member)
5738 << getLangOpts().CPlusPlus;
5739 Invalid = true;
5740 }
5741
5742 // C++ [dcl.dcl]p3:
5743 // [If there are no declarators], and except for the declaration of an
5744 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5745 // names into the program
5746 // C++ [class.mem]p2:
5747 // each such member-declaration shall either declare at least one member
5748 // name of the class or declare at least one unnamed bit-field
5749 //
5750 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5751 if (getLangOpts().CPlusPlus && Record->field_empty())
5752 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_no_declarators) << DS.getSourceRange();
5753
5754 // Mock up a declarator.
5755 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5756 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5757 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5758 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5759
5760 // Create a declaration for this anonymous struct/union.
5761 NamedDecl *Anon = nullptr;
5762 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Val: Owner)) {
5763 Anon = FieldDecl::Create(
5764 C: Context, DC: OwningClass, StartLoc: DS.getBeginLoc(), IdLoc: Record->getLocation(),
5765 /*IdentifierInfo=*/Id: nullptr, T: Context.getTypeDeclType(Decl: Record), TInfo,
5766 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5767 /*InitStyle=*/ICIS_NoInit);
5768 Anon->setAccess(AS);
5769 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5770
5771 if (getLangOpts().CPlusPlus)
5772 FieldCollector->Add(D: cast<FieldDecl>(Val: Anon));
5773 } else {
5774 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5775 if (SCSpec == DeclSpec::SCS_mutable) {
5776 // mutable can only appear on non-static class members, so it's always
5777 // an error here
5778 Diag(Loc: Record->getLocation(), DiagID: diag::err_mutable_nonmember);
5779 Invalid = true;
5780 SC = SC_None;
5781 }
5782
5783 Anon = VarDecl::Create(C&: Context, DC: Owner, StartLoc: DS.getBeginLoc(),
5784 IdLoc: Record->getLocation(), /*IdentifierInfo=*/Id: nullptr,
5785 T: Context.getTypeDeclType(Decl: Record), TInfo, S: SC);
5786 if (Invalid)
5787 Anon->setInvalidDecl();
5788
5789 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5790
5791 // Default-initialize the implicit variable. This initialization will be
5792 // trivial in almost all cases, except if a union member has an in-class
5793 // initializer:
5794 // union { int n = 0; };
5795 ActOnUninitializedDecl(dcl: Anon);
5796 }
5797 Anon->setImplicit();
5798
5799 // Mark this as an anonymous struct/union type.
5800 Record->setAnonymousStructOrUnion(true);
5801
5802 // Add the anonymous struct/union object to the current
5803 // context. We'll be referencing this object when we refer to one of
5804 // its members.
5805 Owner->addDecl(D: Anon);
5806
5807 // Inject the members of the anonymous struct/union into the owning
5808 // context and into the identifier resolver chain for name lookup
5809 // purposes.
5810 SmallVector<NamedDecl*, 2> Chain;
5811 Chain.push_back(Elt: Anon);
5812
5813 if (InjectAnonymousStructOrUnionMembers(SemaRef&: *this, S, Owner, AnonRecord: Record, AS, SC,
5814 Chaining&: Chain))
5815 Invalid = true;
5816
5817 if (VarDecl *NewVD = dyn_cast<VarDecl>(Val: Anon)) {
5818 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5819 MangleNumberingContext *MCtx;
5820 Decl *ManglingContextDecl;
5821 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5822 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
5823 if (MCtx) {
5824 Context.setManglingNumber(
5825 ND: NewVD, Number: MCtx->getManglingNumber(
5826 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
5827 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
5828 }
5829 }
5830 }
5831
5832 if (Invalid)
5833 Anon->setInvalidDecl();
5834
5835 return Anon;
5836}
5837
5838Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5839 RecordDecl *Record) {
5840 assert(Record && "expected a record!");
5841
5842 // Mock up a declarator.
5843 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5844 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5845 assert(TInfo && "couldn't build declarator info for anonymous struct");
5846
5847 auto *ParentDecl = cast<RecordDecl>(Val: CurContext);
5848 QualType RecTy = Context.getTypeDeclType(Decl: Record);
5849
5850 // Create a declaration for this anonymous struct.
5851 NamedDecl *Anon =
5852 FieldDecl::Create(C: Context, DC: ParentDecl, StartLoc: DS.getBeginLoc(), IdLoc: DS.getBeginLoc(),
5853 /*IdentifierInfo=*/Id: nullptr, T: RecTy, TInfo,
5854 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5855 /*InitStyle=*/ICIS_NoInit);
5856 Anon->setImplicit();
5857
5858 // Add the anonymous struct object to the current context.
5859 CurContext->addDecl(D: Anon);
5860
5861 // Inject the members of the anonymous struct into the current
5862 // context and into the identifier resolver chain for name lookup
5863 // purposes.
5864 SmallVector<NamedDecl*, 2> Chain;
5865 Chain.push_back(Elt: Anon);
5866
5867 RecordDecl *RecordDef = Record->getDefinition();
5868 if (RequireCompleteSizedType(Loc: Anon->getLocation(), T: RecTy,
5869 DiagID: diag::err_field_incomplete_or_sizeless) ||
5870 InjectAnonymousStructOrUnionMembers(
5871 SemaRef&: *this, S, Owner: CurContext, AnonRecord: RecordDef, AS: AS_none,
5872 SC: StorageClassSpecToVarDeclStorageClass(DS), Chaining&: Chain)) {
5873 Anon->setInvalidDecl();
5874 ParentDecl->setInvalidDecl();
5875 }
5876
5877 return Anon;
5878}
5879
5880DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5881 return GetNameFromUnqualifiedId(Name: D.getName());
5882}
5883
5884DeclarationNameInfo
5885Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5886 DeclarationNameInfo NameInfo;
5887 NameInfo.setLoc(Name.StartLocation);
5888
5889 switch (Name.getKind()) {
5890
5891 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5892 case UnqualifiedIdKind::IK_Identifier:
5893 NameInfo.setName(Name.Identifier);
5894 return NameInfo;
5895
5896 case UnqualifiedIdKind::IK_DeductionGuideName: {
5897 // C++ [temp.deduct.guide]p3:
5898 // The simple-template-id shall name a class template specialization.
5899 // The template-name shall be the same identifier as the template-name
5900 // of the simple-template-id.
5901 // These together intend to imply that the template-name shall name a
5902 // class template.
5903 // FIXME: template<typename T> struct X {};
5904 // template<typename T> using Y = X<T>;
5905 // Y(int) -> Y<int>;
5906 // satisfies these rules but does not name a class template.
5907 TemplateName TN = Name.TemplateName.get().get();
5908 auto *Template = TN.getAsTemplateDecl();
5909 if (!Template || !isa<ClassTemplateDecl>(Val: Template)) {
5910 Diag(Loc: Name.StartLocation,
5911 DiagID: diag::err_deduction_guide_name_not_class_template)
5912 << (int)getTemplateNameKindForDiagnostics(Name: TN) << TN;
5913 if (Template)
5914 NoteTemplateLocation(Decl: *Template);
5915 return DeclarationNameInfo();
5916 }
5917
5918 NameInfo.setName(
5919 Context.DeclarationNames.getCXXDeductionGuideName(TD: Template));
5920 return NameInfo;
5921 }
5922
5923 case UnqualifiedIdKind::IK_OperatorFunctionId:
5924 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5925 Op: Name.OperatorFunctionId.Operator));
5926 NameInfo.setCXXOperatorNameRange(SourceRange(
5927 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5928 return NameInfo;
5929
5930 case UnqualifiedIdKind::IK_LiteralOperatorId:
5931 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5932 II: Name.Identifier));
5933 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5934 return NameInfo;
5935
5936 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5937 TypeSourceInfo *TInfo;
5938 QualType Ty = GetTypeFromParser(Ty: Name.ConversionFunctionId, TInfo: &TInfo);
5939 if (Ty.isNull())
5940 return DeclarationNameInfo();
5941 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5942 Ty: Context.getCanonicalType(T: Ty)));
5943 NameInfo.setNamedTypeInfo(TInfo);
5944 return NameInfo;
5945 }
5946
5947 case UnqualifiedIdKind::IK_ConstructorName: {
5948 TypeSourceInfo *TInfo;
5949 QualType Ty = GetTypeFromParser(Ty: Name.ConstructorName, TInfo: &TInfo);
5950 if (Ty.isNull())
5951 return DeclarationNameInfo();
5952 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5953 Ty: Context.getCanonicalType(T: Ty)));
5954 NameInfo.setNamedTypeInfo(TInfo);
5955 return NameInfo;
5956 }
5957
5958 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5959 // In well-formed code, we can only have a constructor
5960 // template-id that refers to the current context, so go there
5961 // to find the actual type being constructed.
5962 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(Val: CurContext);
5963 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5964 return DeclarationNameInfo();
5965
5966 // Determine the type of the class being constructed.
5967 QualType CurClassType = Context.getTypeDeclType(Decl: CurClass);
5968
5969 // FIXME: Check two things: that the template-id names the same type as
5970 // CurClassType, and that the template-id does not occur when the name
5971 // was qualified.
5972
5973 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5974 Ty: Context.getCanonicalType(T: CurClassType)));
5975 // FIXME: should we retrieve TypeSourceInfo?
5976 NameInfo.setNamedTypeInfo(nullptr);
5977 return NameInfo;
5978 }
5979
5980 case UnqualifiedIdKind::IK_DestructorName: {
5981 TypeSourceInfo *TInfo;
5982 QualType Ty = GetTypeFromParser(Ty: Name.DestructorName, TInfo: &TInfo);
5983 if (Ty.isNull())
5984 return DeclarationNameInfo();
5985 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5986 Ty: Context.getCanonicalType(T: Ty)));
5987 NameInfo.setNamedTypeInfo(TInfo);
5988 return NameInfo;
5989 }
5990
5991 case UnqualifiedIdKind::IK_TemplateId: {
5992 TemplateName TName = Name.TemplateId->Template.get();
5993 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5994 return Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
5995 }
5996
5997 } // switch (Name.getKind())
5998
5999 llvm_unreachable("Unknown name kind");
6000}
6001
6002static QualType getCoreType(QualType Ty) {
6003 do {
6004 if (Ty->isPointerOrReferenceType())
6005 Ty = Ty->getPointeeType();
6006 else if (Ty->isArrayType())
6007 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6008 else
6009 return Ty.withoutLocalFastQualifiers();
6010 } while (true);
6011}
6012
6013/// hasSimilarParameters - Determine whether the C++ functions Declaration
6014/// and Definition have "nearly" matching parameters. This heuristic is
6015/// used to improve diagnostics in the case where an out-of-line function
6016/// definition doesn't match any declaration within the class or namespace.
6017/// Also sets Params to the list of indices to the parameters that differ
6018/// between the declaration and the definition. If hasSimilarParameters
6019/// returns true and Params is empty, then all of the parameters match.
6020static bool hasSimilarParameters(ASTContext &Context,
6021 FunctionDecl *Declaration,
6022 FunctionDecl *Definition,
6023 SmallVectorImpl<unsigned> &Params) {
6024 Params.clear();
6025 if (Declaration->param_size() != Definition->param_size())
6026 return false;
6027 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6028 QualType DeclParamTy = Declaration->getParamDecl(i: Idx)->getType();
6029 QualType DefParamTy = Definition->getParamDecl(i: Idx)->getType();
6030
6031 // The parameter types are identical
6032 if (Context.hasSameUnqualifiedType(T1: DefParamTy, T2: DeclParamTy))
6033 continue;
6034
6035 QualType DeclParamBaseTy = getCoreType(Ty: DeclParamTy);
6036 QualType DefParamBaseTy = getCoreType(Ty: DefParamTy);
6037 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6038 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6039
6040 if (Context.hasSameUnqualifiedType(T1: DeclParamBaseTy, T2: DefParamBaseTy) ||
6041 (DeclTyName && DeclTyName == DefTyName))
6042 Params.push_back(Elt: Idx);
6043 else // The two parameters aren't even close
6044 return false;
6045 }
6046
6047 return true;
6048}
6049
6050/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6051/// declarator needs to be rebuilt in the current instantiation.
6052/// Any bits of declarator which appear before the name are valid for
6053/// consideration here. That's specifically the type in the decl spec
6054/// and the base type in any member-pointer chunks.
6055static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6056 DeclarationName Name) {
6057 // The types we specifically need to rebuild are:
6058 // - typenames, typeofs, and decltypes
6059 // - types which will become injected class names
6060 // Of course, we also need to rebuild any type referencing such a
6061 // type. It's safest to just say "dependent", but we call out a
6062 // few cases here.
6063
6064 DeclSpec &DS = D.getMutableDeclSpec();
6065 switch (DS.getTypeSpecType()) {
6066 case DeclSpec::TST_typename:
6067 case DeclSpec::TST_typeofType:
6068 case DeclSpec::TST_typeof_unqualType:
6069#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6070#include "clang/Basic/TransformTypeTraits.def"
6071 case DeclSpec::TST_atomic: {
6072 // Grab the type from the parser.
6073 TypeSourceInfo *TSI = nullptr;
6074 QualType T = S.GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TSI);
6075 if (T.isNull() || !T->isInstantiationDependentType()) break;
6076
6077 // Make sure there's a type source info. This isn't really much
6078 // of a waste; most dependent types should have type source info
6079 // attached already.
6080 if (!TSI)
6081 TSI = S.Context.getTrivialTypeSourceInfo(T, Loc: DS.getTypeSpecTypeLoc());
6082
6083 // Rebuild the type in the current instantiation.
6084 TSI = S.RebuildTypeInCurrentInstantiation(T: TSI, Loc: D.getIdentifierLoc(), Name);
6085 if (!TSI) return true;
6086
6087 // Store the new type back in the decl spec.
6088 ParsedType LocType = S.CreateParsedType(T: TSI->getType(), TInfo: TSI);
6089 DS.UpdateTypeRep(Rep: LocType);
6090 break;
6091 }
6092
6093 case DeclSpec::TST_decltype:
6094 case DeclSpec::TST_typeof_unqualExpr:
6095 case DeclSpec::TST_typeofExpr: {
6096 Expr *E = DS.getRepAsExpr();
6097 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6098 if (Result.isInvalid()) return true;
6099 DS.UpdateExprRep(Rep: Result.get());
6100 break;
6101 }
6102
6103 default:
6104 // Nothing to do for these decl specs.
6105 break;
6106 }
6107
6108 // It doesn't matter what order we do this in.
6109 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6110 DeclaratorChunk &Chunk = D.getTypeObject(i: I);
6111
6112 // The only type information in the declarator which can come
6113 // before the declaration name is the base type of a member
6114 // pointer.
6115 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6116 continue;
6117
6118 // Rebuild the scope specifier in-place.
6119 CXXScopeSpec &SS = Chunk.Mem.Scope();
6120 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6121 return true;
6122 }
6123
6124 return false;
6125}
6126
6127/// Returns true if the declaration is declared in a system header or from a
6128/// system macro.
6129static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6130 return SM.isInSystemHeader(Loc: D->getLocation()) ||
6131 SM.isInSystemMacro(loc: D->getLocation());
6132}
6133
6134void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6135 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6136 // of system decl.
6137 if (D->getPreviousDecl() || D->isImplicit())
6138 return;
6139 ReservedIdentifierStatus Status = D->isReserved(LangOpts: getLangOpts());
6140 if (Status != ReservedIdentifierStatus::NotReserved &&
6141 !isFromSystemHeader(SM&: Context.getSourceManager(), D)) {
6142 Diag(Loc: D->getLocation(), DiagID: diag::warn_reserved_extern_symbol)
6143 << D << static_cast<int>(Status);
6144 }
6145}
6146
6147Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6148 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6149
6150 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6151 // declaration only if the `bind_to_declaration` extension is set.
6152 SmallVector<FunctionDecl *, 4> Bases;
6153 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6154 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6155 TP: llvm::omp::TraitProperty::
6156 implementation_extension_bind_to_declaration))
6157 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6158 S, D, TemplateParameterLists: MultiTemplateParamsArg(), Bases);
6159
6160 Decl *Dcl = HandleDeclarator(S, D, TemplateParameterLists: MultiTemplateParamsArg());
6161
6162 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6163 Dcl && Dcl->getDeclContext()->isFileContext())
6164 Dcl->setTopLevelDeclInObjCContainer();
6165
6166 if (!Bases.empty())
6167 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
6168 Bases);
6169
6170 return Dcl;
6171}
6172
6173bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6174 DeclarationNameInfo NameInfo) {
6175 DeclarationName Name = NameInfo.getName();
6176
6177 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC);
6178 while (Record && Record->isAnonymousStructOrUnion())
6179 Record = dyn_cast<CXXRecordDecl>(Val: Record->getParent());
6180 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6181 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_member_name_of_class) << Name;
6182 return true;
6183 }
6184
6185 return false;
6186}
6187
6188bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6189 DeclarationName Name,
6190 SourceLocation Loc,
6191 TemplateIdAnnotation *TemplateId,
6192 bool IsMemberSpecialization) {
6193 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6194 "without nested-name-specifier");
6195 DeclContext *Cur = CurContext;
6196 while (isa<LinkageSpecDecl>(Val: Cur) || isa<CapturedDecl>(Val: Cur))
6197 Cur = Cur->getParent();
6198
6199 // If the user provided a superfluous scope specifier that refers back to the
6200 // class in which the entity is already declared, diagnose and ignore it.
6201 //
6202 // class X {
6203 // void X::f();
6204 // };
6205 //
6206 // Note, it was once ill-formed to give redundant qualification in all
6207 // contexts, but that rule was removed by DR482.
6208 if (Cur->Equals(DC)) {
6209 if (Cur->isRecord()) {
6210 Diag(Loc, DiagID: LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6211 : diag::err_member_extra_qualification)
6212 << Name << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
6213 SS.clear();
6214 } else {
6215 Diag(Loc, DiagID: diag::warn_namespace_member_extra_qualification) << Name;
6216 }
6217 return false;
6218 }
6219
6220 // Check whether the qualifying scope encloses the scope of the original
6221 // declaration. For a template-id, we perform the checks in
6222 // CheckTemplateSpecializationScope.
6223 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6224 if (Cur->isRecord())
6225 Diag(Loc, DiagID: diag::err_member_qualification)
6226 << Name << SS.getRange();
6227 else if (isa<TranslationUnitDecl>(Val: DC))
6228 Diag(Loc, DiagID: diag::err_invalid_declarator_global_scope)
6229 << Name << SS.getRange();
6230 else if (isa<FunctionDecl>(Val: Cur))
6231 Diag(Loc, DiagID: diag::err_invalid_declarator_in_function)
6232 << Name << SS.getRange();
6233 else if (isa<BlockDecl>(Val: Cur))
6234 Diag(Loc, DiagID: diag::err_invalid_declarator_in_block)
6235 << Name << SS.getRange();
6236 else if (isa<ExportDecl>(Val: Cur)) {
6237 if (!isa<NamespaceDecl>(Val: DC))
6238 Diag(Loc, DiagID: diag::err_export_non_namespace_scope_name)
6239 << Name << SS.getRange();
6240 else
6241 // The cases that DC is not NamespaceDecl should be handled in
6242 // CheckRedeclarationExported.
6243 return false;
6244 } else
6245 Diag(Loc, DiagID: diag::err_invalid_declarator_scope)
6246 << Name << cast<NamedDecl>(Val: Cur) << cast<NamedDecl>(Val: DC) << SS.getRange();
6247
6248 return true;
6249 }
6250
6251 if (Cur->isRecord()) {
6252 // Cannot qualify members within a class.
6253 Diag(Loc, DiagID: diag::err_member_qualification)
6254 << Name << SS.getRange();
6255 SS.clear();
6256
6257 // C++ constructors and destructors with incorrect scopes can break
6258 // our AST invariants by having the wrong underlying types. If
6259 // that's the case, then drop this declaration entirely.
6260 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6261 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6262 !Context.hasSameType(T1: Name.getCXXNameType(),
6263 T2: Context.getTypeDeclType(Decl: cast<CXXRecordDecl>(Val: Cur))))
6264 return true;
6265
6266 return false;
6267 }
6268
6269 // C++23 [temp.names]p5:
6270 // The keyword template shall not appear immediately after a declarative
6271 // nested-name-specifier.
6272 //
6273 // First check the template-id (if any), and then check each component of the
6274 // nested-name-specifier in reverse order.
6275 //
6276 // FIXME: nested-name-specifiers in friend declarations are declarative,
6277 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6278 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6279 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6280 << FixItHint::CreateRemoval(RemoveRange: TemplateId->TemplateKWLoc);
6281
6282 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6283 do {
6284 if (TypeLoc TL = SpecLoc.getTypeLoc()) {
6285 if (SourceLocation TemplateKeywordLoc = TL.getTemplateKeywordLoc();
6286 TemplateKeywordLoc.isValid())
6287 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6288 << FixItHint::CreateRemoval(RemoveRange: TemplateKeywordLoc);
6289 }
6290
6291 if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) {
6292 if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) {
6293 // C++23 [expr.prim.id.qual]p3:
6294 // [...] If a nested-name-specifier N is declarative and has a
6295 // simple-template-id with a template argument list A that involves a
6296 // template parameter, let T be the template nominated by N without A.
6297 // T shall be a class template.
6298 if (TST->isDependentType() && TST->isTypeAlias())
6299 Diag(Loc, DiagID: diag::ext_alias_template_in_declarative_nns)
6300 << SpecLoc.getLocalSourceRange();
6301 } else if (T->isDecltypeType() || T->getAsAdjusted<PackIndexingType>()) {
6302 // C++23 [expr.prim.id.qual]p2:
6303 // [...] A declarative nested-name-specifier shall not have a
6304 // computed-type-specifier.
6305 //
6306 // CWG2858 changed this from 'decltype-specifier' to
6307 // 'computed-type-specifier'.
6308 Diag(Loc, DiagID: diag::err_computed_type_in_declarative_nns)
6309 << T->isDecltypeType() << SpecLoc.getTypeLoc().getSourceRange();
6310 }
6311 }
6312 } while ((SpecLoc = SpecLoc.getPrefix()));
6313
6314 return false;
6315}
6316
6317NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6318 MultiTemplateParamsArg TemplateParamLists) {
6319 // TODO: consider using NameInfo for diagnostic.
6320 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6321 DeclarationName Name = NameInfo.getName();
6322
6323 // All of these full declarators require an identifier. If it doesn't have
6324 // one, the ParsedFreeStandingDeclSpec action should be used.
6325 if (D.isDecompositionDeclarator()) {
6326 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6327 } else if (!Name) {
6328 if (!D.isInvalidType()) // Reject this if we think it is valid.
6329 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_declarator_need_ident)
6330 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6331 return nullptr;
6332 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_DeclarationType))
6333 return nullptr;
6334
6335 DeclContext *DC = CurContext;
6336 if (D.getCXXScopeSpec().isInvalid())
6337 D.setInvalidType();
6338 else if (D.getCXXScopeSpec().isSet()) {
6339 if (DiagnoseUnexpandedParameterPack(SS: D.getCXXScopeSpec(),
6340 UPPC: UPPC_DeclarationQualifier))
6341 return nullptr;
6342
6343 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6344 DC = computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext);
6345 if (!DC || isa<EnumDecl>(Val: DC)) {
6346 // If we could not compute the declaration context, it's because the
6347 // declaration context is dependent but does not refer to a class,
6348 // class template, or class template partial specialization. Complain
6349 // and return early, to avoid the coming semantic disaster.
6350 Diag(Loc: D.getIdentifierLoc(),
6351 DiagID: diag::err_template_qualified_declarator_no_match)
6352 << D.getCXXScopeSpec().getScopeRep()
6353 << D.getCXXScopeSpec().getRange();
6354 return nullptr;
6355 }
6356 bool IsDependentContext = DC->isDependentContext();
6357
6358 if (!IsDependentContext &&
6359 RequireCompleteDeclContext(SS&: D.getCXXScopeSpec(), DC))
6360 return nullptr;
6361
6362 // If a class is incomplete, do not parse entities inside it.
6363 if (isa<CXXRecordDecl>(Val: DC) && !cast<CXXRecordDecl>(Val: DC)->hasDefinition()) {
6364 Diag(Loc: D.getIdentifierLoc(),
6365 DiagID: diag::err_member_def_undefined_record)
6366 << Name << DC << D.getCXXScopeSpec().getRange();
6367 return nullptr;
6368 }
6369 if (!D.getDeclSpec().isFriendSpecified()) {
6370 TemplateIdAnnotation *TemplateId =
6371 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6372 ? D.getName().TemplateId
6373 : nullptr;
6374 if (diagnoseQualifiedDeclaration(SS&: D.getCXXScopeSpec(), DC, Name,
6375 Loc: D.getIdentifierLoc(), TemplateId,
6376 /*IsMemberSpecialization=*/false)) {
6377 if (DC->isRecord())
6378 return nullptr;
6379
6380 D.setInvalidType();
6381 }
6382 }
6383
6384 // Check whether we need to rebuild the type of the given
6385 // declaration in the current instantiation.
6386 if (EnteringContext && IsDependentContext &&
6387 TemplateParamLists.size() != 0) {
6388 ContextRAII SavedContext(*this, DC);
6389 if (RebuildDeclaratorInCurrentInstantiation(S&: *this, D, Name))
6390 D.setInvalidType();
6391 }
6392 }
6393
6394 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6395 QualType R = TInfo->getType();
6396
6397 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
6398 UPPC: UPPC_DeclarationType))
6399 D.setInvalidType();
6400
6401 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6402 forRedeclarationInCurContext());
6403
6404 // See if this is a redefinition of a variable in the same scope.
6405 if (!D.getCXXScopeSpec().isSet()) {
6406 bool IsLinkageLookup = false;
6407 bool CreateBuiltins = false;
6408
6409 // If the declaration we're planning to build will be a function
6410 // or object with linkage, then look for another declaration with
6411 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6412 //
6413 // If the declaration we're planning to build will be declared with
6414 // external linkage in the translation unit, create any builtin with
6415 // the same name.
6416 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6417 /* Do nothing*/;
6418 else if (CurContext->isFunctionOrMethod() &&
6419 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6420 R->isFunctionType())) {
6421 IsLinkageLookup = true;
6422 CreateBuiltins =
6423 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6424 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6425 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6426 CreateBuiltins = true;
6427
6428 if (IsLinkageLookup) {
6429 Previous.clear(Kind: LookupRedeclarationWithLinkage);
6430 Previous.setRedeclarationKind(
6431 RedeclarationKind::ForExternalRedeclaration);
6432 }
6433
6434 LookupName(R&: Previous, S, AllowBuiltinCreation: CreateBuiltins);
6435 } else { // Something like "int foo::x;"
6436 LookupQualifiedName(R&: Previous, LookupCtx: DC);
6437
6438 // C++ [dcl.meaning]p1:
6439 // When the declarator-id is qualified, the declaration shall refer to a
6440 // previously declared member of the class or namespace to which the
6441 // qualifier refers (or, in the case of a namespace, of an element of the
6442 // inline namespace set of that namespace (7.3.1)) or to a specialization
6443 // thereof; [...]
6444 //
6445 // Note that we already checked the context above, and that we do not have
6446 // enough information to make sure that Previous contains the declaration
6447 // we want to match. For example, given:
6448 //
6449 // class X {
6450 // void f();
6451 // void f(float);
6452 // };
6453 //
6454 // void X::f(int) { } // ill-formed
6455 //
6456 // In this case, Previous will point to the overload set
6457 // containing the two f's declared in X, but neither of them
6458 // matches.
6459
6460 RemoveUsingDecls(R&: Previous);
6461 }
6462
6463 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6464 TPD && TPD->isTemplateParameter()) {
6465 // Older versions of clang allowed the names of function/variable templates
6466 // to shadow the names of their template parameters. For the compatibility
6467 // purposes we detect such cases and issue a default-to-error warning that
6468 // can be disabled with -Wno-strict-primary-template-shadow.
6469 if (!D.isInvalidType()) {
6470 bool AllowForCompatibility = false;
6471 if (Scope *DeclParent = S->getDeclParent();
6472 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6473 AllowForCompatibility = DeclParent->Contains(rhs: *TemplateParamParent) &&
6474 TemplateParamParent->isDeclScope(D: TPD);
6475 }
6476 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl: TPD,
6477 SupportedForCompatibility: AllowForCompatibility);
6478 }
6479
6480 // Just pretend that we didn't see the previous declaration.
6481 Previous.clear();
6482 }
6483
6484 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6485 // Forget that the previous declaration is the injected-class-name.
6486 Previous.clear();
6487
6488 // In C++, the previous declaration we find might be a tag type
6489 // (class or enum). In this case, the new declaration will hide the
6490 // tag type. Note that this applies to functions, function templates, and
6491 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6492 if (Previous.isSingleTagDecl() &&
6493 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6494 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6495 Previous.clear();
6496
6497 // Check that there are no default arguments other than in the parameters
6498 // of a function declaration (C++ only).
6499 if (getLangOpts().CPlusPlus)
6500 CheckExtraCXXDefaultArguments(D);
6501
6502 /// Get the innermost enclosing declaration scope.
6503 S = S->getDeclParent();
6504
6505 NamedDecl *New;
6506
6507 bool AddToScope = true;
6508 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6509 if (TemplateParamLists.size()) {
6510 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_typedef);
6511 return nullptr;
6512 }
6513
6514 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6515 } else if (R->isFunctionType()) {
6516 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6517 TemplateParamLists,
6518 AddToScope);
6519 } else {
6520 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6521 AddToScope);
6522 }
6523
6524 if (!New)
6525 return nullptr;
6526
6527 warnOnCTypeHiddenInCPlusPlus(D: New);
6528
6529 // If this has an identifier and is not a function template specialization,
6530 // add it to the scope stack.
6531 if (New->getDeclName() && AddToScope)
6532 PushOnScopeChains(D: New, S);
6533
6534 if (OpenMP().isInOpenMPDeclareTargetContext())
6535 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
6536
6537 return New;
6538}
6539
6540/// Helper method to turn variable array types into constant array
6541/// types in certain situations which would otherwise be errors (for
6542/// GCC compatibility).
6543static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6544 ASTContext &Context,
6545 bool &SizeIsNegative,
6546 llvm::APSInt &Oversized) {
6547 // This method tries to turn a variable array into a constant
6548 // array even when the size isn't an ICE. This is necessary
6549 // for compatibility with code that depends on gcc's buggy
6550 // constant expression folding, like struct {char x[(int)(char*)2];}
6551 SizeIsNegative = false;
6552 Oversized = 0;
6553
6554 if (T->isDependentType())
6555 return QualType();
6556
6557 QualifierCollector Qs;
6558 const Type *Ty = Qs.strip(type: T);
6559
6560 if (const PointerType* PTy = dyn_cast<PointerType>(Val: Ty)) {
6561 QualType Pointee = PTy->getPointeeType();
6562 QualType FixedType =
6563 TryToFixInvalidVariablyModifiedType(T: Pointee, Context, SizeIsNegative,
6564 Oversized);
6565 if (FixedType.isNull()) return FixedType;
6566 FixedType = Context.getPointerType(T: FixedType);
6567 return Qs.apply(Context, QT: FixedType);
6568 }
6569 if (const ParenType* PTy = dyn_cast<ParenType>(Val: Ty)) {
6570 QualType Inner = PTy->getInnerType();
6571 QualType FixedType =
6572 TryToFixInvalidVariablyModifiedType(T: Inner, Context, SizeIsNegative,
6573 Oversized);
6574 if (FixedType.isNull()) return FixedType;
6575 FixedType = Context.getParenType(NamedType: FixedType);
6576 return Qs.apply(Context, QT: FixedType);
6577 }
6578
6579 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(Val&: T);
6580 if (!VLATy)
6581 return QualType();
6582
6583 QualType ElemTy = VLATy->getElementType();
6584 if (ElemTy->isVariablyModifiedType()) {
6585 ElemTy = TryToFixInvalidVariablyModifiedType(T: ElemTy, Context,
6586 SizeIsNegative, Oversized);
6587 if (ElemTy.isNull())
6588 return QualType();
6589 }
6590
6591 Expr::EvalResult Result;
6592 if (!VLATy->getSizeExpr() ||
6593 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Ctx: Context))
6594 return QualType();
6595
6596 llvm::APSInt Res = Result.Val.getInt();
6597
6598 // Check whether the array size is negative.
6599 if (Res.isSigned() && Res.isNegative()) {
6600 SizeIsNegative = true;
6601 return QualType();
6602 }
6603
6604 // Check whether the array is too large to be addressed.
6605 unsigned ActiveSizeBits =
6606 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6607 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6608 ? ConstantArrayType::getNumAddressingBits(Context, ElementType: ElemTy, NumElements: Res)
6609 : Res.getActiveBits();
6610 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6611 Oversized = Res;
6612 return QualType();
6613 }
6614
6615 QualType FoldedArrayType = Context.getConstantArrayType(
6616 EltTy: ElemTy, ArySize: Res, SizeExpr: VLATy->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6617 return Qs.apply(Context, QT: FoldedArrayType);
6618}
6619
6620static void
6621FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6622 SrcTL = SrcTL.getUnqualifiedLoc();
6623 DstTL = DstTL.getUnqualifiedLoc();
6624 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6625 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6626 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getPointeeLoc(),
6627 DstTL: DstPTL.getPointeeLoc());
6628 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6629 return;
6630 }
6631 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6632 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6633 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getInnerLoc(),
6634 DstTL: DstPTL.getInnerLoc());
6635 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6636 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6637 return;
6638 }
6639 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6640 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6641 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6642 TypeLoc DstElemTL = DstATL.getElementLoc();
6643 if (VariableArrayTypeLoc SrcElemATL =
6644 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6645 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6646 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcElemATL, DstTL: DstElemATL);
6647 } else {
6648 DstElemTL.initializeFullCopy(Other: SrcElemTL);
6649 }
6650 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6651 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6652 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6653}
6654
6655/// Helper method to turn variable array types into constant array
6656/// types in certain situations which would otherwise be errors (for
6657/// GCC compatibility).
6658static TypeSourceInfo*
6659TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6660 ASTContext &Context,
6661 bool &SizeIsNegative,
6662 llvm::APSInt &Oversized) {
6663 QualType FixedTy
6664 = TryToFixInvalidVariablyModifiedType(T: TInfo->getType(), Context,
6665 SizeIsNegative, Oversized);
6666 if (FixedTy.isNull())
6667 return nullptr;
6668 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(T: FixedTy);
6669 FixInvalidVariablyModifiedTypeLoc(SrcTL: TInfo->getTypeLoc(),
6670 DstTL: FixedTInfo->getTypeLoc());
6671 return FixedTInfo;
6672}
6673
6674bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6675 QualType &T, SourceLocation Loc,
6676 unsigned FailedFoldDiagID) {
6677 bool SizeIsNegative;
6678 llvm::APSInt Oversized;
6679 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6680 TInfo, Context, SizeIsNegative, Oversized);
6681 if (FixedTInfo) {
6682 Diag(Loc, DiagID: diag::ext_vla_folded_to_constant);
6683 TInfo = FixedTInfo;
6684 T = FixedTInfo->getType();
6685 return true;
6686 }
6687
6688 if (SizeIsNegative)
6689 Diag(Loc, DiagID: diag::err_typecheck_negative_array_size);
6690 else if (Oversized.getBoolValue())
6691 Diag(Loc, DiagID: diag::err_array_too_large) << toString(I: Oversized, Radix: 10);
6692 else if (FailedFoldDiagID)
6693 Diag(Loc, DiagID: FailedFoldDiagID);
6694 return false;
6695}
6696
6697void
6698Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6699 if (!getLangOpts().CPlusPlus &&
6700 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6701 // Don't need to track declarations in the TU in C.
6702 return;
6703
6704 // Note that we have a locally-scoped external with this name.
6705 Context.getExternCContextDecl()->makeDeclVisibleInContext(D: ND);
6706}
6707
6708NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6709 // FIXME: We can have multiple results via __attribute__((overloadable)).
6710 auto Result = Context.getExternCContextDecl()->lookup(Name);
6711 return Result.empty() ? nullptr : *Result.begin();
6712}
6713
6714void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6715 // FIXME: We should probably indicate the identifier in question to avoid
6716 // confusion for constructs like "virtual int a(), b;"
6717 if (DS.isVirtualSpecified())
6718 Diag(Loc: DS.getVirtualSpecLoc(),
6719 DiagID: diag::err_virtual_non_function);
6720
6721 if (DS.hasExplicitSpecifier())
6722 Diag(Loc: DS.getExplicitSpecLoc(),
6723 DiagID: diag::err_explicit_non_function);
6724
6725 if (DS.isNoreturnSpecified())
6726 Diag(Loc: DS.getNoreturnSpecLoc(),
6727 DiagID: diag::err_noreturn_non_function);
6728}
6729
6730NamedDecl*
6731Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6732 TypeSourceInfo *TInfo, LookupResult &Previous) {
6733 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6734 if (D.getCXXScopeSpec().isSet()) {
6735 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_typedef_declarator)
6736 << D.getCXXScopeSpec().getRange();
6737 D.setInvalidType();
6738 // Pretend we didn't see the scope specifier.
6739 DC = CurContext;
6740 Previous.clear();
6741 }
6742
6743 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
6744
6745 if (D.getDeclSpec().isInlineSpecified())
6746 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
6747 DiagID: (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6748 ? diag::warn_ms_inline_non_function
6749 : diag::err_inline_non_function)
6750 << getLangOpts().CPlusPlus17;
6751 if (D.getDeclSpec().hasConstexprSpecifier())
6752 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
6753 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6754
6755 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6756 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6757 Diag(Loc: D.getName().StartLocation,
6758 DiagID: diag::err_deduction_guide_invalid_specifier)
6759 << "typedef";
6760 else
6761 Diag(Loc: D.getName().StartLocation, DiagID: diag::err_typedef_not_identifier)
6762 << D.getName().getSourceRange();
6763 return nullptr;
6764 }
6765
6766 TypedefDecl *NewTD = ParseTypedefDecl(S, D, T: TInfo->getType(), TInfo);
6767 if (!NewTD) return nullptr;
6768
6769 // Handle attributes prior to checking for duplicates in MergeVarDecl
6770 ProcessDeclAttributes(S, D: NewTD, PD: D);
6771
6772 CheckTypedefForVariablyModifiedType(S, D: NewTD);
6773
6774 bool Redeclaration = D.isRedeclaration();
6775 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, D: NewTD, Previous, Redeclaration);
6776 D.setRedeclaration(Redeclaration);
6777 return ND;
6778}
6779
6780void
6781Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6782 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6783 // then it shall have block scope.
6784 // Note that variably modified types must be fixed before merging the decl so
6785 // that redeclarations will match.
6786 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6787 QualType T = TInfo->getType();
6788 if (T->isVariablyModifiedType()) {
6789 setFunctionHasBranchProtectedScope();
6790
6791 if (S->getFnParent() == nullptr) {
6792 bool SizeIsNegative;
6793 llvm::APSInt Oversized;
6794 TypeSourceInfo *FixedTInfo =
6795 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6796 SizeIsNegative,
6797 Oversized);
6798 if (FixedTInfo) {
6799 Diag(Loc: NewTD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
6800 NewTD->setTypeSourceInfo(FixedTInfo);
6801 } else {
6802 if (SizeIsNegative)
6803 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_typecheck_negative_array_size);
6804 else if (T->isVariableArrayType())
6805 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope);
6806 else if (Oversized.getBoolValue())
6807 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_array_too_large)
6808 << toString(I: Oversized, Radix: 10);
6809 else
6810 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
6811 NewTD->setInvalidDecl();
6812 }
6813 }
6814 }
6815}
6816
6817NamedDecl*
6818Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6819 LookupResult &Previous, bool &Redeclaration) {
6820
6821 // Find the shadowed declaration before filtering for scope.
6822 NamedDecl *ShadowedDecl = getShadowedDeclaration(D: NewTD, R: Previous);
6823
6824 // Merge the decl with the existing one if appropriate. If the decl is
6825 // in an outer scope, it isn't the same thing.
6826 FilterLookupForScope(R&: Previous, Ctx: DC, S, /*ConsiderLinkage*/false,
6827 /*AllowInlineNamespace*/false);
6828 filterNonConflictingPreviousTypedefDecls(S&: *this, Decl: NewTD, Previous);
6829 if (!Previous.empty()) {
6830 Redeclaration = true;
6831 MergeTypedefNameDecl(S, New: NewTD, OldDecls&: Previous);
6832 } else {
6833 inferGslPointerAttribute(TD: NewTD);
6834 }
6835
6836 if (ShadowedDecl && !Redeclaration)
6837 CheckShadow(D: NewTD, ShadowedDecl, R: Previous);
6838
6839 // If this is the C FILE type, notify the AST context.
6840 if (IdentifierInfo *II = NewTD->getIdentifier())
6841 if (!NewTD->isInvalidDecl() &&
6842 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6843 switch (II->getNotableIdentifierID()) {
6844 case tok::NotableIdentifierKind::FILE:
6845 Context.setFILEDecl(NewTD);
6846 break;
6847 case tok::NotableIdentifierKind::jmp_buf:
6848 Context.setjmp_bufDecl(NewTD);
6849 break;
6850 case tok::NotableIdentifierKind::sigjmp_buf:
6851 Context.setsigjmp_bufDecl(NewTD);
6852 break;
6853 case tok::NotableIdentifierKind::ucontext_t:
6854 Context.setucontext_tDecl(NewTD);
6855 break;
6856 case tok::NotableIdentifierKind::float_t:
6857 case tok::NotableIdentifierKind::double_t:
6858 NewTD->addAttr(A: AvailableOnlyInDefaultEvalMethodAttr::Create(Ctx&: Context));
6859 break;
6860 default:
6861 break;
6862 }
6863 }
6864
6865 return NewTD;
6866}
6867
6868/// Determines whether the given declaration is an out-of-scope
6869/// previous declaration.
6870///
6871/// This routine should be invoked when name lookup has found a
6872/// previous declaration (PrevDecl) that is not in the scope where a
6873/// new declaration by the same name is being introduced. If the new
6874/// declaration occurs in a local scope, previous declarations with
6875/// linkage may still be considered previous declarations (C99
6876/// 6.2.2p4-5, C++ [basic.link]p6).
6877///
6878/// \param PrevDecl the previous declaration found by name
6879/// lookup
6880///
6881/// \param DC the context in which the new declaration is being
6882/// declared.
6883///
6884/// \returns true if PrevDecl is an out-of-scope previous declaration
6885/// for a new delcaration with the same name.
6886static bool
6887isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6888 ASTContext &Context) {
6889 if (!PrevDecl)
6890 return false;
6891
6892 if (!PrevDecl->hasLinkage())
6893 return false;
6894
6895 if (Context.getLangOpts().CPlusPlus) {
6896 // C++ [basic.link]p6:
6897 // If there is a visible declaration of an entity with linkage
6898 // having the same name and type, ignoring entities declared
6899 // outside the innermost enclosing namespace scope, the block
6900 // scope declaration declares that same entity and receives the
6901 // linkage of the previous declaration.
6902 DeclContext *OuterContext = DC->getRedeclContext();
6903 if (!OuterContext->isFunctionOrMethod())
6904 // This rule only applies to block-scope declarations.
6905 return false;
6906
6907 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6908 if (PrevOuterContext->isRecord())
6909 // We found a member function: ignore it.
6910 return false;
6911
6912 // Find the innermost enclosing namespace for the new and
6913 // previous declarations.
6914 OuterContext = OuterContext->getEnclosingNamespaceContext();
6915 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6916
6917 // The previous declaration is in a different namespace, so it
6918 // isn't the same function.
6919 if (!OuterContext->Equals(DC: PrevOuterContext))
6920 return false;
6921 }
6922
6923 return true;
6924}
6925
6926static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6927 CXXScopeSpec &SS = D.getCXXScopeSpec();
6928 if (!SS.isSet()) return;
6929 DD->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
6930}
6931
6932void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6933 if (Decl->getType().hasAddressSpace())
6934 return;
6935 if (Decl->getType()->isDependentType())
6936 return;
6937 if (VarDecl *Var = dyn_cast<VarDecl>(Val: Decl)) {
6938 QualType Type = Var->getType();
6939 if (Type->isSamplerT() || Type->isVoidType())
6940 return;
6941 LangAS ImplAS = LangAS::opencl_private;
6942 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6943 // __opencl_c_program_scope_global_variables feature, the address space
6944 // for a variable at program scope or a static or extern variable inside
6945 // a function are inferred to be __global.
6946 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()) &&
6947 Var->hasGlobalStorage())
6948 ImplAS = LangAS::opencl_global;
6949 // If the original type from a decayed type is an array type and that array
6950 // type has no address space yet, deduce it now.
6951 if (auto DT = dyn_cast<DecayedType>(Val&: Type)) {
6952 auto OrigTy = DT->getOriginalType();
6953 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6954 // Add the address space to the original array type and then propagate
6955 // that to the element type through `getAsArrayType`.
6956 OrigTy = Context.getAddrSpaceQualType(T: OrigTy, AddressSpace: ImplAS);
6957 OrigTy = QualType(Context.getAsArrayType(T: OrigTy), 0);
6958 // Re-generate the decayed type.
6959 Type = Context.getDecayedType(T: OrigTy);
6960 }
6961 }
6962 Type = Context.getAddrSpaceQualType(T: Type, AddressSpace: ImplAS);
6963 // Apply any qualifiers (including address space) from the array type to
6964 // the element type. This implements C99 6.7.3p8: "If the specification of
6965 // an array type includes any type qualifiers, the element type is so
6966 // qualified, not the array type."
6967 if (Type->isArrayType())
6968 Type = QualType(Context.getAsArrayType(T: Type), 0);
6969 Decl->setType(Type);
6970 }
6971}
6972
6973static void checkWeakAttr(Sema &S, NamedDecl &ND) {
6974 // 'weak' only applies to declarations with external linkage.
6975 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6976 if (!ND.isExternallyVisible()) {
6977 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weak_static);
6978 ND.dropAttr<WeakAttr>();
6979 }
6980 }
6981}
6982
6983static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
6984 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6985 if (ND.isExternallyVisible()) {
6986 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weakref_not_static);
6987 ND.dropAttrs<WeakRefAttr, AliasAttr>();
6988 }
6989 }
6990}
6991
6992static void checkAliasAttr(Sema &S, NamedDecl &ND) {
6993 if (auto *VD = dyn_cast<VarDecl>(Val: &ND)) {
6994 if (VD->hasInit()) {
6995 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6996 assert(VD->isThisDeclarationADefinition() &&
6997 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6998 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << VD << 0;
6999 VD->dropAttr<AliasAttr>();
7000 }
7001 }
7002 }
7003}
7004
7005static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7006 // 'selectany' only applies to externally visible variable declarations.
7007 // It does not apply to functions.
7008 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7009 if (isa<FunctionDecl>(Val: ND) || !ND.isExternallyVisible()) {
7010 S.Diag(Loc: Attr->getLocation(),
7011 DiagID: diag::err_attribute_selectany_non_extern_data);
7012 ND.dropAttr<SelectAnyAttr>();
7013 }
7014 }
7015}
7016
7017static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND) {
7018 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7019 if (!ND.isExternallyVisible())
7020 S.Diag(Loc: Attr->getLocation(),
7021 DiagID: diag::warn_attribute_hybrid_patchable_non_extern);
7022 }
7023}
7024
7025static void checkInheritableAttr(Sema &S, NamedDecl &ND) {
7026 if (const InheritableAttr *Attr = getDLLAttr(D: &ND)) {
7027 auto *VD = dyn_cast<VarDecl>(Val: &ND);
7028 bool IsAnonymousNS = false;
7029 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7030 if (VD) {
7031 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: VD->getDeclContext());
7032 while (NS && !IsAnonymousNS) {
7033 IsAnonymousNS = NS->isAnonymousNamespace();
7034 NS = dyn_cast<NamespaceDecl>(Val: NS->getParent());
7035 }
7036 }
7037 // dll attributes require external linkage. Static locals may have external
7038 // linkage but still cannot be explicitly imported or exported.
7039 // In Microsoft mode, a variable defined in anonymous namespace must have
7040 // external linkage in order to be exported.
7041 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7042 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7043 (!AnonNSInMicrosoftMode &&
7044 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7045 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_attribute_dll_not_extern)
7046 << &ND << Attr;
7047 ND.setInvalidDecl();
7048 }
7049 }
7050}
7051
7052static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND) {
7053 // Check the attributes on the function type and function params, if any.
7054 if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND)) {
7055 FD = FD->getMostRecentDecl();
7056 // Don't declare this variable in the second operand of the for-statement;
7057 // GCC miscompiles that by ending its lifetime before evaluating the
7058 // third operand. See gcc.gnu.org/PR86769.
7059 AttributedTypeLoc ATL;
7060 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7061 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7062 TL = ATL.getModifiedLoc()) {
7063 // The [[lifetimebound]] attribute can be applied to the implicit object
7064 // parameter of a non-static member function (other than a ctor or dtor)
7065 // by applying it to the function type.
7066 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7067 const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
7068 int NoImplicitObjectError = -1;
7069 if (!MD)
7070 NoImplicitObjectError = 0;
7071 else if (MD->isStatic())
7072 NoImplicitObjectError = 1;
7073 else if (MD->isExplicitObjectMemberFunction())
7074 NoImplicitObjectError = 2;
7075 if (NoImplicitObjectError != -1) {
7076 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_no_object_param)
7077 << NoImplicitObjectError << A->getRange();
7078 } else if (isa<CXXConstructorDecl>(Val: MD) || isa<CXXDestructorDecl>(Val: MD)) {
7079 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_ctor_dtor)
7080 << isa<CXXDestructorDecl>(Val: MD) << A->getRange();
7081 } else if (MD->getReturnType()->isVoidType()) {
7082 S.Diag(
7083 Loc: MD->getLocation(),
7084 DiagID: diag::
7085 err_lifetimebound_implicit_object_parameter_void_return_type);
7086 }
7087 }
7088 }
7089
7090 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7091 const ParmVarDecl *P = FD->getParamDecl(i: I);
7092
7093 // The [[lifetimebound]] attribute can be applied to a function parameter
7094 // only if the function returns a value.
7095 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7096 if (!isa<CXXConstructorDecl>(Val: FD) && FD->getReturnType()->isVoidType()) {
7097 S.Diag(Loc: A->getLocation(),
7098 DiagID: diag::err_lifetimebound_parameter_void_return_type);
7099 }
7100 }
7101 }
7102 }
7103}
7104
7105static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7106 // Ensure that an auto decl is deduced otherwise the checks below might cache
7107 // the wrong linkage.
7108 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7109
7110 checkWeakAttr(S, ND);
7111 checkWeakRefAttr(S, ND);
7112 checkAliasAttr(S, ND);
7113 checkSelectAnyAttr(S, ND);
7114 checkHybridPatchableAttr(S, ND);
7115 checkInheritableAttr(S, ND);
7116 checkLifetimeBoundAttr(S, ND);
7117}
7118
7119static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7120 NamedDecl *NewDecl,
7121 bool IsSpecialization,
7122 bool IsDefinition) {
7123 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7124 return;
7125
7126 bool IsTemplate = false;
7127 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(Val: OldDecl)) {
7128 OldDecl = OldTD->getTemplatedDecl();
7129 IsTemplate = true;
7130 if (!IsSpecialization)
7131 IsDefinition = false;
7132 }
7133 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(Val: NewDecl)) {
7134 NewDecl = NewTD->getTemplatedDecl();
7135 IsTemplate = true;
7136 }
7137
7138 if (!OldDecl || !NewDecl)
7139 return;
7140
7141 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7142 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7143 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7144 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7145
7146 // dllimport and dllexport are inheritable attributes so we have to exclude
7147 // inherited attribute instances.
7148 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7149 (NewExportAttr && !NewExportAttr->isInherited());
7150
7151 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7152 // the only exception being explicit specializations.
7153 // Implicitly generated declarations are also excluded for now because there
7154 // is no other way to switch these to use dllimport or dllexport.
7155 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7156
7157 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7158 // Allow with a warning for free functions and global variables.
7159 bool JustWarn = false;
7160 if (!OldDecl->isCXXClassMember()) {
7161 auto *VD = dyn_cast<VarDecl>(Val: OldDecl);
7162 if (VD && !VD->getDescribedVarTemplate())
7163 JustWarn = true;
7164 auto *FD = dyn_cast<FunctionDecl>(Val: OldDecl);
7165 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7166 JustWarn = true;
7167 }
7168
7169 // We cannot change a declaration that's been used because IR has already
7170 // been emitted. Dllimported functions will still work though (modulo
7171 // address equality) as they can use the thunk.
7172 if (OldDecl->isUsed())
7173 if (!isa<FunctionDecl>(Val: OldDecl) || !NewImportAttr)
7174 JustWarn = false;
7175
7176 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7177 : diag::err_attribute_dll_redeclaration;
7178 S.Diag(Loc: NewDecl->getLocation(), DiagID)
7179 << NewDecl
7180 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7181 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7182 if (!JustWarn) {
7183 NewDecl->setInvalidDecl();
7184 return;
7185 }
7186 }
7187
7188 // A redeclaration is not allowed to drop a dllimport attribute, the only
7189 // exceptions being inline function definitions (except for function
7190 // templates), local extern declarations, qualified friend declarations or
7191 // special MSVC extension: in the last case, the declaration is treated as if
7192 // it were marked dllexport.
7193 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7194 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7195 if (const auto *VD = dyn_cast<VarDecl>(Val: NewDecl)) {
7196 // Ignore static data because out-of-line definitions are diagnosed
7197 // separately.
7198 IsStaticDataMember = VD->isStaticDataMember();
7199 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7200 VarDecl::DeclarationOnly;
7201 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: NewDecl)) {
7202 IsInline = FD->isInlined();
7203 IsQualifiedFriend = FD->getQualifier() &&
7204 FD->getFriendObjectKind() == Decl::FOK_Declared;
7205 }
7206
7207 if (OldImportAttr && !HasNewAttr &&
7208 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7209 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7210 if (IsMicrosoftABI && IsDefinition) {
7211 if (IsSpecialization) {
7212 S.Diag(
7213 Loc: NewDecl->getLocation(),
7214 DiagID: diag::err_attribute_dllimport_function_specialization_definition);
7215 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_attribute);
7216 NewDecl->dropAttr<DLLImportAttr>();
7217 } else {
7218 S.Diag(Loc: NewDecl->getLocation(),
7219 DiagID: diag::warn_redeclaration_without_import_attribute)
7220 << NewDecl;
7221 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7222 NewDecl->dropAttr<DLLImportAttr>();
7223 NewDecl->addAttr(A: DLLExportAttr::CreateImplicit(
7224 Ctx&: S.Context, Range: NewImportAttr->getRange()));
7225 }
7226 } else if (IsMicrosoftABI && IsSpecialization) {
7227 assert(!IsDefinition);
7228 // MSVC allows this. Keep the inherited attribute.
7229 } else {
7230 S.Diag(Loc: NewDecl->getLocation(),
7231 DiagID: diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7232 << NewDecl << OldImportAttr;
7233 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7234 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_previous_attribute);
7235 OldDecl->dropAttr<DLLImportAttr>();
7236 NewDecl->dropAttr<DLLImportAttr>();
7237 }
7238 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7239 // In MinGW, seeing a function declared inline drops the dllimport
7240 // attribute.
7241 OldDecl->dropAttr<DLLImportAttr>();
7242 NewDecl->dropAttr<DLLImportAttr>();
7243 S.Diag(Loc: NewDecl->getLocation(),
7244 DiagID: diag::warn_dllimport_dropped_from_inline_function)
7245 << NewDecl << OldImportAttr;
7246 }
7247
7248 // A specialization of a class template member function is processed here
7249 // since it's a redeclaration. If the parent class is dllexport, the
7250 // specialization inherits that attribute. This doesn't happen automatically
7251 // since the parent class isn't instantiated until later.
7252 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDecl)) {
7253 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7254 !NewImportAttr && !NewExportAttr) {
7255 if (const DLLExportAttr *ParentExportAttr =
7256 MD->getParent()->getAttr<DLLExportAttr>()) {
7257 DLLExportAttr *NewAttr = ParentExportAttr->clone(C&: S.Context);
7258 NewAttr->setInherited(true);
7259 NewDecl->addAttr(A: NewAttr);
7260 }
7261 }
7262 }
7263}
7264
7265/// Given that we are within the definition of the given function,
7266/// will that definition behave like C99's 'inline', where the
7267/// definition is discarded except for optimization purposes?
7268static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7269 // Try to avoid calling GetGVALinkageForFunction.
7270
7271 // All cases of this require the 'inline' keyword.
7272 if (!FD->isInlined()) return false;
7273
7274 // This is only possible in C++ with the gnu_inline attribute.
7275 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7276 return false;
7277
7278 // Okay, go ahead and call the relatively-more-expensive function.
7279 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7280}
7281
7282/// Determine whether a variable is extern "C" prior to attaching
7283/// an initializer. We can't just call isExternC() here, because that
7284/// will also compute and cache whether the declaration is externally
7285/// visible, which might change when we attach the initializer.
7286///
7287/// This can only be used if the declaration is known to not be a
7288/// redeclaration of an internal linkage declaration.
7289///
7290/// For instance:
7291///
7292/// auto x = []{};
7293///
7294/// Attaching the initializer here makes this declaration not externally
7295/// visible, because its type has internal linkage.
7296///
7297/// FIXME: This is a hack.
7298template<typename T>
7299static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7300 if (S.getLangOpts().CPlusPlus) {
7301 // In C++, the overloadable attribute negates the effects of extern "C".
7302 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7303 return false;
7304
7305 // So do CUDA's host/device attributes.
7306 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7307 D->template hasAttr<CUDAHostAttr>()))
7308 return false;
7309 }
7310 return D->isExternC();
7311}
7312
7313static bool shouldConsiderLinkage(const VarDecl *VD) {
7314 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7315 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(Val: DC) ||
7316 isa<OMPDeclareMapperDecl>(Val: DC))
7317 return VD->hasExternalStorage();
7318 if (DC->isFileContext())
7319 return true;
7320 if (DC->isRecord())
7321 return false;
7322 if (DC->getDeclKind() == Decl::HLSLBuffer)
7323 return false;
7324
7325 if (isa<RequiresExprBodyDecl>(Val: DC))
7326 return false;
7327 llvm_unreachable("Unexpected context");
7328}
7329
7330static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7331 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7332 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7333 isa<OMPDeclareReductionDecl>(Val: DC) || isa<OMPDeclareMapperDecl>(Val: DC))
7334 return true;
7335 if (DC->isRecord())
7336 return false;
7337 llvm_unreachable("Unexpected context");
7338}
7339
7340static bool hasParsedAttr(Scope *S, const Declarator &PD,
7341 ParsedAttr::Kind Kind) {
7342 // Check decl attributes on the DeclSpec.
7343 if (PD.getDeclSpec().getAttributes().hasAttribute(K: Kind))
7344 return true;
7345
7346 // Walk the declarator structure, checking decl attributes that were in a type
7347 // position to the decl itself.
7348 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7349 if (PD.getTypeObject(i: I).getAttrs().hasAttribute(K: Kind))
7350 return true;
7351 }
7352
7353 // Finally, check attributes on the decl itself.
7354 return PD.getAttributes().hasAttribute(K: Kind) ||
7355 PD.getDeclarationAttributes().hasAttribute(K: Kind);
7356}
7357
7358bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7359 if (!DC->isFunctionOrMethod())
7360 return false;
7361
7362 // If this is a local extern function or variable declared within a function
7363 // template, don't add it into the enclosing namespace scope until it is
7364 // instantiated; it might have a dependent type right now.
7365 if (DC->isDependentContext())
7366 return true;
7367
7368 // C++11 [basic.link]p7:
7369 // When a block scope declaration of an entity with linkage is not found to
7370 // refer to some other declaration, then that entity is a member of the
7371 // innermost enclosing namespace.
7372 //
7373 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7374 // semantically-enclosing namespace, not a lexically-enclosing one.
7375 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(Val: DC))
7376 DC = DC->getParent();
7377 return true;
7378}
7379
7380/// Returns true if given declaration has external C language linkage.
7381static bool isDeclExternC(const Decl *D) {
7382 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
7383 return FD->isExternC();
7384 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
7385 return VD->isExternC();
7386
7387 llvm_unreachable("Unknown type of decl!");
7388}
7389
7390/// Returns true if there hasn't been any invalid type diagnosed.
7391static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7392 DeclContext *DC = NewVD->getDeclContext();
7393 QualType R = NewVD->getType();
7394
7395 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7396 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7397 // argument.
7398 if (R->isImageType() || R->isPipeType()) {
7399 Se.Diag(Loc: NewVD->getLocation(),
7400 DiagID: diag::err_opencl_type_can_only_be_used_as_function_parameter)
7401 << R;
7402 NewVD->setInvalidDecl();
7403 return false;
7404 }
7405
7406 // OpenCL v1.2 s6.9.r:
7407 // The event type cannot be used to declare a program scope variable.
7408 // OpenCL v2.0 s6.9.q:
7409 // The clk_event_t and reserve_id_t types cannot be declared in program
7410 // scope.
7411 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7412 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7413 Se.Diag(Loc: NewVD->getLocation(),
7414 DiagID: diag::err_invalid_type_for_program_scope_var)
7415 << R;
7416 NewVD->setInvalidDecl();
7417 return false;
7418 }
7419 }
7420
7421 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7422 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
7423 LO: Se.getLangOpts())) {
7424 QualType NR = R.getCanonicalType();
7425 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7426 NR->isReferenceType()) {
7427 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7428 NR->isFunctionReferenceType()) {
7429 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_pointer)
7430 << NR->isReferenceType();
7431 NewVD->setInvalidDecl();
7432 return false;
7433 }
7434 NR = NR->getPointeeType();
7435 }
7436 }
7437
7438 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
7439 LO: Se.getLangOpts())) {
7440 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7441 // half array type (unless the cl_khr_fp16 extension is enabled).
7442 if (Se.Context.getBaseElementType(QT: R)->isHalfType()) {
7443 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_half_declaration) << R;
7444 NewVD->setInvalidDecl();
7445 return false;
7446 }
7447 }
7448
7449 // OpenCL v1.2 s6.9.r:
7450 // The event type cannot be used with the __local, __constant and __global
7451 // address space qualifiers.
7452 if (R->isEventT()) {
7453 if (R.getAddressSpace() != LangAS::opencl_private) {
7454 Se.Diag(Loc: NewVD->getBeginLoc(), DiagID: diag::err_event_t_addr_space_qual);
7455 NewVD->setInvalidDecl();
7456 return false;
7457 }
7458 }
7459
7460 if (R->isSamplerT()) {
7461 // OpenCL v1.2 s6.9.b p4:
7462 // The sampler type cannot be used with the __local and __global address
7463 // space qualifiers.
7464 if (R.getAddressSpace() == LangAS::opencl_local ||
7465 R.getAddressSpace() == LangAS::opencl_global) {
7466 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wrong_sampler_addressspace);
7467 NewVD->setInvalidDecl();
7468 }
7469
7470 // OpenCL v1.2 s6.12.14.1:
7471 // A global sampler must be declared with either the constant address
7472 // space qualifier or with the const qualifier.
7473 if (DC->isTranslationUnit() &&
7474 !(R.getAddressSpace() == LangAS::opencl_constant ||
7475 R.isConstQualified())) {
7476 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_nonconst_global_sampler);
7477 NewVD->setInvalidDecl();
7478 }
7479 if (NewVD->isInvalidDecl())
7480 return false;
7481 }
7482
7483 return true;
7484}
7485
7486template <typename AttrTy>
7487static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7488 const TypedefNameDecl *TND = TT->getDecl();
7489 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7490 AttrTy *Clone = Attribute->clone(S.Context);
7491 Clone->setInherited(true);
7492 D->addAttr(A: Clone);
7493 }
7494}
7495
7496// This function emits warning and a corresponding note based on the
7497// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7498// declarations of an annotated type must be const qualified.
7499static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7500 QualType VarType = VD->getType().getCanonicalType();
7501
7502 // Ignore local declarations (for now) and those with const qualification.
7503 // TODO: Local variables should not be allowed if their type declaration has
7504 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7505 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7506 return;
7507
7508 if (VarType->isArrayType()) {
7509 // Retrieve element type for array declarations.
7510 VarType = S.getASTContext().getBaseElementType(QT: VarType);
7511 }
7512
7513 const RecordDecl *RD = VarType->getAsRecordDecl();
7514
7515 // Check if the record declaration is present and if it has any attributes.
7516 if (RD == nullptr)
7517 return;
7518
7519 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7520 S.Diag(Loc: VD->getLocation(), DiagID: diag::warn_var_decl_not_read_only) << RD;
7521 S.Diag(Loc: ConstDecl->getLocation(), DiagID: diag::note_enforce_read_only_placement);
7522 return;
7523 }
7524}
7525
7526// Checks if VD is declared at global scope or with C language linkage.
7527static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7528 return Name.getAsIdentifierInfo() &&
7529 Name.getAsIdentifierInfo()->isStr(Str: "main") &&
7530 !VD->getDescribedVarTemplate() &&
7531 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7532 VD->isExternC());
7533}
7534
7535NamedDecl *Sema::ActOnVariableDeclarator(
7536 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7537 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7538 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7539 QualType R = TInfo->getType();
7540 DeclarationName Name = GetNameForDeclarator(D).getName();
7541
7542 IdentifierInfo *II = Name.getAsIdentifierInfo();
7543 bool IsPlaceholderVariable = false;
7544
7545 if (D.isDecompositionDeclarator()) {
7546 // Take the name of the first declarator as our name for diagnostic
7547 // purposes.
7548 auto &Decomp = D.getDecompositionDeclarator();
7549 if (!Decomp.bindings().empty()) {
7550 II = Decomp.bindings()[0].Name;
7551 Name = II;
7552 }
7553 } else if (!II) {
7554 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_variable_name) << Name;
7555 return nullptr;
7556 }
7557
7558
7559 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7560 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS: D.getDeclSpec());
7561 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7562 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7563
7564 IsPlaceholderVariable = true;
7565
7566 if (!Previous.empty()) {
7567 NamedDecl *PrevDecl = *Previous.begin();
7568 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7569 DC: DC->getRedeclContext());
7570 if (SameDC && isDeclInScope(D: PrevDecl, Ctx: CurContext, S, AllowInlineNamespace: false)) {
7571 IsPlaceholderVariable = !isa<ParmVarDecl>(Val: PrevDecl);
7572 if (IsPlaceholderVariable)
7573 DiagPlaceholderVariableDefinition(Loc: D.getIdentifierLoc());
7574 }
7575 }
7576 }
7577
7578 // dllimport globals without explicit storage class are treated as extern. We
7579 // have to change the storage class this early to get the right DeclContext.
7580 if (SC == SC_None && !DC->isRecord() &&
7581 hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLImport) &&
7582 !hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLExport))
7583 SC = SC_Extern;
7584
7585 DeclContext *OriginalDC = DC;
7586 bool IsLocalExternDecl = SC == SC_Extern &&
7587 adjustContextForLocalExternDecl(DC);
7588
7589 if (SCSpec == DeclSpec::SCS_mutable) {
7590 // mutable can only appear on non-static class members, so it's always
7591 // an error here
7592 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_mutable_nonmember);
7593 D.setInvalidType();
7594 SC = SC_None;
7595 }
7596
7597 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7598 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7599 loc: D.getDeclSpec().getStorageClassSpecLoc())) {
7600 // In C++11, the 'register' storage class specifier is deprecated.
7601 // Suppress the warning in system macros, it's used in macros in some
7602 // popular C system headers, such as in glibc's htonl() macro.
7603 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7604 DiagID: getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7605 : diag::warn_deprecated_register)
7606 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7607 }
7608
7609 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
7610
7611 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7612 // C99 6.9p2: The storage-class specifiers auto and register shall not
7613 // appear in the declaration specifiers in an external declaration.
7614 // Global Register+Asm is a GNU extension we support.
7615 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7616 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_typecheck_sclass_fscope);
7617 D.setInvalidType();
7618 }
7619 }
7620
7621 // If this variable has a VLA type and an initializer, try to
7622 // fold to a constant-sized type. This is otherwise invalid.
7623 if (D.hasInitializer() && R->isVariableArrayType())
7624 tryToFixVariablyModifiedVarType(TInfo, T&: R, Loc: D.getIdentifierLoc(),
7625 /*DiagID=*/FailedFoldDiagID: 0);
7626
7627 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7628 const AutoType *AT = TL.getTypePtr();
7629 CheckConstrainedAuto(AutoT: AT, Loc: TL.getConceptNameLoc());
7630 }
7631
7632 bool IsMemberSpecialization = false;
7633 bool IsVariableTemplateSpecialization = false;
7634 bool IsPartialSpecialization = false;
7635 bool IsVariableTemplate = false;
7636 VarDecl *NewVD = nullptr;
7637 VarTemplateDecl *NewTemplate = nullptr;
7638 TemplateParameterList *TemplateParams = nullptr;
7639 if (!getLangOpts().CPlusPlus) {
7640 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
7641 Id: II, T: R, TInfo, S: SC);
7642
7643 if (R->getContainedDeducedType())
7644 ParsingInitForAutoVars.insert(Ptr: NewVD);
7645
7646 if (D.isInvalidType())
7647 NewVD->setInvalidDecl();
7648
7649 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7650 NewVD->hasLocalStorage())
7651 checkNonTrivialCUnion(QT: NewVD->getType(), Loc: NewVD->getLocation(),
7652 UseContext: NonTrivialCUnionContext::AutoVar, NonTrivialKind: NTCUK_Destruct);
7653 } else {
7654 bool Invalid = false;
7655 // Match up the template parameter lists with the scope specifier, then
7656 // determine whether we have a template or a template specialization.
7657 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7658 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
7659 SS: D.getCXXScopeSpec(),
7660 TemplateId: D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7661 ? D.getName().TemplateId
7662 : nullptr,
7663 ParamLists: TemplateParamLists,
7664 /*never a friend*/ IsFriend: false, IsMemberSpecialization, Invalid);
7665
7666 if (TemplateParams) {
7667 if (DC->isDependentContext()) {
7668 ContextRAII SavedContext(*this, DC);
7669 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
7670 Invalid = true;
7671 }
7672
7673 if (!TemplateParams->size() &&
7674 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7675 // There is an extraneous 'template<>' for this variable. Complain
7676 // about it, but allow the declaration of the variable.
7677 Diag(Loc: TemplateParams->getTemplateLoc(),
7678 DiagID: diag::err_template_variable_noparams)
7679 << II
7680 << SourceRange(TemplateParams->getTemplateLoc(),
7681 TemplateParams->getRAngleLoc());
7682 TemplateParams = nullptr;
7683 } else {
7684 // Check that we can declare a template here.
7685 if (CheckTemplateDeclScope(S, TemplateParams))
7686 return nullptr;
7687
7688 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7689 // This is an explicit specialization or a partial specialization.
7690 IsVariableTemplateSpecialization = true;
7691 IsPartialSpecialization = TemplateParams->size() > 0;
7692 } else { // if (TemplateParams->size() > 0)
7693 // This is a template declaration.
7694 IsVariableTemplate = true;
7695
7696 // Only C++1y supports variable templates (N3651).
7697 DiagCompat(Loc: D.getIdentifierLoc(), CompatDiagId: diag_compat::variable_template);
7698 }
7699 }
7700 } else {
7701 // Check that we can declare a member specialization here.
7702 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7703 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
7704 return nullptr;
7705 assert((Invalid ||
7706 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7707 "should have a 'template<>' for this decl");
7708 }
7709
7710 bool IsExplicitSpecialization =
7711 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7712
7713 // C++ [temp.expl.spec]p2:
7714 // The declaration in an explicit-specialization shall not be an
7715 // export-declaration. An explicit specialization shall not use a
7716 // storage-class-specifier other than thread_local.
7717 //
7718 // We use the storage-class-specifier from DeclSpec because we may have
7719 // added implicit 'extern' for declarations with __declspec(dllimport)!
7720 if (SCSpec != DeclSpec::SCS_unspecified &&
7721 (IsExplicitSpecialization || IsMemberSpecialization)) {
7722 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7723 DiagID: diag::ext_explicit_specialization_storage_class)
7724 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7725 }
7726
7727 if (CurContext->isRecord()) {
7728 if (SC == SC_Static) {
7729 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
7730 // Walk up the enclosing DeclContexts to check for any that are
7731 // incompatible with static data members.
7732 const DeclContext *FunctionOrMethod = nullptr;
7733 const CXXRecordDecl *AnonStruct = nullptr;
7734 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7735 if (Ctxt->isFunctionOrMethod()) {
7736 FunctionOrMethod = Ctxt;
7737 break;
7738 }
7739 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Val: Ctxt);
7740 if (ParentDecl && !ParentDecl->getDeclName()) {
7741 AnonStruct = ParentDecl;
7742 break;
7743 }
7744 }
7745 if (FunctionOrMethod) {
7746 // C++ [class.static.data]p5: A local class shall not have static
7747 // data members.
7748 Diag(Loc: D.getIdentifierLoc(),
7749 DiagID: diag::err_static_data_member_not_allowed_in_local_class)
7750 << Name << RD->getDeclName() << RD->getTagKind();
7751 } else if (AnonStruct) {
7752 // C++ [class.static.data]p4: Unnamed classes and classes contained
7753 // directly or indirectly within unnamed classes shall not contain
7754 // static data members.
7755 Diag(Loc: D.getIdentifierLoc(),
7756 DiagID: diag::err_static_data_member_not_allowed_in_anon_struct)
7757 << Name << AnonStruct->getTagKind();
7758 Invalid = true;
7759 } else if (RD->isUnion()) {
7760 // C++98 [class.union]p1: If a union contains a static data member,
7761 // the program is ill-formed. C++11 drops this restriction.
7762 DiagCompat(Loc: D.getIdentifierLoc(),
7763 CompatDiagId: diag_compat::static_data_member_in_union)
7764 << Name;
7765 }
7766 }
7767 } else if (IsVariableTemplate || IsPartialSpecialization) {
7768 // There is no such thing as a member field template.
7769 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_member)
7770 << II << TemplateParams->getSourceRange();
7771 // Recover by pretending this is a static data member template.
7772 SC = SC_Static;
7773 }
7774 } else if (DC->isRecord()) {
7775 // This is an out-of-line definition of a static data member.
7776 switch (SC) {
7777 case SC_None:
7778 break;
7779 case SC_Static:
7780 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7781 DiagID: diag::err_static_out_of_line)
7782 << FixItHint::CreateRemoval(
7783 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7784 break;
7785 case SC_Auto:
7786 case SC_Register:
7787 case SC_Extern:
7788 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7789 // to names of variables declared in a block or to function parameters.
7790 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7791 // of class members
7792
7793 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7794 DiagID: diag::err_storage_class_for_static_member)
7795 << FixItHint::CreateRemoval(
7796 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7797 break;
7798 case SC_PrivateExtern:
7799 llvm_unreachable("C storage class in c++!");
7800 }
7801 }
7802
7803 if (IsVariableTemplateSpecialization) {
7804 SourceLocation TemplateKWLoc =
7805 TemplateParamLists.size() > 0
7806 ? TemplateParamLists[0]->getTemplateLoc()
7807 : SourceLocation();
7808 DeclResult Res = ActOnVarTemplateSpecialization(
7809 S, D, DI: TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7810 IsPartialSpecialization);
7811 if (Res.isInvalid())
7812 return nullptr;
7813 NewVD = cast<VarDecl>(Val: Res.get());
7814 AddToScope = false;
7815 } else if (D.isDecompositionDeclarator()) {
7816 NewVD = DecompositionDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
7817 LSquareLoc: D.getIdentifierLoc(), T: R, TInfo, S: SC,
7818 Bindings);
7819 } else
7820 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
7821 IdLoc: D.getIdentifierLoc(), Id: II, T: R, TInfo, S: SC);
7822
7823 // If this is supposed to be a variable template, create it as such.
7824 if (IsVariableTemplate) {
7825 NewTemplate =
7826 VarTemplateDecl::Create(C&: Context, DC, L: D.getIdentifierLoc(), Name,
7827 Params: TemplateParams, Decl: NewVD);
7828 NewVD->setDescribedVarTemplate(NewTemplate);
7829 }
7830
7831 // If this decl has an auto type in need of deduction, make a note of the
7832 // Decl so we can diagnose uses of it in its own initializer.
7833 if (R->getContainedDeducedType())
7834 ParsingInitForAutoVars.insert(Ptr: NewVD);
7835
7836 if (D.isInvalidType() || Invalid) {
7837 NewVD->setInvalidDecl();
7838 if (NewTemplate)
7839 NewTemplate->setInvalidDecl();
7840 }
7841
7842 SetNestedNameSpecifier(S&: *this, DD: NewVD, D);
7843
7844 // If we have any template parameter lists that don't directly belong to
7845 // the variable (matching the scope specifier), store them.
7846 // An explicit variable template specialization does not own any template
7847 // parameter lists.
7848 unsigned VDTemplateParamLists =
7849 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7850 if (TemplateParamLists.size() > VDTemplateParamLists)
7851 NewVD->setTemplateParameterListsInfo(
7852 Context, TPLists: TemplateParamLists.drop_back(N: VDTemplateParamLists));
7853 }
7854
7855 if (D.getDeclSpec().isInlineSpecified()) {
7856 if (!getLangOpts().CPlusPlus) {
7857 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
7858 << 0;
7859 } else if (CurContext->isFunctionOrMethod()) {
7860 // 'inline' is not allowed on block scope variable declaration.
7861 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
7862 DiagID: diag::err_inline_declaration_block_scope) << Name
7863 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
7864 } else {
7865 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
7866 DiagID: getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
7867 : diag::compat_pre_cxx17_inline_variable);
7868 NewVD->setInlineSpecified();
7869 }
7870 }
7871
7872 // Set the lexical context. If the declarator has a C++ scope specifier, the
7873 // lexical context will be different from the semantic context.
7874 NewVD->setLexicalDeclContext(CurContext);
7875 if (NewTemplate)
7876 NewTemplate->setLexicalDeclContext(CurContext);
7877
7878 if (IsLocalExternDecl) {
7879 if (D.isDecompositionDeclarator())
7880 for (auto *B : Bindings)
7881 B->setLocalExternDecl();
7882 else
7883 NewVD->setLocalExternDecl();
7884 }
7885
7886 bool EmitTLSUnsupportedError = false;
7887 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7888 // C++11 [dcl.stc]p4:
7889 // When thread_local is applied to a variable of block scope the
7890 // storage-class-specifier static is implied if it does not appear
7891 // explicitly.
7892 // Core issue: 'static' is not implied if the variable is declared
7893 // 'extern'.
7894 if (NewVD->hasLocalStorage() &&
7895 (SCSpec != DeclSpec::SCS_unspecified ||
7896 TSCS != DeclSpec::TSCS_thread_local ||
7897 !DC->isFunctionOrMethod()))
7898 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
7899 DiagID: diag::err_thread_non_global)
7900 << DeclSpec::getSpecifierName(S: TSCS);
7901 else if (!Context.getTargetInfo().isTLSSupported()) {
7902 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
7903 // Postpone error emission until we've collected attributes required to
7904 // figure out whether it's a host or device variable and whether the
7905 // error should be ignored.
7906 EmitTLSUnsupportedError = true;
7907 // We still need to mark the variable as TLS so it shows up in AST with
7908 // proper storage class for other tools to use even if we're not going
7909 // to emit any code for it.
7910 NewVD->setTSCSpec(TSCS);
7911 } else
7912 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
7913 DiagID: diag::err_thread_unsupported);
7914 } else
7915 NewVD->setTSCSpec(TSCS);
7916 }
7917
7918 switch (D.getDeclSpec().getConstexprSpecifier()) {
7919 case ConstexprSpecKind::Unspecified:
7920 break;
7921
7922 case ConstexprSpecKind::Consteval:
7923 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
7924 DiagID: diag::err_constexpr_wrong_decl_kind)
7925 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7926 [[fallthrough]];
7927
7928 case ConstexprSpecKind::Constexpr:
7929 NewVD->setConstexpr(true);
7930 // C++1z [dcl.spec.constexpr]p1:
7931 // A static data member declared with the constexpr specifier is
7932 // implicitly an inline variable.
7933 if (NewVD->isStaticDataMember() &&
7934 (getLangOpts().CPlusPlus17 ||
7935 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7936 NewVD->setImplicitlyInline();
7937 break;
7938
7939 case ConstexprSpecKind::Constinit:
7940 if (!NewVD->hasGlobalStorage())
7941 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
7942 DiagID: diag::err_constinit_local_variable);
7943 else
7944 NewVD->addAttr(
7945 A: ConstInitAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getConstexprSpecLoc(),
7946 S: ConstInitAttr::Keyword_constinit));
7947 break;
7948 }
7949
7950 // C99 6.7.4p3
7951 // An inline definition of a function with external linkage shall
7952 // not contain a definition of a modifiable object with static or
7953 // thread storage duration...
7954 // We only apply this when the function is required to be defined
7955 // elsewhere, i.e. when the function is not 'extern inline'. Note
7956 // that a local variable with thread storage duration still has to
7957 // be marked 'static'. Also note that it's possible to get these
7958 // semantics in C++ using __attribute__((gnu_inline)).
7959 if (SC == SC_Static && S->getFnParent() != nullptr &&
7960 !NewVD->getType().isConstQualified()) {
7961 FunctionDecl *CurFD = getCurFunctionDecl();
7962 if (CurFD && isFunctionDefinitionDiscarded(S&: *this, FD: CurFD)) {
7963 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7964 DiagID: diag::warn_static_local_in_extern_inline);
7965 MaybeSuggestAddingStaticToDecl(D: CurFD);
7966 }
7967 }
7968
7969 if (D.getDeclSpec().isModulePrivateSpecified()) {
7970 if (IsVariableTemplateSpecialization)
7971 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
7972 << (IsPartialSpecialization ? 1 : 0)
7973 << FixItHint::CreateRemoval(
7974 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
7975 else if (IsMemberSpecialization)
7976 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
7977 << 2
7978 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
7979 else if (NewVD->hasLocalStorage())
7980 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_local)
7981 << 0 << NewVD
7982 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7983 << FixItHint::CreateRemoval(
7984 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
7985 else {
7986 NewVD->setModulePrivate();
7987 if (NewTemplate)
7988 NewTemplate->setModulePrivate();
7989 for (auto *B : Bindings)
7990 B->setModulePrivate();
7991 }
7992 }
7993
7994 if (getLangOpts().OpenCL) {
7995 deduceOpenCLAddressSpace(Decl: NewVD);
7996
7997 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7998 if (TSC != TSCS_unspecified) {
7999 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8000 DiagID: diag::err_opencl_unknown_type_specifier)
8001 << getLangOpts().getOpenCLVersionString()
8002 << DeclSpec::getSpecifierName(S: TSC) << 1;
8003 NewVD->setInvalidDecl();
8004 }
8005 }
8006
8007 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8008 // address space if the table has local storage (semantic checks elsewhere
8009 // will produce an error anyway).
8010 if (const auto *ATy = dyn_cast<ArrayType>(Val: NewVD->getType())) {
8011 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8012 !NewVD->hasLocalStorage()) {
8013 QualType Type = Context.getAddrSpaceQualType(
8014 T: NewVD->getType(), AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: 1));
8015 NewVD->setType(Type);
8016 }
8017 }
8018
8019 // Handle attributes prior to checking for duplicates in MergeVarDecl
8020 ProcessDeclAttributes(S, D: NewVD, PD: D);
8021
8022 if (getLangOpts().HLSL)
8023 HLSL().ActOnVariableDeclarator(VD: NewVD);
8024
8025 if (getLangOpts().OpenACC)
8026 OpenACC().ActOnVariableDeclarator(VD: NewVD);
8027
8028 // FIXME: This is probably the wrong location to be doing this and we should
8029 // probably be doing this for more attributes (especially for function
8030 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8031 // the code to copy attributes would be generated by TableGen.
8032 if (R->isFunctionPointerType())
8033 if (const auto *TT = R->getAs<TypedefType>())
8034 copyAttrFromTypedefToDecl<AllocSizeAttr>(S&: *this, D: NewVD, TT);
8035
8036 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8037 if (EmitTLSUnsupportedError &&
8038 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) ||
8039 (getLangOpts().OpenMPIsTargetDevice &&
8040 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD: NewVD))))
8041 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8042 DiagID: diag::err_thread_unsupported);
8043
8044 if (EmitTLSUnsupportedError &&
8045 (LangOpts.SYCLIsDevice ||
8046 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8047 targetDiag(Loc: D.getIdentifierLoc(), DiagID: diag::err_thread_unsupported);
8048 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8049 // storage [duration]."
8050 if (SC == SC_None && S->getFnParent() != nullptr &&
8051 (NewVD->hasAttr<CUDASharedAttr>() ||
8052 NewVD->hasAttr<CUDAConstantAttr>())) {
8053 NewVD->setStorageClass(SC_Static);
8054 }
8055 }
8056
8057 // Ensure that dllimport globals without explicit storage class are treated as
8058 // extern. The storage class is set above using parsed attributes. Now we can
8059 // check the VarDecl itself.
8060 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8061 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8062 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8063
8064 // In auto-retain/release, infer strong retension for variables of
8065 // retainable type.
8066 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewVD))
8067 NewVD->setInvalidDecl();
8068
8069 // Handle GNU asm-label extension (encoded as an attribute).
8070 if (Expr *E = D.getAsmLabel()) {
8071 // The parser guarantees this is a string.
8072 StringLiteral *SE = cast<StringLiteral>(Val: E);
8073 StringRef Label = SE->getString();
8074 if (S->getFnParent() != nullptr) {
8075 switch (SC) {
8076 case SC_None:
8077 case SC_Auto:
8078 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_asm_label_on_auto_decl) << Label;
8079 break;
8080 case SC_Register:
8081 // Local Named register
8082 if (!Context.getTargetInfo().isValidGCCRegisterName(Name: Label) &&
8083 DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: getCurFunctionDecl()))
8084 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
8085 break;
8086 case SC_Static:
8087 case SC_Extern:
8088 case SC_PrivateExtern:
8089 break;
8090 }
8091 } else if (SC == SC_Register) {
8092 // Global Named register
8093 if (DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) {
8094 const auto &TI = Context.getTargetInfo();
8095 bool HasSizeMismatch;
8096
8097 if (!TI.isValidGCCRegisterName(Name: Label))
8098 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
8099 else if (!TI.validateGlobalRegisterVariable(RegName: Label,
8100 RegSize: Context.getTypeSize(T: R),
8101 HasSizeMismatch))
8102 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_invalid_global_var_reg) << Label;
8103 else if (HasSizeMismatch)
8104 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_register_size_mismatch) << Label;
8105 }
8106
8107 if (!R->isIntegralType(Ctx: Context) && !R->isPointerType()) {
8108 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
8109 DiagID: diag::err_asm_unsupported_register_type)
8110 << TInfo->getTypeLoc().getSourceRange();
8111 NewVD->setInvalidDecl(true);
8112 }
8113 }
8114
8115 NewVD->addAttr(A: AsmLabelAttr::Create(Ctx&: Context, Label,
8116 /*IsLiteralLabel=*/true,
8117 Range: SE->getStrTokenLoc(TokNum: 0)));
8118 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8119 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8120 ExtnameUndeclaredIdentifiers.find(Val: NewVD->getIdentifier());
8121 if (I != ExtnameUndeclaredIdentifiers.end()) {
8122 if (isDeclExternC(D: NewVD)) {
8123 NewVD->addAttr(A: I->second);
8124 ExtnameUndeclaredIdentifiers.erase(I);
8125 } else
8126 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
8127 << /*Variable*/1 << NewVD;
8128 }
8129 }
8130
8131 // Find the shadowed declaration before filtering for scope.
8132 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8133 ? getShadowedDeclaration(D: NewVD, R: Previous)
8134 : nullptr;
8135
8136 // Don't consider existing declarations that are in a different
8137 // scope and are out-of-semantic-context declarations (if the new
8138 // declaration has linkage).
8139 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(VD: NewVD),
8140 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
8141 IsMemberSpecialization ||
8142 IsVariableTemplateSpecialization);
8143
8144 // Check whether the previous declaration is in the same block scope. This
8145 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8146 if (getLangOpts().CPlusPlus &&
8147 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8148 NewVD->setPreviousDeclInSameBlockScope(
8149 Previous.isSingleResult() && !Previous.isShadowed() &&
8150 isDeclInScope(D: Previous.getFoundDecl(), Ctx: OriginalDC, S, AllowInlineNamespace: false));
8151
8152 if (!getLangOpts().CPlusPlus) {
8153 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8154 } else {
8155 // If this is an explicit specialization of a static data member, check it.
8156 if (IsMemberSpecialization && !IsVariableTemplate &&
8157 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8158 CheckMemberSpecialization(Member: NewVD, Previous))
8159 NewVD->setInvalidDecl();
8160
8161 // Merge the decl with the existing one if appropriate.
8162 if (!Previous.empty()) {
8163 if (Previous.isSingleResult() &&
8164 isa<FieldDecl>(Val: Previous.getFoundDecl()) &&
8165 D.getCXXScopeSpec().isSet()) {
8166 // The user tried to define a non-static data member
8167 // out-of-line (C++ [dcl.meaning]p1).
8168 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_nonstatic_member_out_of_line)
8169 << D.getCXXScopeSpec().getRange();
8170 Previous.clear();
8171 NewVD->setInvalidDecl();
8172 }
8173 } else if (D.getCXXScopeSpec().isSet() &&
8174 !IsVariableTemplateSpecialization) {
8175 // No previous declaration in the qualifying scope.
8176 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_no_member)
8177 << Name << computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext: true)
8178 << D.getCXXScopeSpec().getRange();
8179 NewVD->setInvalidDecl();
8180 }
8181
8182 if (!IsPlaceholderVariable)
8183 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8184
8185 // CheckVariableDeclaration will set NewVD as invalid if something is in
8186 // error like WebAssembly tables being declared as arrays with a non-zero
8187 // size, but then parsing continues and emits further errors on that line.
8188 // To avoid that we check here if it happened and return nullptr.
8189 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8190 return nullptr;
8191
8192 if (NewTemplate) {
8193 VarTemplateDecl *PrevVarTemplate =
8194 NewVD->getPreviousDecl()
8195 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8196 : nullptr;
8197
8198 // Check the template parameter list of this declaration, possibly
8199 // merging in the template parameter list from the previous variable
8200 // template declaration.
8201 if (CheckTemplateParameterList(
8202 NewParams: TemplateParams,
8203 OldParams: PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8204 : nullptr,
8205 TPC: (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8206 DC->isDependentContext())
8207 ? TPC_ClassTemplateMember
8208 : TPC_Other))
8209 NewVD->setInvalidDecl();
8210
8211 // If we are providing an explicit specialization of a static variable
8212 // template, make a note of that.
8213 if (PrevVarTemplate &&
8214 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8215 PrevVarTemplate->setMemberSpecialization();
8216 }
8217 }
8218
8219 // Diagnose shadowed variables iff this isn't a redeclaration.
8220 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8221 CheckShadow(D: NewVD, ShadowedDecl, R: Previous);
8222
8223 ProcessPragmaWeak(S, D: NewVD);
8224
8225 // If this is the first declaration of an extern C variable, update
8226 // the map of such variables.
8227 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8228 isIncompleteDeclExternC(S&: *this, D: NewVD))
8229 RegisterLocallyScopedExternCDecl(ND: NewVD, S);
8230
8231 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8232 MangleNumberingContext *MCtx;
8233 Decl *ManglingContextDecl;
8234 std::tie(args&: MCtx, args&: ManglingContextDecl) =
8235 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
8236 if (MCtx) {
8237 Context.setManglingNumber(
8238 ND: NewVD, Number: MCtx->getManglingNumber(
8239 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
8240 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
8241 }
8242 }
8243
8244 // Special handling of variable named 'main'.
8245 if (!getLangOpts().Freestanding && isMainVar(Name, VD: NewVD)) {
8246 // C++ [basic.start.main]p3:
8247 // A program that declares
8248 // - a variable main at global scope, or
8249 // - an entity named main with C language linkage (in any namespace)
8250 // is ill-formed
8251 if (getLangOpts().CPlusPlus)
8252 Diag(Loc: D.getBeginLoc(), DiagID: diag::err_main_global_variable)
8253 << NewVD->isExternC();
8254
8255 // In C, and external-linkage variable named main results in undefined
8256 // behavior.
8257 else if (NewVD->hasExternalFormalLinkage())
8258 Diag(Loc: D.getBeginLoc(), DiagID: diag::warn_main_redefined);
8259 }
8260
8261 if (D.isRedeclaration() && !Previous.empty()) {
8262 NamedDecl *Prev = Previous.getRepresentativeDecl();
8263 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewVD, IsSpecialization: IsMemberSpecialization,
8264 IsDefinition: D.isFunctionDefinition());
8265 }
8266
8267 if (NewTemplate) {
8268 if (NewVD->isInvalidDecl())
8269 NewTemplate->setInvalidDecl();
8270 ActOnDocumentableDecl(D: NewTemplate);
8271 return NewTemplate;
8272 }
8273
8274 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8275 CompleteMemberSpecialization(Member: NewVD, Previous);
8276
8277 emitReadOnlyPlacementAttrWarning(S&: *this, VD: NewVD);
8278
8279 return NewVD;
8280}
8281
8282/// Enum describing the %select options in diag::warn_decl_shadow.
8283enum ShadowedDeclKind {
8284 SDK_Local,
8285 SDK_Global,
8286 SDK_StaticMember,
8287 SDK_Field,
8288 SDK_Typedef,
8289 SDK_Using,
8290 SDK_StructuredBinding
8291};
8292
8293/// Determine what kind of declaration we're shadowing.
8294static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8295 const DeclContext *OldDC) {
8296 if (isa<TypeAliasDecl>(Val: ShadowedDecl))
8297 return SDK_Using;
8298 else if (isa<TypedefDecl>(Val: ShadowedDecl))
8299 return SDK_Typedef;
8300 else if (isa<BindingDecl>(Val: ShadowedDecl))
8301 return SDK_StructuredBinding;
8302 else if (isa<RecordDecl>(Val: OldDC))
8303 return isa<FieldDecl>(Val: ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8304
8305 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8306}
8307
8308/// Return the location of the capture if the given lambda captures the given
8309/// variable \p VD, or an invalid source location otherwise.
8310static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8311 const VarDecl *VD) {
8312 for (const Capture &Capture : LSI->Captures) {
8313 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8314 return Capture.getLocation();
8315 }
8316 return SourceLocation();
8317}
8318
8319static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8320 const LookupResult &R) {
8321 // Only diagnose if we're shadowing an unambiguous field or variable.
8322 if (R.getResultKind() != LookupResultKind::Found)
8323 return false;
8324
8325 // Return false if warning is ignored.
8326 return !Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: R.getNameLoc());
8327}
8328
8329NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8330 const LookupResult &R) {
8331 if (!shouldWarnIfShadowedDecl(Diags, R))
8332 return nullptr;
8333
8334 // Don't diagnose declarations at file scope.
8335 if (D->hasGlobalStorage() && !D->isStaticLocal())
8336 return nullptr;
8337
8338 NamedDecl *ShadowedDecl = R.getFoundDecl();
8339 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8340 : nullptr;
8341}
8342
8343NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8344 const LookupResult &R) {
8345 // Don't warn if typedef declaration is part of a class
8346 if (D->getDeclContext()->isRecord())
8347 return nullptr;
8348
8349 if (!shouldWarnIfShadowedDecl(Diags, R))
8350 return nullptr;
8351
8352 NamedDecl *ShadowedDecl = R.getFoundDecl();
8353 return isa<TypedefNameDecl>(Val: ShadowedDecl) ? ShadowedDecl : nullptr;
8354}
8355
8356NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8357 const LookupResult &R) {
8358 if (!shouldWarnIfShadowedDecl(Diags, R))
8359 return nullptr;
8360
8361 NamedDecl *ShadowedDecl = R.getFoundDecl();
8362 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8363 : nullptr;
8364}
8365
8366void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8367 const LookupResult &R) {
8368 DeclContext *NewDC = D->getDeclContext();
8369
8370 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ShadowedDecl)) {
8371 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDC)) {
8372 // Fields are not shadowed by variables in C++ static methods.
8373 if (MD->isStatic())
8374 return;
8375
8376 if (!MD->getParent()->isLambda() && MD->isExplicitObjectMemberFunction())
8377 return;
8378 }
8379 // Fields shadowed by constructor parameters are a special case. Usually
8380 // the constructor initializes the field with the parameter.
8381 if (isa<CXXConstructorDecl>(Val: NewDC))
8382 if (const auto PVD = dyn_cast<ParmVarDecl>(Val: D)) {
8383 // Remember that this was shadowed so we can either warn about its
8384 // modification or its existence depending on warning settings.
8385 ShadowingDecls.insert(KV: {PVD->getCanonicalDecl(), FD});
8386 return;
8387 }
8388 }
8389
8390 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(Val: ShadowedDecl))
8391 if (shadowedVar->isExternC()) {
8392 // For shadowing external vars, make sure that we point to the global
8393 // declaration, not a locally scoped extern declaration.
8394 for (auto *I : shadowedVar->redecls())
8395 if (I->isFileVarDecl()) {
8396 ShadowedDecl = I;
8397 break;
8398 }
8399 }
8400
8401 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8402
8403 unsigned WarningDiag = diag::warn_decl_shadow;
8404 SourceLocation CaptureLoc;
8405 if (isa<VarDecl>(Val: D) && NewDC && isa<CXXMethodDecl>(Val: NewDC)) {
8406 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: NewDC->getParent())) {
8407 if (RD->isLambda() && OldDC->Encloses(DC: NewDC->getLexicalParent())) {
8408 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl)) {
8409 const auto *LSI = cast<LambdaScopeInfo>(Val: getCurFunction());
8410 if (RD->getLambdaCaptureDefault() == LCD_None) {
8411 // Try to avoid warnings for lambdas with an explicit capture
8412 // list. Warn only when the lambda captures the shadowed decl
8413 // explicitly.
8414 CaptureLoc = getCaptureLocation(LSI, VD);
8415 if (CaptureLoc.isInvalid())
8416 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8417 } else {
8418 // Remember that this was shadowed so we can avoid the warning if
8419 // the shadowed decl isn't captured and the warning settings allow
8420 // it.
8421 cast<LambdaScopeInfo>(Val: getCurFunction())
8422 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: VD});
8423 return;
8424 }
8425 }
8426 if (isa<FieldDecl>(Val: ShadowedDecl)) {
8427 // If lambda can capture this, then emit default shadowing warning,
8428 // Otherwise it is not really a shadowing case since field is not
8429 // available in lambda's body.
8430 // At this point we don't know that lambda can capture this, so
8431 // remember that this was shadowed and delay until we know.
8432 cast<LambdaScopeInfo>(Val: getCurFunction())
8433 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: ShadowedDecl});
8434 return;
8435 }
8436 }
8437 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl);
8438 VD && VD->hasLocalStorage()) {
8439 // A variable can't shadow a local variable in an enclosing scope, if
8440 // they are separated by a non-capturing declaration context.
8441 for (DeclContext *ParentDC = NewDC;
8442 ParentDC && !ParentDC->Equals(DC: OldDC);
8443 ParentDC = getLambdaAwareParentOfDeclContext(DC: ParentDC)) {
8444 // Only block literals, captured statements, and lambda expressions
8445 // can capture; other scopes don't.
8446 if (!isa<BlockDecl>(Val: ParentDC) && !isa<CapturedDecl>(Val: ParentDC) &&
8447 !isLambdaCallOperator(DC: ParentDC)) {
8448 return;
8449 }
8450 }
8451 }
8452 }
8453 }
8454
8455 // Never warn about shadowing a placeholder variable.
8456 if (ShadowedDecl->isPlaceholderVar(LangOpts: getLangOpts()))
8457 return;
8458
8459 // Only warn about certain kinds of shadowing for class members.
8460 if (NewDC) {
8461 // In particular, don't warn about shadowing non-class members.
8462 if (NewDC->isRecord() && !OldDC->isRecord())
8463 return;
8464
8465 // Skip shadowing check if we're in a class scope, dealing with an enum
8466 // constant in a different context.
8467 DeclContext *ReDC = NewDC->getRedeclContext();
8468 if (ReDC->isRecord() && isa<EnumConstantDecl>(Val: D) && !OldDC->Equals(DC: ReDC))
8469 return;
8470
8471 // TODO: should we warn about static data members shadowing
8472 // static data members from base classes?
8473
8474 // TODO: don't diagnose for inaccessible shadowed members.
8475 // This is hard to do perfectly because we might friend the
8476 // shadowing context, but that's just a false negative.
8477 }
8478
8479 DeclarationName Name = R.getLookupName();
8480
8481 // Emit warning and note.
8482 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8483 Diag(Loc: R.getNameLoc(), DiagID: WarningDiag) << Name << Kind << OldDC;
8484 if (!CaptureLoc.isInvalid())
8485 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8486 << Name << /*explicitly*/ 1;
8487 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8488}
8489
8490void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8491 for (const auto &Shadow : LSI->ShadowingDecls) {
8492 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8493 // Try to avoid the warning when the shadowed decl isn't captured.
8494 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8495 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl)) {
8496 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8497 Diag(Loc: Shadow.VD->getLocation(),
8498 DiagID: CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8499 : diag::warn_decl_shadow)
8500 << Shadow.VD->getDeclName()
8501 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8502 if (CaptureLoc.isValid())
8503 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8504 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8505 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8506 } else if (isa<FieldDecl>(Val: ShadowedDecl)) {
8507 Diag(Loc: Shadow.VD->getLocation(),
8508 DiagID: LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8509 : diag::warn_decl_shadow_uncaptured_local)
8510 << Shadow.VD->getDeclName()
8511 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8512 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8513 }
8514 }
8515}
8516
8517void Sema::CheckShadow(Scope *S, VarDecl *D) {
8518 if (Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: D->getLocation()))
8519 return;
8520
8521 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8522 Sema::LookupOrdinaryName,
8523 RedeclarationKind::ForVisibleRedeclaration);
8524 LookupName(R, S);
8525 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8526 CheckShadow(D, ShadowedDecl, R);
8527}
8528
8529/// Check if 'E', which is an expression that is about to be modified, refers
8530/// to a constructor parameter that shadows a field.
8531void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8532 // Quickly ignore expressions that can't be shadowing ctor parameters.
8533 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8534 return;
8535 E = E->IgnoreParenImpCasts();
8536 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
8537 if (!DRE)
8538 return;
8539 const NamedDecl *D = cast<NamedDecl>(Val: DRE->getDecl()->getCanonicalDecl());
8540 auto I = ShadowingDecls.find(Val: D);
8541 if (I == ShadowingDecls.end())
8542 return;
8543 const NamedDecl *ShadowedDecl = I->second;
8544 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8545 Diag(Loc, DiagID: diag::warn_modifying_shadowing_decl) << D << OldDC;
8546 Diag(Loc: D->getLocation(), DiagID: diag::note_var_declared_here) << D;
8547 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8548
8549 // Avoid issuing multiple warnings about the same decl.
8550 ShadowingDecls.erase(I);
8551}
8552
8553/// Check for conflict between this global or extern "C" declaration and
8554/// previous global or extern "C" declarations. This is only used in C++.
8555template<typename T>
8556static bool checkGlobalOrExternCConflict(
8557 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8558 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8559 NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName());
8560
8561 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8562 // The common case: this global doesn't conflict with any extern "C"
8563 // declaration.
8564 return false;
8565 }
8566
8567 if (Prev) {
8568 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8569 // Both the old and new declarations have C language linkage. This is a
8570 // redeclaration.
8571 Previous.clear();
8572 Previous.addDecl(D: Prev);
8573 return true;
8574 }
8575
8576 // This is a global, non-extern "C" declaration, and there is a previous
8577 // non-global extern "C" declaration. Diagnose if this is a variable
8578 // declaration.
8579 if (!isa<VarDecl>(ND))
8580 return false;
8581 } else {
8582 // The declaration is extern "C". Check for any declaration in the
8583 // translation unit which might conflict.
8584 if (IsGlobal) {
8585 // We have already performed the lookup into the translation unit.
8586 IsGlobal = false;
8587 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8588 I != E; ++I) {
8589 if (isa<VarDecl>(Val: *I)) {
8590 Prev = *I;
8591 break;
8592 }
8593 }
8594 } else {
8595 DeclContext::lookup_result R =
8596 S.Context.getTranslationUnitDecl()->lookup(Name: ND->getDeclName());
8597 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8598 I != E; ++I) {
8599 if (isa<VarDecl>(Val: *I)) {
8600 Prev = *I;
8601 break;
8602 }
8603 // FIXME: If we have any other entity with this name in global scope,
8604 // the declaration is ill-formed, but that is a defect: it breaks the
8605 // 'stat' hack, for instance. Only variables can have mangled name
8606 // clashes with extern "C" declarations, so only they deserve a
8607 // diagnostic.
8608 }
8609 }
8610
8611 if (!Prev)
8612 return false;
8613 }
8614
8615 // Use the first declaration's location to ensure we point at something which
8616 // is lexically inside an extern "C" linkage-spec.
8617 assert(Prev && "should have found a previous declaration to diagnose");
8618 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: Prev))
8619 Prev = FD->getFirstDecl();
8620 else
8621 Prev = cast<VarDecl>(Val: Prev)->getFirstDecl();
8622
8623 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8624 << IsGlobal << ND;
8625 S.Diag(Loc: Prev->getLocation(), DiagID: diag::note_extern_c_global_conflict)
8626 << IsGlobal;
8627 return false;
8628}
8629
8630/// Apply special rules for handling extern "C" declarations. Returns \c true
8631/// if we have found that this is a redeclaration of some prior entity.
8632///
8633/// Per C++ [dcl.link]p6:
8634/// Two declarations [for a function or variable] with C language linkage
8635/// with the same name that appear in different scopes refer to the same
8636/// [entity]. An entity with C language linkage shall not be declared with
8637/// the same name as an entity in global scope.
8638template<typename T>
8639static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8640 LookupResult &Previous) {
8641 if (!S.getLangOpts().CPlusPlus) {
8642 // In C, when declaring a global variable, look for a corresponding 'extern'
8643 // variable declared in function scope. We don't need this in C++, because
8644 // we find local extern decls in the surrounding file-scope DeclContext.
8645 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8646 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName())) {
8647 Previous.clear();
8648 Previous.addDecl(D: Prev);
8649 return true;
8650 }
8651 }
8652 return false;
8653 }
8654
8655 // A declaration in the translation unit can conflict with an extern "C"
8656 // declaration.
8657 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8658 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8659
8660 // An extern "C" declaration can conflict with a declaration in the
8661 // translation unit or can be a redeclaration of an extern "C" declaration
8662 // in another scope.
8663 if (isIncompleteDeclExternC(S,ND))
8664 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8665
8666 // Neither global nor extern "C": nothing to do.
8667 return false;
8668}
8669
8670static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8671 QualType T) {
8672 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8673 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8674 // any of its members, even recursively, shall not have an atomic type, or a
8675 // variably modified type, or a type that is volatile or restrict qualified.
8676 if (CanonT->isVariablyModifiedType()) {
8677 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8678 return true;
8679 }
8680
8681 // Arrays are qualified by their element type, so get the base type (this
8682 // works on non-arrays as well).
8683 CanonT = SemaRef.Context.getBaseElementType(QT: CanonT);
8684
8685 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8686 CanonT.isRestrictQualified()) {
8687 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8688 return true;
8689 }
8690
8691 if (CanonT->isRecordType()) {
8692 const RecordDecl *RD = CanonT->getAsRecordDecl();
8693 if (!RD->isInvalidDecl() &&
8694 llvm::any_of(Range: RD->fields(), P: [&SemaRef, VarLoc](const FieldDecl *F) {
8695 return CheckC23ConstexprVarType(SemaRef, VarLoc, T: F->getType());
8696 }))
8697 return true;
8698 }
8699
8700 return false;
8701}
8702
8703void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8704 // If the decl is already known invalid, don't check it.
8705 if (NewVD->isInvalidDecl())
8706 return;
8707
8708 QualType T = NewVD->getType();
8709
8710 // Defer checking an 'auto' type until its initializer is attached.
8711 if (T->isUndeducedType())
8712 return;
8713
8714 if (NewVD->hasAttrs())
8715 CheckAlignasUnderalignment(D: NewVD);
8716
8717 if (T->isObjCObjectType()) {
8718 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_statically_allocated_object)
8719 << FixItHint::CreateInsertion(InsertionLoc: NewVD->getLocation(), Code: "*");
8720 T = Context.getObjCObjectPointerType(OIT: T);
8721 NewVD->setType(T);
8722 }
8723
8724 // Emit an error if an address space was applied to decl with local storage.
8725 // This includes arrays of objects with address space qualifiers, but not
8726 // automatic variables that point to other address spaces.
8727 // ISO/IEC TR 18037 S5.1.2
8728 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8729 T.getAddressSpace() != LangAS::Default) {
8730 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 0;
8731 NewVD->setInvalidDecl();
8732 return;
8733 }
8734
8735 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8736 // scope.
8737 if (getLangOpts().OpenCLVersion == 120 &&
8738 !getOpenCLOptions().isAvailableOption(Ext: "cl_clang_storage_class_specifiers",
8739 LO: getLangOpts()) &&
8740 NewVD->isStaticLocal()) {
8741 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_static_function_scope);
8742 NewVD->setInvalidDecl();
8743 return;
8744 }
8745
8746 if (getLangOpts().OpenCL) {
8747 if (!diagnoseOpenCLTypes(Se&: *this, NewVD))
8748 return;
8749
8750 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8751 if (NewVD->hasAttr<BlocksAttr>()) {
8752 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_block_storage_type);
8753 return;
8754 }
8755
8756 if (T->isBlockPointerType()) {
8757 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8758 // can't use 'extern' storage class.
8759 if (!T.isConstQualified()) {
8760 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
8761 << 0 /*const*/;
8762 NewVD->setInvalidDecl();
8763 return;
8764 }
8765 if (NewVD->hasExternalStorage()) {
8766 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_extern_block_declaration);
8767 NewVD->setInvalidDecl();
8768 return;
8769 }
8770 }
8771
8772 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8773 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8774 NewVD->hasExternalStorage()) {
8775 if (!T->isSamplerT() && !T->isDependentType() &&
8776 !(T.getAddressSpace() == LangAS::opencl_constant ||
8777 (T.getAddressSpace() == LangAS::opencl_global &&
8778 getOpenCLOptions().areProgramScopeVariablesSupported(
8779 Opts: getLangOpts())))) {
8780 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8781 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()))
8782 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
8783 << Scope << "global or constant";
8784 else
8785 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
8786 << Scope << "constant";
8787 NewVD->setInvalidDecl();
8788 return;
8789 }
8790 } else {
8791 if (T.getAddressSpace() == LangAS::opencl_global) {
8792 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
8793 << 1 /*is any function*/ << "global";
8794 NewVD->setInvalidDecl();
8795 return;
8796 }
8797 if (T.getAddressSpace() == LangAS::opencl_constant ||
8798 T.getAddressSpace() == LangAS::opencl_local) {
8799 FunctionDecl *FD = getCurFunctionDecl();
8800 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8801 // in functions.
8802 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
8803 if (T.getAddressSpace() == LangAS::opencl_constant)
8804 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
8805 << 0 /*non-kernel only*/ << "constant";
8806 else
8807 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
8808 << 0 /*non-kernel only*/ << "local";
8809 NewVD->setInvalidDecl();
8810 return;
8811 }
8812 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8813 // in the outermost scope of a kernel function.
8814 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
8815 if (!getCurScope()->isFunctionScope()) {
8816 if (T.getAddressSpace() == LangAS::opencl_constant)
8817 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
8818 << "constant";
8819 else
8820 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
8821 << "local";
8822 NewVD->setInvalidDecl();
8823 return;
8824 }
8825 }
8826 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8827 // If we are parsing a template we didn't deduce an addr
8828 // space yet.
8829 T.getAddressSpace() != LangAS::Default) {
8830 // Do not allow other address spaces on automatic variable.
8831 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 1;
8832 NewVD->setInvalidDecl();
8833 return;
8834 }
8835 }
8836 }
8837
8838 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8839 && !NewVD->hasAttr<BlocksAttr>()) {
8840 if (getLangOpts().getGC() != LangOptions::NonGC)
8841 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_gc_attribute_weak_on_local);
8842 else {
8843 assert(!getLangOpts().ObjCAutoRefCount);
8844 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_attribute_weak_on_local);
8845 }
8846 }
8847
8848 // WebAssembly tables must be static with a zero length and can't be
8849 // declared within functions.
8850 if (T->isWebAssemblyTableType()) {
8851 if (getCurScope()->getParent()) { // Parent is null at top-level
8852 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_in_function);
8853 NewVD->setInvalidDecl();
8854 return;
8855 }
8856 if (NewVD->getStorageClass() != SC_Static) {
8857 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_must_be_static);
8858 NewVD->setInvalidDecl();
8859 return;
8860 }
8861 const auto *ATy = dyn_cast<ConstantArrayType>(Val: T.getTypePtr());
8862 if (!ATy || ATy->getZExtSize() != 0) {
8863 Diag(Loc: NewVD->getLocation(),
8864 DiagID: diag::err_typecheck_wasm_table_must_have_zero_length);
8865 NewVD->setInvalidDecl();
8866 return;
8867 }
8868 }
8869
8870 // zero sized static arrays are not allowed in HIP device functions
8871 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
8872 if (FunctionDecl *FD = getCurFunctionDecl();
8873 FD &&
8874 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
8875 if (const ConstantArrayType *ArrayT =
8876 getASTContext().getAsConstantArrayType(T);
8877 ArrayT && ArrayT->isZeroSize()) {
8878 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_zero_array_size) << 2;
8879 }
8880 }
8881 }
8882
8883 bool isVM = T->isVariablyModifiedType();
8884 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8885 NewVD->hasAttr<BlocksAttr>())
8886 setFunctionHasBranchProtectedScope();
8887
8888 if ((isVM && NewVD->hasLinkage()) ||
8889 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8890 bool SizeIsNegative;
8891 llvm::APSInt Oversized;
8892 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8893 TInfo: NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8894 QualType FixedT;
8895 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8896 FixedT = FixedTInfo->getType();
8897 else if (FixedTInfo) {
8898 // Type and type-as-written are canonically different. We need to fix up
8899 // both types separately.
8900 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8901 Oversized);
8902 }
8903 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8904 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8905 // FIXME: This won't give the correct result for
8906 // int a[10][n];
8907 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8908
8909 if (NewVD->isFileVarDecl())
8910 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope)
8911 << SizeRange;
8912 else if (NewVD->isStaticLocal())
8913 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_static_storage)
8914 << SizeRange;
8915 else
8916 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_extern_linkage)
8917 << SizeRange;
8918 NewVD->setInvalidDecl();
8919 return;
8920 }
8921
8922 if (!FixedTInfo) {
8923 if (NewVD->isFileVarDecl())
8924 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
8925 else
8926 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_has_extern_linkage);
8927 NewVD->setInvalidDecl();
8928 return;
8929 }
8930
8931 Diag(Loc: NewVD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
8932 NewVD->setType(FixedT);
8933 NewVD->setTypeSourceInfo(FixedTInfo);
8934 }
8935
8936 if (T->isVoidType()) {
8937 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8938 // of objects and functions.
8939 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8940 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
8941 << T;
8942 NewVD->setInvalidDecl();
8943 return;
8944 }
8945 }
8946
8947 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8948 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_on_nonlocal);
8949 NewVD->setInvalidDecl();
8950 return;
8951 }
8952
8953 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8954 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
8955 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sizeless_nonlocal) << T;
8956 NewVD->setInvalidDecl();
8957 return;
8958 }
8959
8960 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8961 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_on_vm);
8962 NewVD->setInvalidDecl();
8963 return;
8964 }
8965
8966 if (getLangOpts().C23 && NewVD->isConstexpr() &&
8967 CheckC23ConstexprVarType(SemaRef&: *this, VarLoc: NewVD->getLocation(), T)) {
8968 NewVD->setInvalidDecl();
8969 return;
8970 }
8971
8972 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
8973 !T->isDependentType() &&
8974 RequireLiteralType(Loc: NewVD->getLocation(), T,
8975 DiagID: diag::err_constexpr_var_non_literal)) {
8976 NewVD->setInvalidDecl();
8977 return;
8978 }
8979
8980 // PPC MMA non-pointer types are not allowed as non-local variable types.
8981 if (Context.getTargetInfo().getTriple().isPPC64() &&
8982 !NewVD->isLocalVarDecl() &&
8983 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewVD->getLocation())) {
8984 NewVD->setInvalidDecl();
8985 return;
8986 }
8987
8988 // Check that SVE types are only used in functions with SVE available.
8989 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
8990 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
8991 llvm::StringMap<bool> CallerFeatureMap;
8992 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
8993
8994 if (!Builtin::evaluateRequiredTargetFeatures(RequiredFatures: "sve", TargetFetureMap: CallerFeatureMap)) {
8995 if (!Builtin::evaluateRequiredTargetFeatures(RequiredFatures: "sme", TargetFetureMap: CallerFeatureMap)) {
8996 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sve_vector_in_non_sve_target) << T;
8997 NewVD->setInvalidDecl();
8998 return;
8999 } else if (!IsArmStreamingFunction(FD,
9000 /*IncludeLocallyStreaming=*/true)) {
9001 Diag(Loc: NewVD->getLocation(),
9002 DiagID: diag::err_sve_vector_in_non_streaming_function)
9003 << T;
9004 NewVD->setInvalidDecl();
9005 return;
9006 }
9007 }
9008 }
9009
9010 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9011 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9012 llvm::StringMap<bool> CallerFeatureMap;
9013 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9014 RISCV().checkRVVTypeSupport(Ty: T, Loc: NewVD->getLocation(), D: cast<Decl>(Val: CurContext),
9015 FeatureMap: CallerFeatureMap);
9016 }
9017}
9018
9019bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
9020 CheckVariableDeclarationType(NewVD);
9021
9022 // If the decl is already known invalid, don't check it.
9023 if (NewVD->isInvalidDecl())
9024 return false;
9025
9026 // If we did not find anything by this name, look for a non-visible
9027 // extern "C" declaration with the same name.
9028 if (Previous.empty() &&
9029 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewVD, Previous))
9030 Previous.setShadowed();
9031
9032 if (!Previous.empty()) {
9033 MergeVarDecl(New: NewVD, Previous);
9034 return true;
9035 }
9036 return false;
9037}
9038
9039bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
9040 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
9041
9042 // Look for methods in base classes that this method might override.
9043 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9044 /*DetectVirtual=*/false);
9045 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9046 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9047 DeclarationName Name = MD->getDeclName();
9048
9049 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9050 // We really want to find the base class destructor here.
9051 QualType T = Context.getTypeDeclType(Decl: BaseRecord);
9052 CanQualType CT = Context.getCanonicalType(T);
9053 Name = Context.DeclarationNames.getCXXDestructorName(Ty: CT);
9054 }
9055
9056 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9057 CXXMethodDecl *BaseMD =
9058 dyn_cast<CXXMethodDecl>(Val: BaseND->getCanonicalDecl());
9059 if (!BaseMD || !BaseMD->isVirtual() ||
9060 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9061 /*ConsiderCudaAttrs=*/true))
9062 continue;
9063 if (!CheckExplicitObjectOverride(New: MD, Old: BaseMD))
9064 continue;
9065 if (Overridden.insert(Ptr: BaseMD).second) {
9066 MD->addOverriddenMethod(MD: BaseMD);
9067 CheckOverridingFunctionReturnType(New: MD, Old: BaseMD);
9068 CheckOverridingFunctionAttributes(New: MD, Old: BaseMD);
9069 CheckOverridingFunctionExceptionSpec(New: MD, Old: BaseMD);
9070 CheckIfOverriddenFunctionIsMarkedFinal(New: MD, Old: BaseMD);
9071 }
9072
9073 // A method can only override one function from each base class. We
9074 // don't track indirectly overridden methods from bases of bases.
9075 return true;
9076 }
9077
9078 return false;
9079 };
9080
9081 DC->lookupInBases(BaseMatches: VisitBase, Paths);
9082 return !Overridden.empty();
9083}
9084
9085namespace {
9086 // Struct for holding all of the extra arguments needed by
9087 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9088 struct ActOnFDArgs {
9089 Scope *S;
9090 Declarator &D;
9091 MultiTemplateParamsArg TemplateParamLists;
9092 bool AddToScope;
9093 };
9094} // end anonymous namespace
9095
9096namespace {
9097
9098// Callback to only accept typo corrections that have a non-zero edit distance.
9099// Also only accept corrections that have the same parent decl.
9100class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9101 public:
9102 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9103 CXXRecordDecl *Parent)
9104 : Context(Context), OriginalFD(TypoFD),
9105 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9106
9107 bool ValidateCandidate(const TypoCorrection &candidate) override {
9108 if (candidate.getEditDistance() == 0)
9109 return false;
9110
9111 SmallVector<unsigned, 1> MismatchedParams;
9112 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9113 CDeclEnd = candidate.end();
9114 CDecl != CDeclEnd; ++CDecl) {
9115 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9116
9117 if (FD && !FD->hasBody() &&
9118 hasSimilarParameters(Context, Declaration: FD, Definition: OriginalFD, Params&: MismatchedParams)) {
9119 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
9120 CXXRecordDecl *Parent = MD->getParent();
9121 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9122 return true;
9123 } else if (!ExpectedParent) {
9124 return true;
9125 }
9126 }
9127 }
9128
9129 return false;
9130 }
9131
9132 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9133 return std::make_unique<DifferentNameValidatorCCC>(args&: *this);
9134 }
9135
9136 private:
9137 ASTContext &Context;
9138 FunctionDecl *OriginalFD;
9139 CXXRecordDecl *ExpectedParent;
9140};
9141
9142} // end anonymous namespace
9143
9144void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9145 TypoCorrectedFunctionDefinitions.insert(Ptr: F);
9146}
9147
9148/// Generate diagnostics for an invalid function redeclaration.
9149///
9150/// This routine handles generating the diagnostic messages for an invalid
9151/// function redeclaration, including finding possible similar declarations
9152/// or performing typo correction if there are no previous declarations with
9153/// the same name.
9154///
9155/// Returns a NamedDecl iff typo correction was performed and substituting in
9156/// the new declaration name does not cause new errors.
9157static NamedDecl *DiagnoseInvalidRedeclaration(
9158 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9159 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9160 DeclarationName Name = NewFD->getDeclName();
9161 DeclContext *NewDC = NewFD->getDeclContext();
9162 SmallVector<unsigned, 1> MismatchedParams;
9163 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9164 TypoCorrection Correction;
9165 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9166 unsigned DiagMsg =
9167 IsLocalFriend ? diag::err_no_matching_local_friend :
9168 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9169 diag::err_member_decl_does_not_match;
9170 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9171 IsLocalFriend ? Sema::LookupLocalFriendName
9172 : Sema::LookupOrdinaryName,
9173 RedeclarationKind::ForVisibleRedeclaration);
9174
9175 NewFD->setInvalidDecl();
9176 if (IsLocalFriend)
9177 SemaRef.LookupName(R&: Prev, S);
9178 else
9179 SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: NewDC);
9180 assert(!Prev.isAmbiguous() &&
9181 "Cannot have an ambiguity in previous-declaration lookup");
9182 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9183 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9184 MD ? MD->getParent() : nullptr);
9185 if (!Prev.empty()) {
9186 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9187 Func != FuncEnd; ++Func) {
9188 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *Func);
9189 if (FD &&
9190 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9191 // Add 1 to the index so that 0 can mean the mismatch didn't
9192 // involve a parameter
9193 unsigned ParamNum =
9194 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9195 NearMatches.push_back(Elt: std::make_pair(x&: FD, y&: ParamNum));
9196 }
9197 }
9198 // If the qualified name lookup yielded nothing, try typo correction
9199 } else if ((Correction = SemaRef.CorrectTypo(
9200 Typo: Prev.getLookupNameInfo(), LookupKind: Prev.getLookupKind(), S,
9201 SS: &ExtraArgs.D.getCXXScopeSpec(), CCC,
9202 Mode: CorrectTypoKind::ErrorRecovery,
9203 MemberContext: IsLocalFriend ? nullptr : NewDC))) {
9204 // Set up everything for the call to ActOnFunctionDeclarator
9205 ExtraArgs.D.SetIdentifier(Id: Correction.getCorrectionAsIdentifierInfo(),
9206 IdLoc: ExtraArgs.D.getIdentifierLoc());
9207 Previous.clear();
9208 Previous.setLookupName(Correction.getCorrection());
9209 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9210 CDeclEnd = Correction.end();
9211 CDecl != CDeclEnd; ++CDecl) {
9212 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9213 if (FD && !FD->hasBody() &&
9214 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9215 Previous.addDecl(D: FD);
9216 }
9217 }
9218 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9219
9220 NamedDecl *Result;
9221 // Retry building the function declaration with the new previous
9222 // declarations, and with errors suppressed.
9223 {
9224 // Trap errors.
9225 Sema::SFINAETrap Trap(SemaRef);
9226
9227 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9228 // pieces need to verify the typo-corrected C++ declaration and hopefully
9229 // eliminate the need for the parameter pack ExtraArgs.
9230 Result = SemaRef.ActOnFunctionDeclarator(
9231 S: ExtraArgs.S, D&: ExtraArgs.D,
9232 DC: Correction.getCorrectionDecl()->getDeclContext(),
9233 TInfo: NewFD->getTypeSourceInfo(), Previous, TemplateParamLists: ExtraArgs.TemplateParamLists,
9234 AddToScope&: ExtraArgs.AddToScope);
9235
9236 if (Trap.hasErrorOccurred())
9237 Result = nullptr;
9238 }
9239
9240 if (Result) {
9241 // Determine which correction we picked.
9242 Decl *Canonical = Result->getCanonicalDecl();
9243 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9244 I != E; ++I)
9245 if ((*I)->getCanonicalDecl() == Canonical)
9246 Correction.setCorrectionDecl(*I);
9247
9248 // Let Sema know about the correction.
9249 SemaRef.MarkTypoCorrectedFunctionDefinition(F: Result);
9250 SemaRef.diagnoseTypo(
9251 Correction,
9252 TypoDiag: SemaRef.PDiag(DiagID: IsLocalFriend
9253 ? diag::err_no_matching_local_friend_suggest
9254 : diag::err_member_decl_does_not_match_suggest)
9255 << Name << NewDC << IsDefinition);
9256 return Result;
9257 }
9258
9259 // Pretend the typo correction never occurred
9260 ExtraArgs.D.SetIdentifier(Id: Name.getAsIdentifierInfo(),
9261 IdLoc: ExtraArgs.D.getIdentifierLoc());
9262 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9263 Previous.clear();
9264 Previous.setLookupName(Name);
9265 }
9266
9267 SemaRef.Diag(Loc: NewFD->getLocation(), DiagID: DiagMsg)
9268 << Name << NewDC << IsDefinition << NewFD->getLocation();
9269
9270 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9271 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9272 CXXRecordDecl *RD = NewMD->getParent();
9273 SemaRef.Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here)
9274 << RD->getName() << RD->getLocation();
9275 }
9276
9277 bool NewFDisConst = NewMD && NewMD->isConst();
9278
9279 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9280 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9281 NearMatch != NearMatchEnd; ++NearMatch) {
9282 FunctionDecl *FD = NearMatch->first;
9283 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
9284 bool FDisConst = MD && MD->isConst();
9285 bool IsMember = MD || !IsLocalFriend;
9286
9287 // FIXME: These notes are poorly worded for the local friend case.
9288 if (unsigned Idx = NearMatch->second) {
9289 ParmVarDecl *FDParam = FD->getParamDecl(i: Idx-1);
9290 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9291 if (Loc.isInvalid()) Loc = FD->getLocation();
9292 SemaRef.Diag(Loc, DiagID: IsMember ? diag::note_member_def_close_param_match
9293 : diag::note_local_decl_close_param_match)
9294 << Idx << FDParam->getType()
9295 << NewFD->getParamDecl(i: Idx - 1)->getType();
9296 } else if (FDisConst != NewFDisConst) {
9297 auto DB = SemaRef.Diag(Loc: FD->getLocation(),
9298 DiagID: diag::note_member_def_close_const_match)
9299 << NewFDisConst << FD->getSourceRange().getEnd();
9300 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9301 DB << FixItHint::CreateInsertion(InsertionLoc: FTI.getRParenLoc().getLocWithOffset(Offset: 1),
9302 Code: " const");
9303 else if (FTI.hasMethodTypeQualifiers() &&
9304 FTI.getConstQualifierLoc().isValid())
9305 DB << FixItHint::CreateRemoval(RemoveRange: FTI.getConstQualifierLoc());
9306 } else {
9307 SemaRef.Diag(Loc: FD->getLocation(),
9308 DiagID: IsMember ? diag::note_member_def_close_match
9309 : diag::note_local_decl_close_match);
9310 }
9311 }
9312 return nullptr;
9313}
9314
9315static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9316 switch (D.getDeclSpec().getStorageClassSpec()) {
9317 default: llvm_unreachable("Unknown storage class!");
9318 case DeclSpec::SCS_auto:
9319 case DeclSpec::SCS_register:
9320 case DeclSpec::SCS_mutable:
9321 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9322 DiagID: diag::err_typecheck_sclass_func);
9323 D.getMutableDeclSpec().ClearStorageClassSpecs();
9324 D.setInvalidType();
9325 break;
9326 case DeclSpec::SCS_unspecified: break;
9327 case DeclSpec::SCS_extern:
9328 if (D.getDeclSpec().isExternInLinkageSpec())
9329 return SC_None;
9330 return SC_Extern;
9331 case DeclSpec::SCS_static: {
9332 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9333 // C99 6.7.1p5:
9334 // The declaration of an identifier for a function that has
9335 // block scope shall have no explicit storage-class specifier
9336 // other than extern
9337 // See also (C++ [dcl.stc]p4).
9338 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9339 DiagID: diag::err_static_block_func);
9340 break;
9341 } else
9342 return SC_Static;
9343 }
9344 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9345 }
9346
9347 // No explicit storage class has already been returned
9348 return SC_None;
9349}
9350
9351static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9352 DeclContext *DC, QualType &R,
9353 TypeSourceInfo *TInfo,
9354 StorageClass SC,
9355 bool &IsVirtualOkay) {
9356 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9357 DeclarationName Name = NameInfo.getName();
9358
9359 FunctionDecl *NewFD = nullptr;
9360 bool isInline = D.getDeclSpec().isInlineSpecified();
9361
9362 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9363 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9364 (SemaRef.getLangOpts().C23 &&
9365 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9366
9367 if (SemaRef.getLangOpts().C23)
9368 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9369 DiagID: diag::err_c23_constexpr_not_variable);
9370 else
9371 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9372 DiagID: diag::err_constexpr_wrong_decl_kind)
9373 << static_cast<int>(ConstexprKind);
9374 ConstexprKind = ConstexprSpecKind::Unspecified;
9375 D.getMutableDeclSpec().ClearConstexprSpec();
9376 }
9377
9378 if (!SemaRef.getLangOpts().CPlusPlus) {
9379 // Determine whether the function was written with a prototype. This is
9380 // true when:
9381 // - there is a prototype in the declarator, or
9382 // - the type R of the function is some kind of typedef or other non-
9383 // attributed reference to a type name (which eventually refers to a
9384 // function type). Note, we can't always look at the adjusted type to
9385 // check this case because attributes may cause a non-function
9386 // declarator to still have a function type. e.g.,
9387 // typedef void func(int a);
9388 // __attribute__((noreturn)) func other_func; // This has a prototype
9389 bool HasPrototype =
9390 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9391 (D.getDeclSpec().isTypeRep() &&
9392 SemaRef.GetTypeFromParser(Ty: D.getDeclSpec().getRepAsType(), TInfo: nullptr)
9393 ->isFunctionProtoType()) ||
9394 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9395 assert(
9396 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9397 "Strict prototypes are required");
9398
9399 NewFD = FunctionDecl::Create(
9400 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9401 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline, hasWrittenPrototype: HasPrototype,
9402 ConstexprKind: ConstexprSpecKind::Unspecified,
9403 /*TrailingRequiresClause=*/{});
9404 if (D.isInvalidType())
9405 NewFD->setInvalidDecl();
9406
9407 return NewFD;
9408 }
9409
9410 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9411 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9412
9413 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9414
9415 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9416 // This is a C++ constructor declaration.
9417 assert(DC->isRecord() &&
9418 "Constructors can only be declared in a member context");
9419
9420 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9421 return CXXConstructorDecl::Create(
9422 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9423 TInfo, ES: ExplicitSpecifier, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(),
9424 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9425 Inherited: InheritedConstructor(), TrailingRequiresClause);
9426
9427 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9428 // This is a C++ destructor declaration.
9429 if (DC->isRecord()) {
9430 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9431 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC);
9432 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9433 C&: SemaRef.Context, RD: Record, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo,
9434 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9435 /*isImplicitlyDeclared=*/false, ConstexprKind,
9436 TrailingRequiresClause);
9437 // User defined destructors start as not selected if the class definition is still
9438 // not done.
9439 if (Record->isBeingDefined())
9440 NewDD->setIneligibleOrNotSelected(true);
9441
9442 // If the destructor needs an implicit exception specification, set it
9443 // now. FIXME: It'd be nice to be able to create the right type to start
9444 // with, but the type needs to reference the destructor declaration.
9445 if (SemaRef.getLangOpts().CPlusPlus11)
9446 SemaRef.AdjustDestructorExceptionSpec(Destructor: NewDD);
9447
9448 IsVirtualOkay = true;
9449 return NewDD;
9450
9451 } else {
9452 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_not_member);
9453 D.setInvalidType();
9454
9455 // Create a FunctionDecl to satisfy the function definition parsing
9456 // code path.
9457 return FunctionDecl::Create(
9458 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NLoc: D.getIdentifierLoc(), N: Name, T: R,
9459 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9460 /*hasPrototype=*/hasWrittenPrototype: true, ConstexprKind, TrailingRequiresClause);
9461 }
9462
9463 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9464 if (!DC->isRecord()) {
9465 SemaRef.Diag(Loc: D.getIdentifierLoc(),
9466 DiagID: diag::err_conv_function_not_member);
9467 return nullptr;
9468 }
9469
9470 SemaRef.CheckConversionDeclarator(D, R, SC);
9471 if (D.isInvalidType())
9472 return nullptr;
9473
9474 IsVirtualOkay = true;
9475 return CXXConversionDecl::Create(
9476 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9477 TInfo, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9478 ES: ExplicitSpecifier, ConstexprKind, EndLocation: SourceLocation(),
9479 TrailingRequiresClause);
9480
9481 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9482 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9483 return nullptr;
9484 return CXXDeductionGuideDecl::Create(
9485 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), ES: ExplicitSpecifier, NameInfo, T: R,
9486 TInfo, EndLocation: D.getEndLoc(), /*Ctor=*/nullptr,
9487 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9488 } else if (DC->isRecord()) {
9489 // If the name of the function is the same as the name of the record,
9490 // then this must be an invalid constructor that has a return type.
9491 // (The parser checks for a return type and makes the declarator a
9492 // constructor if it has no return type).
9493 if (Name.getAsIdentifierInfo() &&
9494 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(Val: DC)->getIdentifier()){
9495 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_return_type)
9496 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9497 << SourceRange(D.getIdentifierLoc());
9498 return nullptr;
9499 }
9500
9501 // This is a C++ method declaration.
9502 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9503 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9504 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9505 ConstexprKind, EndLocation: SourceLocation(), TrailingRequiresClause);
9506 IsVirtualOkay = !Ret->isStatic();
9507 return Ret;
9508 } else {
9509 bool isFriend =
9510 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9511 if (!isFriend && SemaRef.CurContext->isRecord())
9512 return nullptr;
9513
9514 // Determine whether the function was written with a
9515 // prototype. This true when:
9516 // - we're in C++ (where every function has a prototype),
9517 return FunctionDecl::Create(
9518 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9519 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9520 hasWrittenPrototype: true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9521 }
9522}
9523
9524enum OpenCLParamType {
9525 ValidKernelParam,
9526 PtrPtrKernelParam,
9527 PtrKernelParam,
9528 InvalidAddrSpacePtrKernelParam,
9529 InvalidKernelParam,
9530 RecordKernelParam
9531};
9532
9533static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9534 // Size dependent types are just typedefs to normal integer types
9535 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9536 // integers other than by their names.
9537 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9538
9539 // Remove typedefs one by one until we reach a typedef
9540 // for a size dependent type.
9541 QualType DesugaredTy = Ty;
9542 do {
9543 ArrayRef<StringRef> Names(SizeTypeNames);
9544 auto Match = llvm::find(Range&: Names, Val: DesugaredTy.getUnqualifiedType().getAsString());
9545 if (Names.end() != Match)
9546 return true;
9547
9548 Ty = DesugaredTy;
9549 DesugaredTy = Ty.getSingleStepDesugaredType(Context: C);
9550 } while (DesugaredTy != Ty);
9551
9552 return false;
9553}
9554
9555static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9556 if (PT->isDependentType())
9557 return InvalidKernelParam;
9558
9559 if (PT->isPointerOrReferenceType()) {
9560 QualType PointeeType = PT->getPointeeType();
9561 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9562 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9563 PointeeType.getAddressSpace() == LangAS::Default)
9564 return InvalidAddrSpacePtrKernelParam;
9565
9566 if (PointeeType->isPointerType()) {
9567 // This is a pointer to pointer parameter.
9568 // Recursively check inner type.
9569 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PT: PointeeType);
9570 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9571 ParamKind == InvalidKernelParam)
9572 return ParamKind;
9573
9574 // OpenCL v3.0 s6.11.a:
9575 // A restriction to pass pointers to pointers only applies to OpenCL C
9576 // v1.2 or below.
9577 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9578 return ValidKernelParam;
9579
9580 return PtrPtrKernelParam;
9581 }
9582
9583 // C++ for OpenCL v1.0 s2.4:
9584 // Moreover the types used in parameters of the kernel functions must be:
9585 // Standard layout types for pointer parameters. The same applies to
9586 // reference if an implementation supports them in kernel parameters.
9587 if (S.getLangOpts().OpenCLCPlusPlus &&
9588 !S.getOpenCLOptions().isAvailableOption(
9589 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts())) {
9590 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9591 bool IsStandardLayoutType = true;
9592 if (CXXRec) {
9593 // If template type is not ODR-used its definition is only available
9594 // in the template definition not its instantiation.
9595 // FIXME: This logic doesn't work for types that depend on template
9596 // parameter (PR58590).
9597 if (!CXXRec->hasDefinition())
9598 CXXRec = CXXRec->getTemplateInstantiationPattern();
9599 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9600 IsStandardLayoutType = false;
9601 }
9602 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9603 !IsStandardLayoutType)
9604 return InvalidKernelParam;
9605 }
9606
9607 // OpenCL v1.2 s6.9.p:
9608 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9609 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9610 return ValidKernelParam;
9611
9612 return PtrKernelParam;
9613 }
9614
9615 // OpenCL v1.2 s6.9.k:
9616 // Arguments to kernel functions in a program cannot be declared with the
9617 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9618 // uintptr_t or a struct and/or union that contain fields declared to be one
9619 // of these built-in scalar types.
9620 if (isOpenCLSizeDependentType(C&: S.getASTContext(), Ty: PT))
9621 return InvalidKernelParam;
9622
9623 if (PT->isImageType())
9624 return PtrKernelParam;
9625
9626 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9627 return InvalidKernelParam;
9628
9629 // OpenCL extension spec v1.2 s9.5:
9630 // This extension adds support for half scalar and vector types as built-in
9631 // types that can be used for arithmetic operations, conversions etc.
9632 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: S.getLangOpts()) &&
9633 PT->isHalfType())
9634 return InvalidKernelParam;
9635
9636 // Look into an array argument to check if it has a forbidden type.
9637 if (PT->isArrayType()) {
9638 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9639 // Call ourself to check an underlying type of an array. Since the
9640 // getPointeeOrArrayElementType returns an innermost type which is not an
9641 // array, this recursive call only happens once.
9642 return getOpenCLKernelParameterType(S, PT: QualType(UnderlyingTy, 0));
9643 }
9644
9645 // C++ for OpenCL v1.0 s2.4:
9646 // Moreover the types used in parameters of the kernel functions must be:
9647 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9648 // types) for parameters passed by value;
9649 if (S.getLangOpts().OpenCLCPlusPlus &&
9650 !S.getOpenCLOptions().isAvailableOption(
9651 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts()) &&
9652 !PT->isOpenCLSpecificType() && !PT.isPODType(Context: S.Context))
9653 return InvalidKernelParam;
9654
9655 if (PT->isRecordType())
9656 return RecordKernelParam;
9657
9658 return ValidKernelParam;
9659}
9660
9661static void checkIsValidOpenCLKernelParameter(
9662 Sema &S,
9663 Declarator &D,
9664 ParmVarDecl *Param,
9665 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9666 QualType PT = Param->getType();
9667
9668 // Cache the valid types we encounter to avoid rechecking structs that are
9669 // used again
9670 if (ValidTypes.count(Ptr: PT.getTypePtr()))
9671 return;
9672
9673 switch (getOpenCLKernelParameterType(S, PT)) {
9674 case PtrPtrKernelParam:
9675 // OpenCL v3.0 s6.11.a:
9676 // A kernel function argument cannot be declared as a pointer to a pointer
9677 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9678 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_opencl_ptrptr_kernel_param);
9679 D.setInvalidType();
9680 return;
9681
9682 case InvalidAddrSpacePtrKernelParam:
9683 // OpenCL v1.0 s6.5:
9684 // __kernel function arguments declared to be a pointer of a type can point
9685 // to one of the following address spaces only : __global, __local or
9686 // __constant.
9687 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_kernel_arg_address_space);
9688 D.setInvalidType();
9689 return;
9690
9691 // OpenCL v1.2 s6.9.k:
9692 // Arguments to kernel functions in a program cannot be declared with the
9693 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9694 // uintptr_t or a struct and/or union that contain fields declared to be
9695 // one of these built-in scalar types.
9696
9697 case InvalidKernelParam:
9698 // OpenCL v1.2 s6.8 n:
9699 // A kernel function argument cannot be declared
9700 // of event_t type.
9701 // Do not diagnose half type since it is diagnosed as invalid argument
9702 // type for any function elsewhere.
9703 if (!PT->isHalfType()) {
9704 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
9705
9706 // Explain what typedefs are involved.
9707 const TypedefType *Typedef = nullptr;
9708 while ((Typedef = PT->getAs<TypedefType>())) {
9709 SourceLocation Loc = Typedef->getDecl()->getLocation();
9710 // SourceLocation may be invalid for a built-in type.
9711 if (Loc.isValid())
9712 S.Diag(Loc, DiagID: diag::note_entity_declared_at) << PT;
9713 PT = Typedef->desugar();
9714 }
9715 }
9716
9717 D.setInvalidType();
9718 return;
9719
9720 case PtrKernelParam:
9721 case ValidKernelParam:
9722 ValidTypes.insert(Ptr: PT.getTypePtr());
9723 return;
9724
9725 case RecordKernelParam:
9726 break;
9727 }
9728
9729 // Track nested structs we will inspect
9730 SmallVector<const Decl *, 4> VisitStack;
9731
9732 // Track where we are in the nested structs. Items will migrate from
9733 // VisitStack to HistoryStack as we do the DFS for bad field.
9734 SmallVector<const FieldDecl *, 4> HistoryStack;
9735 HistoryStack.push_back(Elt: nullptr);
9736
9737 // At this point we already handled everything except of a RecordType.
9738 assert(PT->isRecordType() && "Unexpected type.");
9739 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
9740 VisitStack.push_back(Elt: PD);
9741 assert(VisitStack.back() && "First decl null?");
9742
9743 do {
9744 const Decl *Next = VisitStack.pop_back_val();
9745 if (!Next) {
9746 assert(!HistoryStack.empty());
9747 // Found a marker, we have gone up a level
9748 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9749 ValidTypes.insert(Ptr: Hist->getType().getTypePtr());
9750
9751 continue;
9752 }
9753
9754 // Adds everything except the original parameter declaration (which is not a
9755 // field itself) to the history stack.
9756 const RecordDecl *RD;
9757 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: Next)) {
9758 HistoryStack.push_back(Elt: Field);
9759
9760 QualType FieldTy = Field->getType();
9761 // Other field types (known to be valid or invalid) are handled while we
9762 // walk around RecordDecl::fields().
9763 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9764 "Unexpected type.");
9765 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9766
9767 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9768 } else {
9769 RD = cast<RecordDecl>(Val: Next);
9770 }
9771
9772 // Add a null marker so we know when we've gone back up a level
9773 VisitStack.push_back(Elt: nullptr);
9774
9775 for (const auto *FD : RD->fields()) {
9776 QualType QT = FD->getType();
9777
9778 if (ValidTypes.count(Ptr: QT.getTypePtr()))
9779 continue;
9780
9781 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, PT: QT);
9782 if (ParamType == ValidKernelParam)
9783 continue;
9784
9785 if (ParamType == RecordKernelParam) {
9786 VisitStack.push_back(Elt: FD);
9787 continue;
9788 }
9789
9790 // OpenCL v1.2 s6.9.p:
9791 // Arguments to kernel functions that are declared to be a struct or union
9792 // do not allow OpenCL objects to be passed as elements of the struct or
9793 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9794 // of SVM.
9795 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9796 ParamType == InvalidAddrSpacePtrKernelParam) {
9797 S.Diag(Loc: Param->getLocation(),
9798 DiagID: diag::err_record_with_pointers_kernel_param)
9799 << PT->isUnionType()
9800 << PT;
9801 } else {
9802 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
9803 }
9804
9805 S.Diag(Loc: PD->getLocation(), DiagID: diag::note_within_field_of_type)
9806 << PD->getDeclName();
9807
9808 // We have an error, now let's go back up through history and show where
9809 // the offending field came from
9810 for (ArrayRef<const FieldDecl *>::const_iterator
9811 I = HistoryStack.begin() + 1,
9812 E = HistoryStack.end();
9813 I != E; ++I) {
9814 const FieldDecl *OuterField = *I;
9815 S.Diag(Loc: OuterField->getLocation(), DiagID: diag::note_within_field_of_type)
9816 << OuterField->getType();
9817 }
9818
9819 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_illegal_field_declared_here)
9820 << QT->isPointerType()
9821 << QT;
9822 D.setInvalidType();
9823 return;
9824 }
9825 } while (!VisitStack.empty());
9826}
9827
9828/// Find the DeclContext in which a tag is implicitly declared if we see an
9829/// elaborated type specifier in the specified context, and lookup finds
9830/// nothing.
9831static DeclContext *getTagInjectionContext(DeclContext *DC) {
9832 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9833 DC = DC->getParent();
9834 return DC;
9835}
9836
9837/// Find the Scope in which a tag is implicitly declared if we see an
9838/// elaborated type specifier in the specified context, and lookup finds
9839/// nothing.
9840static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9841 while (S->isClassScope() ||
9842 (LangOpts.CPlusPlus &&
9843 S->isFunctionPrototypeScope()) ||
9844 ((S->getFlags() & Scope::DeclScope) == 0) ||
9845 (S->getEntity() && S->getEntity()->isTransparentContext()))
9846 S = S->getParent();
9847 return S;
9848}
9849
9850/// Determine whether a declaration matches a known function in namespace std.
9851static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9852 unsigned BuiltinID) {
9853 switch (BuiltinID) {
9854 case Builtin::BI__GetExceptionInfo:
9855 // No type checking whatsoever.
9856 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9857
9858 case Builtin::BIaddressof:
9859 case Builtin::BI__addressof:
9860 case Builtin::BIforward:
9861 case Builtin::BIforward_like:
9862 case Builtin::BImove:
9863 case Builtin::BImove_if_noexcept:
9864 case Builtin::BIas_const: {
9865 // Ensure that we don't treat the algorithm
9866 // OutputIt std::move(InputIt, InputIt, OutputIt)
9867 // as the builtin std::move.
9868 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9869 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9870 }
9871
9872 default:
9873 return false;
9874 }
9875}
9876
9877NamedDecl*
9878Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9879 TypeSourceInfo *TInfo, LookupResult &Previous,
9880 MultiTemplateParamsArg TemplateParamListsRef,
9881 bool &AddToScope) {
9882 QualType R = TInfo->getType();
9883
9884 assert(R->isFunctionType());
9885 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9886 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_decl_cmse_ns_call);
9887
9888 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9889 llvm::append_range(C&: TemplateParamLists, R&: TemplateParamListsRef);
9890 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9891 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9892 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9893 TemplateParamLists.back() = Invented;
9894 else
9895 TemplateParamLists.push_back(Elt: Invented);
9896 }
9897
9898 // TODO: consider using NameInfo for diagnostic.
9899 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9900 DeclarationName Name = NameInfo.getName();
9901 StorageClass SC = getFunctionStorageClass(SemaRef&: *this, D);
9902
9903 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9904 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
9905 DiagID: diag::err_invalid_thread)
9906 << DeclSpec::getSpecifierName(S: TSCS);
9907
9908 if (D.isFirstDeclarationOfMember())
9909 adjustMemberFunctionCC(
9910 T&: R, HasThisPointer: !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
9911 IsCtorOrDtor: D.isCtorOrDtor(), Loc: D.getIdentifierLoc());
9912
9913 bool isFriend = false;
9914 FunctionTemplateDecl *FunctionTemplate = nullptr;
9915 bool isMemberSpecialization = false;
9916 bool isFunctionTemplateSpecialization = false;
9917
9918 bool HasExplicitTemplateArgs = false;
9919 TemplateArgumentListInfo TemplateArgs;
9920
9921 bool isVirtualOkay = false;
9922
9923 DeclContext *OriginalDC = DC;
9924 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9925
9926 FunctionDecl *NewFD = CreateNewFunctionDecl(SemaRef&: *this, D, DC, R, TInfo, SC,
9927 IsVirtualOkay&: isVirtualOkay);
9928 if (!NewFD) return nullptr;
9929
9930 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9931 NewFD->setTopLevelDeclInObjCContainer();
9932
9933 // Set the lexical context. If this is a function-scope declaration, or has a
9934 // C++ scope specifier, or is the object of a friend declaration, the lexical
9935 // context will be different from the semantic context.
9936 NewFD->setLexicalDeclContext(CurContext);
9937
9938 if (IsLocalExternDecl)
9939 NewFD->setLocalExternDecl();
9940
9941 if (getLangOpts().CPlusPlus) {
9942 // The rules for implicit inlines changed in C++20 for methods and friends
9943 // with an in-class definition (when such a definition is not attached to
9944 // the global module). This does not affect declarations that are already
9945 // inline (whether explicitly or implicitly by being declared constexpr,
9946 // consteval, etc).
9947 // FIXME: We need a better way to separate C++ standard and clang modules.
9948 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9949 !NewFD->getOwningModule() ||
9950 NewFD->isFromGlobalModule() ||
9951 NewFD->getOwningModule()->isHeaderLikeModule();
9952 bool isInline = D.getDeclSpec().isInlineSpecified();
9953 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9954 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9955 isFriend = D.getDeclSpec().isFriendSpecified();
9956 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
9957 // Pre-C++20 [class.friend]p5
9958 // A function can be defined in a friend declaration of a
9959 // class . . . . Such a function is implicitly inline.
9960 // Post C++20 [class.friend]p7
9961 // Such a function is implicitly an inline function if it is attached
9962 // to the global module.
9963 NewFD->setImplicitlyInline();
9964 }
9965
9966 // If this is a method defined in an __interface, and is not a constructor
9967 // or an overloaded operator, then set the pure flag (isVirtual will already
9968 // return true).
9969 if (const CXXRecordDecl *Parent =
9970 dyn_cast<CXXRecordDecl>(Val: NewFD->getDeclContext())) {
9971 if (Parent->isInterface() && cast<CXXMethodDecl>(Val: NewFD)->isUserProvided())
9972 NewFD->setIsPureVirtual(true);
9973
9974 // C++ [class.union]p2
9975 // A union can have member functions, but not virtual functions.
9976 if (isVirtual && Parent->isUnion()) {
9977 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_virtual_in_union);
9978 NewFD->setInvalidDecl();
9979 }
9980 if ((Parent->isClass() || Parent->isStruct()) &&
9981 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9982 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9983 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9984 if (auto *Def = Parent->getDefinition())
9985 Def->setInitMethod(true);
9986 }
9987 }
9988
9989 SetNestedNameSpecifier(S&: *this, DD: NewFD, D);
9990 isMemberSpecialization = false;
9991 isFunctionTemplateSpecialization = false;
9992 if (D.isInvalidType())
9993 NewFD->setInvalidDecl();
9994
9995 // Match up the template parameter lists with the scope specifier, then
9996 // determine whether we have a template or a template specialization.
9997 bool Invalid = false;
9998 TemplateIdAnnotation *TemplateId =
9999 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
10000 ? D.getName().TemplateId
10001 : nullptr;
10002 TemplateParameterList *TemplateParams =
10003 MatchTemplateParametersToScopeSpecifier(
10004 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
10005 SS: D.getCXXScopeSpec(), TemplateId, ParamLists: TemplateParamLists, IsFriend: isFriend,
10006 IsMemberSpecialization&: isMemberSpecialization, Invalid);
10007 if (TemplateParams) {
10008 // Check that we can declare a template here.
10009 if (CheckTemplateDeclScope(S, TemplateParams))
10010 NewFD->setInvalidDecl();
10011
10012 if (TemplateParams->size() > 0) {
10013 // This is a function template
10014
10015 // A destructor cannot be a template.
10016 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
10017 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_template);
10018 NewFD->setInvalidDecl();
10019 // Function template with explicit template arguments.
10020 } else if (TemplateId) {
10021 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_template_partial_spec)
10022 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10023 NewFD->setInvalidDecl();
10024 }
10025
10026 // If we're adding a template to a dependent context, we may need to
10027 // rebuilding some of the types used within the template parameter list,
10028 // now that we know what the current instantiation is.
10029 if (DC->isDependentContext()) {
10030 ContextRAII SavedContext(*this, DC);
10031 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
10032 Invalid = true;
10033 }
10034
10035 FunctionTemplate = FunctionTemplateDecl::Create(C&: Context, DC,
10036 L: NewFD->getLocation(),
10037 Name, Params: TemplateParams,
10038 Decl: NewFD);
10039 FunctionTemplate->setLexicalDeclContext(CurContext);
10040 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
10041
10042 // For source fidelity, store the other template param lists.
10043 if (TemplateParamLists.size() > 1) {
10044 NewFD->setTemplateParameterListsInfo(Context,
10045 TPLists: ArrayRef<TemplateParameterList *>(TemplateParamLists)
10046 .drop_back(N: 1));
10047 }
10048 } else {
10049 // This is a function template specialization.
10050 isFunctionTemplateSpecialization = true;
10051 // For source fidelity, store all the template param lists.
10052 if (TemplateParamLists.size() > 0)
10053 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10054
10055 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10056 if (isFriend) {
10057 // We want to remove the "template<>", found here.
10058 SourceRange RemoveRange = TemplateParams->getSourceRange();
10059
10060 // If we remove the template<> and the name is not a
10061 // template-id, we're actually silently creating a problem:
10062 // the friend declaration will refer to an untemplated decl,
10063 // and clearly the user wants a template specialization. So
10064 // we need to insert '<>' after the name.
10065 SourceLocation InsertLoc;
10066 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10067 InsertLoc = D.getName().getSourceRange().getEnd();
10068 InsertLoc = getLocForEndOfToken(Loc: InsertLoc);
10069 }
10070
10071 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_spec_decl_friend)
10072 << Name << RemoveRange
10073 << FixItHint::CreateRemoval(RemoveRange)
10074 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: "<>");
10075 Invalid = true;
10076
10077 // Recover by faking up an empty template argument list.
10078 HasExplicitTemplateArgs = true;
10079 TemplateArgs.setLAngleLoc(InsertLoc);
10080 TemplateArgs.setRAngleLoc(InsertLoc);
10081 }
10082 }
10083 } else {
10084 // Check that we can declare a template here.
10085 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10086 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
10087 NewFD->setInvalidDecl();
10088
10089 // All template param lists were matched against the scope specifier:
10090 // this is NOT (an explicit specialization of) a template.
10091 if (TemplateParamLists.size() > 0)
10092 // For source fidelity, store all the template param lists.
10093 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10094
10095 // "friend void foo<>(int);" is an implicit specialization decl.
10096 if (isFriend && TemplateId)
10097 isFunctionTemplateSpecialization = true;
10098 }
10099
10100 // If this is a function template specialization and the unqualified-id of
10101 // the declarator-id is a template-id, convert the template argument list
10102 // into our AST format and check for unexpanded packs.
10103 if (isFunctionTemplateSpecialization && TemplateId) {
10104 HasExplicitTemplateArgs = true;
10105
10106 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10107 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10108 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10109 TemplateId->NumArgs);
10110 translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgs);
10111
10112 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10113 // declaration of a function template partial specialization? Should we
10114 // consider the unexpanded pack context to be a partial specialization?
10115 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10116 if (DiagnoseUnexpandedParameterPack(
10117 Arg: ArgLoc, UPPC: isFriend ? UPPC_FriendDeclaration
10118 : UPPC_ExplicitSpecialization))
10119 NewFD->setInvalidDecl();
10120 }
10121 }
10122
10123 if (Invalid) {
10124 NewFD->setInvalidDecl();
10125 if (FunctionTemplate)
10126 FunctionTemplate->setInvalidDecl();
10127 }
10128
10129 // C++ [dcl.fct.spec]p5:
10130 // The virtual specifier shall only be used in declarations of
10131 // nonstatic class member functions that appear within a
10132 // member-specification of a class declaration; see 10.3.
10133 //
10134 if (isVirtual && !NewFD->isInvalidDecl()) {
10135 if (!isVirtualOkay) {
10136 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10137 DiagID: diag::err_virtual_non_function);
10138 } else if (!CurContext->isRecord()) {
10139 // 'virtual' was specified outside of the class.
10140 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10141 DiagID: diag::err_virtual_out_of_class)
10142 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10143 } else if (NewFD->getDescribedFunctionTemplate()) {
10144 // C++ [temp.mem]p3:
10145 // A member function template shall not be virtual.
10146 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10147 DiagID: diag::err_virtual_member_function_template)
10148 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10149 } else {
10150 // Okay: Add virtual to the method.
10151 NewFD->setVirtualAsWritten(true);
10152 }
10153
10154 if (getLangOpts().CPlusPlus14 &&
10155 NewFD->getReturnType()->isUndeducedType())
10156 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_auto_fn_virtual);
10157 }
10158
10159 // C++ [dcl.fct.spec]p3:
10160 // The inline specifier shall not appear on a block scope function
10161 // declaration.
10162 if (isInline && !NewFD->isInvalidDecl()) {
10163 if (CurContext->isFunctionOrMethod()) {
10164 // 'inline' is not allowed on block scope function declaration.
10165 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10166 DiagID: diag::err_inline_declaration_block_scope) << Name
10167 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10168 }
10169 }
10170
10171 // C++ [dcl.fct.spec]p6:
10172 // The explicit specifier shall be used only in the declaration of a
10173 // constructor or conversion function within its class definition;
10174 // see 12.3.1 and 12.3.2.
10175 if (hasExplicit && !NewFD->isInvalidDecl() &&
10176 !isa<CXXDeductionGuideDecl>(Val: NewFD)) {
10177 if (!CurContext->isRecord()) {
10178 // 'explicit' was specified outside of the class.
10179 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10180 DiagID: diag::err_explicit_out_of_class)
10181 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10182 } else if (!isa<CXXConstructorDecl>(Val: NewFD) &&
10183 !isa<CXXConversionDecl>(Val: NewFD)) {
10184 // 'explicit' was specified on a function that wasn't a constructor
10185 // or conversion function.
10186 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10187 DiagID: diag::err_explicit_non_ctor_or_conv_function)
10188 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10189 }
10190 }
10191
10192 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10193 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10194 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10195 // are implicitly inline.
10196 NewFD->setImplicitlyInline();
10197
10198 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10199 // be either constructors or to return a literal type. Therefore,
10200 // destructors cannot be declared constexpr.
10201 if (isa<CXXDestructorDecl>(Val: NewFD) &&
10202 (!getLangOpts().CPlusPlus20 ||
10203 ConstexprKind == ConstexprSpecKind::Consteval)) {
10204 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_constexpr_dtor)
10205 << static_cast<int>(ConstexprKind);
10206 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10207 ? ConstexprSpecKind::Unspecified
10208 : ConstexprSpecKind::Constexpr);
10209 }
10210 // C++20 [dcl.constexpr]p2: An allocation function, or a
10211 // deallocation function shall not be declared with the consteval
10212 // specifier.
10213 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10214 NewFD->getDeclName().isAnyOperatorNewOrDelete()) {
10215 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10216 DiagID: diag::err_invalid_consteval_decl_kind)
10217 << NewFD;
10218 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10219 }
10220 }
10221
10222 // If __module_private__ was specified, mark the function accordingly.
10223 if (D.getDeclSpec().isModulePrivateSpecified()) {
10224 if (isFunctionTemplateSpecialization) {
10225 SourceLocation ModulePrivateLoc
10226 = D.getDeclSpec().getModulePrivateSpecLoc();
10227 Diag(Loc: ModulePrivateLoc, DiagID: diag::err_module_private_specialization)
10228 << 0
10229 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
10230 } else {
10231 NewFD->setModulePrivate();
10232 if (FunctionTemplate)
10233 FunctionTemplate->setModulePrivate();
10234 }
10235 }
10236
10237 if (isFriend) {
10238 if (FunctionTemplate) {
10239 FunctionTemplate->setObjectOfFriendDecl();
10240 FunctionTemplate->setAccess(AS_public);
10241 }
10242 NewFD->setObjectOfFriendDecl();
10243 NewFD->setAccess(AS_public);
10244 }
10245
10246 // If a function is defined as defaulted or deleted, mark it as such now.
10247 // We'll do the relevant checks on defaulted / deleted functions later.
10248 switch (D.getFunctionDefinitionKind()) {
10249 case FunctionDefinitionKind::Declaration:
10250 case FunctionDefinitionKind::Definition:
10251 break;
10252
10253 case FunctionDefinitionKind::Defaulted:
10254 NewFD->setDefaulted();
10255 break;
10256
10257 case FunctionDefinitionKind::Deleted:
10258 NewFD->setDeletedAsWritten();
10259 break;
10260 }
10261
10262 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(Val: NewFD) && DC == CurContext &&
10263 D.isFunctionDefinition()) {
10264 // Pre C++20 [class.mfct]p2:
10265 // A member function may be defined (8.4) in its class definition, in
10266 // which case it is an inline member function (7.1.2)
10267 // Post C++20 [class.mfct]p1:
10268 // If a member function is attached to the global module and is defined
10269 // in its class definition, it is inline.
10270 NewFD->setImplicitlyInline();
10271 }
10272
10273 if (!isFriend && SC != SC_None) {
10274 // C++ [temp.expl.spec]p2:
10275 // The declaration in an explicit-specialization shall not be an
10276 // export-declaration. An explicit specialization shall not use a
10277 // storage-class-specifier other than thread_local.
10278 //
10279 // We diagnose friend declarations with storage-class-specifiers
10280 // elsewhere.
10281 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10282 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10283 DiagID: diag::ext_explicit_specialization_storage_class)
10284 << FixItHint::CreateRemoval(
10285 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10286 }
10287
10288 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10289 assert(isa<CXXMethodDecl>(NewFD) &&
10290 "Out-of-line member function should be a CXXMethodDecl");
10291 // C++ [class.static]p1:
10292 // A data or function member of a class may be declared static
10293 // in a class definition, in which case it is a static member of
10294 // the class.
10295
10296 // Complain about the 'static' specifier if it's on an out-of-line
10297 // member function definition.
10298
10299 // MSVC permits the use of a 'static' storage specifier on an
10300 // out-of-line member function template declaration and class member
10301 // template declaration (MSVC versions before 2015), warn about this.
10302 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10303 DiagID: ((!getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
10304 cast<CXXRecordDecl>(Val: DC)->getDescribedClassTemplate()) ||
10305 (getLangOpts().MSVCCompat &&
10306 NewFD->getDescribedFunctionTemplate()))
10307 ? diag::ext_static_out_of_line
10308 : diag::err_static_out_of_line)
10309 << FixItHint::CreateRemoval(
10310 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10311 }
10312 }
10313
10314 // C++11 [except.spec]p15:
10315 // A deallocation function with no exception-specification is treated
10316 // as if it were specified with noexcept(true).
10317 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10318 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10319 !FPT->hasExceptionSpec())
10320 NewFD->setType(Context.getFunctionType(
10321 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
10322 EPI: FPT->getExtProtoInfo().withExceptionSpec(ESI: EST_BasicNoexcept)));
10323
10324 // C++20 [dcl.inline]/7
10325 // If an inline function or variable that is attached to a named module
10326 // is declared in a definition domain, it shall be defined in that
10327 // domain.
10328 // So, if the current declaration does not have a definition, we must
10329 // check at the end of the TU (or when the PMF starts) to see that we
10330 // have a definition at that point.
10331 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10332 NewFD->isInNamedModule()) {
10333 PendingInlineFuncDecls.insert(Ptr: NewFD);
10334 }
10335 }
10336
10337 // Filter out previous declarations that don't match the scope.
10338 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(FD: NewFD),
10339 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
10340 isMemberSpecialization ||
10341 isFunctionTemplateSpecialization);
10342
10343 // Handle GNU asm-label extension (encoded as an attribute).
10344 if (Expr *E = D.getAsmLabel()) {
10345 // The parser guarantees this is a string.
10346 StringLiteral *SE = cast<StringLiteral>(Val: E);
10347 NewFD->addAttr(A: AsmLabelAttr::Create(Ctx&: Context, Label: SE->getString(),
10348 /*IsLiteralLabel=*/true,
10349 Range: SE->getStrTokenLoc(TokNum: 0)));
10350 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10351 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10352 ExtnameUndeclaredIdentifiers.find(Val: NewFD->getIdentifier());
10353 if (I != ExtnameUndeclaredIdentifiers.end()) {
10354 if (isDeclExternC(D: NewFD)) {
10355 NewFD->addAttr(A: I->second);
10356 ExtnameUndeclaredIdentifiers.erase(I);
10357 } else
10358 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
10359 << /*Variable*/0 << NewFD;
10360 }
10361 }
10362
10363 // Copy the parameter declarations from the declarator D to the function
10364 // declaration NewFD, if they are available. First scavenge them into Params.
10365 SmallVector<ParmVarDecl*, 16> Params;
10366 unsigned FTIIdx;
10367 if (D.isFunctionDeclarator(idx&: FTIIdx)) {
10368 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(i: FTIIdx).Fun;
10369
10370 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10371 // function that takes no arguments, not a function that takes a
10372 // single void argument.
10373 // We let through "const void" here because Sema::GetTypeForDeclarator
10374 // already checks for that case.
10375 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10376 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10377 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
10378 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10379 Param->setDeclContext(NewFD);
10380 Params.push_back(Elt: Param);
10381
10382 if (Param->isInvalidDecl())
10383 NewFD->setInvalidDecl();
10384 }
10385 }
10386
10387 if (!getLangOpts().CPlusPlus) {
10388 // In C, find all the tag declarations from the prototype and move them
10389 // into the function DeclContext. Remove them from the surrounding tag
10390 // injection context of the function, which is typically but not always
10391 // the TU.
10392 DeclContext *PrototypeTagContext =
10393 getTagInjectionContext(DC: NewFD->getLexicalDeclContext());
10394 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10395 auto *TD = dyn_cast<TagDecl>(Val: NonParmDecl);
10396
10397 // We don't want to reparent enumerators. Look at their parent enum
10398 // instead.
10399 if (!TD) {
10400 if (auto *ECD = dyn_cast<EnumConstantDecl>(Val: NonParmDecl))
10401 TD = cast<EnumDecl>(Val: ECD->getDeclContext());
10402 }
10403 if (!TD)
10404 continue;
10405 DeclContext *TagDC = TD->getLexicalDeclContext();
10406 if (!TagDC->containsDecl(D: TD))
10407 continue;
10408 TagDC->removeDecl(D: TD);
10409 TD->setDeclContext(NewFD);
10410 NewFD->addDecl(D: TD);
10411
10412 // Preserve the lexical DeclContext if it is not the surrounding tag
10413 // injection context of the FD. In this example, the semantic context of
10414 // E will be f and the lexical context will be S, while both the
10415 // semantic and lexical contexts of S will be f:
10416 // void f(struct S { enum E { a } f; } s);
10417 if (TagDC != PrototypeTagContext)
10418 TD->setLexicalDeclContext(TagDC);
10419 }
10420 }
10421 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10422 // When we're declaring a function with a typedef, typeof, etc as in the
10423 // following example, we'll need to synthesize (unnamed)
10424 // parameters for use in the declaration.
10425 //
10426 // @code
10427 // typedef void fn(int);
10428 // fn f;
10429 // @endcode
10430
10431 // Synthesize a parameter for each argument type.
10432 for (const auto &AI : FT->param_types()) {
10433 ParmVarDecl *Param =
10434 BuildParmVarDeclForTypedef(DC: NewFD, Loc: D.getIdentifierLoc(), T: AI);
10435 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
10436 Params.push_back(Elt: Param);
10437 }
10438 } else {
10439 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10440 "Should not need args for typedef of non-prototype fn");
10441 }
10442
10443 // Finally, we know we have the right number of parameters, install them.
10444 NewFD->setParams(Params);
10445
10446 // If this declarator is a declaration and not a definition, its parameters
10447 // will not be pushed onto a scope chain. That means we will not issue any
10448 // reserved identifier warnings for the declaration, but we will for the
10449 // definition. Handle those here.
10450 if (!D.isFunctionDefinition()) {
10451 for (const ParmVarDecl *PVD : Params)
10452 warnOnReservedIdentifier(D: PVD);
10453 }
10454
10455 if (D.getDeclSpec().isNoreturnSpecified())
10456 NewFD->addAttr(
10457 A: C11NoReturnAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getNoreturnSpecLoc()));
10458
10459 // Functions returning a variably modified type violate C99 6.7.5.2p2
10460 // because all functions have linkage.
10461 if (!NewFD->isInvalidDecl() &&
10462 NewFD->getReturnType()->isVariablyModifiedType()) {
10463 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_vm_func_decl);
10464 NewFD->setInvalidDecl();
10465 }
10466
10467 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10468 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10469 !NewFD->hasAttr<SectionAttr>())
10470 NewFD->addAttr(A: PragmaClangTextSectionAttr::CreateImplicit(
10471 Ctx&: Context, Name: PragmaClangTextSection.SectionName,
10472 Range: PragmaClangTextSection.PragmaLocation));
10473
10474 // Apply an implicit SectionAttr if #pragma code_seg is active.
10475 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10476 !NewFD->hasAttr<SectionAttr>()) {
10477 NewFD->addAttr(A: SectionAttr::CreateImplicit(
10478 Ctx&: Context, Name: CodeSegStack.CurrentValue->getString(),
10479 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate));
10480 if (UnifySection(SectionName: CodeSegStack.CurrentValue->getString(),
10481 SectionFlags: ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10482 ASTContext::PSF_Read,
10483 TheDecl: NewFD))
10484 NewFD->dropAttr<SectionAttr>();
10485 }
10486
10487 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10488 // active.
10489 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10490 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10491 NewFD->addAttr(A: StrictGuardStackCheckAttr::CreateImplicit(
10492 Ctx&: Context, Range: PragmaClangTextSection.PragmaLocation));
10493
10494 // Apply an implicit CodeSegAttr from class declspec or
10495 // apply an implicit SectionAttr from #pragma code_seg if active.
10496 if (!NewFD->hasAttr<CodeSegAttr>()) {
10497 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(FD: NewFD,
10498 IsDefinition: D.isFunctionDefinition())) {
10499 NewFD->addAttr(A: SAttr);
10500 }
10501 }
10502
10503 // Handle attributes.
10504 ProcessDeclAttributes(S, D: NewFD, PD: D);
10505 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10506 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10507 !NewTVA->isDefaultVersion() &&
10508 !Context.getTargetInfo().hasFeature(Feature: "fmv")) {
10509 // Don't add to scope fmv functions declarations if fmv disabled
10510 AddToScope = false;
10511 return NewFD;
10512 }
10513
10514 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10515 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10516 // type.
10517 //
10518 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10519 // type declaration will generate a compilation error.
10520 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10521 if (AddressSpace != LangAS::Default) {
10522 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_return_value_with_address_space);
10523 NewFD->setInvalidDecl();
10524 }
10525 }
10526
10527 if (!getLangOpts().CPlusPlus) {
10528 // Perform semantic checking on the function declaration.
10529 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10530 CheckMain(FD: NewFD, D: D.getDeclSpec());
10531
10532 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10533 CheckMSVCRTEntryPoint(FD: NewFD);
10534
10535 if (!NewFD->isInvalidDecl())
10536 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10537 IsMemberSpecialization: isMemberSpecialization,
10538 DeclIsDefn: D.isFunctionDefinition()));
10539 else if (!Previous.empty())
10540 // Recover gracefully from an invalid redeclaration.
10541 D.setRedeclaration(true);
10542 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10543 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10544 "previous declaration set still overloaded");
10545
10546 // Diagnose no-prototype function declarations with calling conventions that
10547 // don't support variadic calls. Only do this in C and do it after merging
10548 // possibly prototyped redeclarations.
10549 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10550 if (isa<FunctionNoProtoType>(Val: FT) && !D.isFunctionDefinition()) {
10551 CallingConv CC = FT->getExtInfo().getCC();
10552 if (!supportsVariadicCall(CC)) {
10553 // Windows system headers sometimes accidentally use stdcall without
10554 // (void) parameters, so we relax this to a warning.
10555 int DiagID =
10556 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10557 Diag(Loc: NewFD->getLocation(), DiagID)
10558 << FunctionType::getNameForCallConv(CC);
10559 }
10560 }
10561
10562 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10563 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10564 checkNonTrivialCUnion(
10565 QT: NewFD->getReturnType(), Loc: NewFD->getReturnTypeSourceRange().getBegin(),
10566 UseContext: NonTrivialCUnionContext::FunctionReturn, NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
10567 } else {
10568 // C++11 [replacement.functions]p3:
10569 // The program's definitions shall not be specified as inline.
10570 //
10571 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10572 //
10573 // Suppress the diagnostic if the function is __attribute__((used)), since
10574 // that forces an external definition to be emitted.
10575 if (D.getDeclSpec().isInlineSpecified() &&
10576 NewFD->isReplaceableGlobalAllocationFunction() &&
10577 !NewFD->hasAttr<UsedAttr>())
10578 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10579 DiagID: diag::ext_operator_new_delete_declared_inline)
10580 << NewFD->getDeclName();
10581
10582 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10583 // C++20 [dcl.decl.general]p4:
10584 // The optional requires-clause in an init-declarator or
10585 // member-declarator shall be present only if the declarator declares a
10586 // templated function.
10587 //
10588 // C++20 [temp.pre]p8:
10589 // An entity is templated if it is
10590 // - a template,
10591 // - an entity defined or created in a templated entity,
10592 // - a member of a templated entity,
10593 // - an enumerator for an enumeration that is a templated entity, or
10594 // - the closure type of a lambda-expression appearing in the
10595 // declaration of a templated entity.
10596 //
10597 // [Note 6: A local class, a local or block variable, or a friend
10598 // function defined in a templated entity is a templated entity.
10599 // — end note]
10600 //
10601 // A templated function is a function template or a function that is
10602 // templated. A templated class is a class template or a class that is
10603 // templated. A templated variable is a variable template or a variable
10604 // that is templated.
10605 if (!FunctionTemplate) {
10606 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10607 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10608 // An explicit specialization shall not have a trailing
10609 // requires-clause unless it declares a function template.
10610 //
10611 // Since a friend function template specialization cannot be
10612 // definition, and since a non-template friend declaration with a
10613 // trailing requires-clause must be a definition, we diagnose
10614 // friend function template specializations with trailing
10615 // requires-clauses on the same path as explicit specializations
10616 // even though they aren't necessarily prohibited by the same
10617 // language rule.
10618 Diag(Loc: TRC->getBeginLoc(), DiagID: diag::err_non_temp_spec_requires_clause)
10619 << isFriend;
10620 } else if (isFriend && NewFD->isTemplated() &&
10621 !D.isFunctionDefinition()) {
10622 // C++ [temp.friend]p9:
10623 // A non-template friend declaration with a requires-clause shall be
10624 // a definition.
10625 Diag(Loc: NewFD->getBeginLoc(),
10626 DiagID: diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10627 NewFD->setInvalidDecl();
10628 } else if (!NewFD->isTemplated() ||
10629 !(isa<CXXMethodDecl>(Val: NewFD) || D.isFunctionDefinition())) {
10630 Diag(Loc: TRC->getBeginLoc(),
10631 DiagID: diag::err_constrained_non_templated_function);
10632 }
10633 }
10634 }
10635
10636 // We do not add HD attributes to specializations here because
10637 // they may have different constexpr-ness compared to their
10638 // templates and, after maybeAddHostDeviceAttrs() is applied,
10639 // may end up with different effective targets. Instead, a
10640 // specialization inherits its target attributes from its template
10641 // in the CheckFunctionTemplateSpecialization() call below.
10642 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10643 CUDA().maybeAddHostDeviceAttrs(FD: NewFD, Previous);
10644
10645 // Handle explicit specializations of function templates
10646 // and friend function declarations with an explicit
10647 // template argument list.
10648 if (isFunctionTemplateSpecialization) {
10649 bool isDependentSpecialization = false;
10650 if (isFriend) {
10651 // For friend function specializations, this is a dependent
10652 // specialization if its semantic context is dependent, its
10653 // type is dependent, or if its template-id is dependent.
10654 isDependentSpecialization =
10655 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10656 (HasExplicitTemplateArgs &&
10657 TemplateSpecializationType::
10658 anyInstantiationDependentTemplateArguments(
10659 Args: TemplateArgs.arguments()));
10660 assert((!isDependentSpecialization ||
10661 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10662 "dependent friend function specialization without template "
10663 "args");
10664 } else {
10665 // For class-scope explicit specializations of function templates,
10666 // if the lexical context is dependent, then the specialization
10667 // is dependent.
10668 isDependentSpecialization =
10669 CurContext->isRecord() && CurContext->isDependentContext();
10670 }
10671
10672 TemplateArgumentListInfo *ExplicitTemplateArgs =
10673 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10674 if (isDependentSpecialization) {
10675 // If it's a dependent specialization, it may not be possible
10676 // to determine the primary template (for explicit specializations)
10677 // or befriended declaration (for friends) until the enclosing
10678 // template is instantiated. In such cases, we store the declarations
10679 // found by name lookup and defer resolution until instantiation.
10680 if (CheckDependentFunctionTemplateSpecialization(
10681 FD: NewFD, ExplicitTemplateArgs, Previous))
10682 NewFD->setInvalidDecl();
10683 } else if (!NewFD->isInvalidDecl()) {
10684 if (CheckFunctionTemplateSpecialization(FD: NewFD, ExplicitTemplateArgs,
10685 Previous))
10686 NewFD->setInvalidDecl();
10687 }
10688 } else if (isMemberSpecialization && !FunctionTemplate) {
10689 if (CheckMemberSpecialization(Member: NewFD, Previous))
10690 NewFD->setInvalidDecl();
10691 }
10692
10693 // Perform semantic checking on the function declaration.
10694 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10695 CheckMain(FD: NewFD, D: D.getDeclSpec());
10696
10697 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10698 CheckMSVCRTEntryPoint(FD: NewFD);
10699
10700 if (!NewFD->isInvalidDecl())
10701 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10702 IsMemberSpecialization: isMemberSpecialization,
10703 DeclIsDefn: D.isFunctionDefinition()));
10704 else if (!Previous.empty())
10705 // Recover gracefully from an invalid redeclaration.
10706 D.setRedeclaration(true);
10707
10708 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10709 !D.isRedeclaration() ||
10710 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10711 "previous declaration set still overloaded");
10712
10713 NamedDecl *PrincipalDecl = (FunctionTemplate
10714 ? cast<NamedDecl>(Val: FunctionTemplate)
10715 : NewFD);
10716
10717 if (isFriend && NewFD->getPreviousDecl()) {
10718 AccessSpecifier Access = AS_public;
10719 if (!NewFD->isInvalidDecl())
10720 Access = NewFD->getPreviousDecl()->getAccess();
10721
10722 NewFD->setAccess(Access);
10723 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10724 }
10725
10726 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10727 PrincipalDecl->isInIdentifierNamespace(NS: Decl::IDNS_Ordinary))
10728 PrincipalDecl->setNonMemberOperator();
10729
10730 // If we have a function template, check the template parameter
10731 // list. This will check and merge default template arguments.
10732 if (FunctionTemplate) {
10733 FunctionTemplateDecl *PrevTemplate =
10734 FunctionTemplate->getPreviousDecl();
10735 CheckTemplateParameterList(NewParams: FunctionTemplate->getTemplateParameters(),
10736 OldParams: PrevTemplate ? PrevTemplate->getTemplateParameters()
10737 : nullptr,
10738 TPC: D.getDeclSpec().isFriendSpecified()
10739 ? (D.isFunctionDefinition()
10740 ? TPC_FriendFunctionTemplateDefinition
10741 : TPC_FriendFunctionTemplate)
10742 : (D.getCXXScopeSpec().isSet() &&
10743 DC && DC->isRecord() &&
10744 DC->isDependentContext())
10745 ? TPC_ClassTemplateMember
10746 : TPC_FunctionTemplate);
10747 }
10748
10749 if (NewFD->isInvalidDecl()) {
10750 // Ignore all the rest of this.
10751 } else if (!D.isRedeclaration()) {
10752 struct ActOnFDArgs ExtraArgs = { .S: S, .D: D, .TemplateParamLists: TemplateParamLists,
10753 .AddToScope: AddToScope };
10754 // Fake up an access specifier if it's supposed to be a class member.
10755 if (isa<CXXRecordDecl>(Val: NewFD->getDeclContext()))
10756 NewFD->setAccess(AS_public);
10757
10758 // Qualified decls generally require a previous declaration.
10759 if (D.getCXXScopeSpec().isSet()) {
10760 // ...with the major exception of templated-scope or
10761 // dependent-scope friend declarations.
10762
10763 // TODO: we currently also suppress this check in dependent
10764 // contexts because (1) the parameter depth will be off when
10765 // matching friend templates and (2) we might actually be
10766 // selecting a friend based on a dependent factor. But there
10767 // are situations where these conditions don't apply and we
10768 // can actually do this check immediately.
10769 //
10770 // Unless the scope is dependent, it's always an error if qualified
10771 // redeclaration lookup found nothing at all. Diagnose that now;
10772 // nothing will diagnose that error later.
10773 if (isFriend &&
10774 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10775 (!Previous.empty() && CurContext->isDependentContext()))) {
10776 // ignore these
10777 } else if (NewFD->isCPUDispatchMultiVersion() ||
10778 NewFD->isCPUSpecificMultiVersion()) {
10779 // ignore this, we allow the redeclaration behavior here to create new
10780 // versions of the function.
10781 } else {
10782 // The user tried to provide an out-of-line definition for a
10783 // function that is a member of a class or namespace, but there
10784 // was no such member function declared (C++ [class.mfct]p2,
10785 // C++ [namespace.memdef]p2). For example:
10786 //
10787 // class X {
10788 // void f() const;
10789 // };
10790 //
10791 // void X::f() { } // ill-formed
10792 //
10793 // Complain about this problem, and attempt to suggest close
10794 // matches (e.g., those that differ only in cv-qualifiers and
10795 // whether the parameter types are references).
10796
10797 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10798 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: false, S: nullptr)) {
10799 AddToScope = ExtraArgs.AddToScope;
10800 return Result;
10801 }
10802 }
10803
10804 // Unqualified local friend declarations are required to resolve
10805 // to something.
10806 } else if (isFriend && cast<CXXRecordDecl>(Val: CurContext)->isLocalClass()) {
10807 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10808 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: true, S)) {
10809 AddToScope = ExtraArgs.AddToScope;
10810 return Result;
10811 }
10812 }
10813 } else if (!D.isFunctionDefinition() &&
10814 isa<CXXMethodDecl>(Val: NewFD) && NewFD->isOutOfLine() &&
10815 !isFriend && !isFunctionTemplateSpecialization &&
10816 !isMemberSpecialization) {
10817 // An out-of-line member function declaration must also be a
10818 // definition (C++ [class.mfct]p2).
10819 // Note that this is not the case for explicit specializations of
10820 // function templates or member functions of class templates, per
10821 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10822 // extension for compatibility with old SWIG code which likes to
10823 // generate them.
10824 Diag(Loc: NewFD->getLocation(), DiagID: diag::ext_out_of_line_declaration)
10825 << D.getCXXScopeSpec().getRange();
10826 }
10827 }
10828
10829 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10830 // Any top level function could potentially be specified as an entry.
10831 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10832 HLSL().ActOnTopLevelFunction(FD: NewFD);
10833
10834 if (NewFD->hasAttr<HLSLShaderAttr>())
10835 HLSL().CheckEntryPoint(FD: NewFD);
10836 }
10837
10838 // If this is the first declaration of a library builtin function, add
10839 // attributes as appropriate.
10840 if (!D.isRedeclaration()) {
10841 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10842 if (unsigned BuiltinID = II->getBuiltinID()) {
10843 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID);
10844 if (!InStdNamespace &&
10845 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10846 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10847 // Validate the type matches unless this builtin is specified as
10848 // matching regardless of its declared type.
10849 if (Context.BuiltinInfo.allowTypeMismatch(ID: BuiltinID)) {
10850 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
10851 } else {
10852 ASTContext::GetBuiltinTypeError Error;
10853 LookupNecessaryTypesForBuiltin(S, ID: BuiltinID);
10854 QualType BuiltinType = Context.GetBuiltinType(ID: BuiltinID, Error);
10855
10856 if (!Error && !BuiltinType.isNull() &&
10857 Context.hasSameFunctionTypeIgnoringExceptionSpec(
10858 T: NewFD->getType(), U: BuiltinType))
10859 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
10860 }
10861 }
10862 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10863 isStdBuiltin(Ctx&: Context, FD: NewFD, BuiltinID)) {
10864 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
10865 }
10866 }
10867 }
10868 }
10869
10870 ProcessPragmaWeak(S, D: NewFD);
10871 checkAttributesAfterMerging(S&: *this, ND&: *NewFD);
10872
10873 AddKnownFunctionAttributes(FD: NewFD);
10874
10875 if (NewFD->hasAttr<OverloadableAttr>() &&
10876 !NewFD->getType()->getAs<FunctionProtoType>()) {
10877 Diag(Loc: NewFD->getLocation(),
10878 DiagID: diag::err_attribute_overloadable_no_prototype)
10879 << NewFD;
10880 NewFD->dropAttr<OverloadableAttr>();
10881 }
10882
10883 // If there's a #pragma GCC visibility in scope, and this isn't a class
10884 // member, set the visibility of this function.
10885 if (!DC->isRecord() && NewFD->isExternallyVisible())
10886 AddPushedVisibilityAttribute(RD: NewFD);
10887
10888 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10889 // marking the function.
10890 ObjC().AddCFAuditedAttribute(D: NewFD);
10891
10892 // If this is a function definition, check if we have to apply any
10893 // attributes (i.e. optnone and no_builtin) due to a pragma.
10894 if (D.isFunctionDefinition()) {
10895 AddRangeBasedOptnone(FD: NewFD);
10896 AddImplicitMSFunctionNoBuiltinAttr(FD: NewFD);
10897 AddSectionMSAllocText(FD: NewFD);
10898 ModifyFnAttributesMSPragmaOptimize(FD: NewFD);
10899 }
10900
10901 // If this is the first declaration of an extern C variable, update
10902 // the map of such variables.
10903 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10904 isIncompleteDeclExternC(S&: *this, D: NewFD))
10905 RegisterLocallyScopedExternCDecl(ND: NewFD, S);
10906
10907 // Set this FunctionDecl's range up to the right paren.
10908 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10909
10910 if (D.isRedeclaration() && !Previous.empty()) {
10911 NamedDecl *Prev = Previous.getRepresentativeDecl();
10912 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewFD,
10913 IsSpecialization: isMemberSpecialization ||
10914 isFunctionTemplateSpecialization,
10915 IsDefinition: D.isFunctionDefinition());
10916 }
10917
10918 if (getLangOpts().CUDA) {
10919 IdentifierInfo *II = NewFD->getIdentifier();
10920 if (II && II->isStr(Str: CUDA().getConfigureFuncName()) &&
10921 !NewFD->isInvalidDecl() &&
10922 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10923 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10924 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
10925 << CUDA().getConfigureFuncName();
10926 Context.setcudaConfigureCallDecl(NewFD);
10927 }
10928
10929 // Variadic functions, other than a *declaration* of printf, are not allowed
10930 // in device-side CUDA code, unless someone passed
10931 // -fcuda-allow-variadic-functions.
10932 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10933 (NewFD->hasAttr<CUDADeviceAttr>() ||
10934 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10935 !(II && II->isStr(Str: "printf") && NewFD->isExternC() &&
10936 !D.isFunctionDefinition())) {
10937 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_variadic_device_fn);
10938 }
10939 }
10940
10941 MarkUnusedFileScopedDecl(D: NewFD);
10942
10943 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
10944 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10945 if (SC == SC_Static) {
10946 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_static_kernel);
10947 D.setInvalidType();
10948 }
10949
10950 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10951 if (!NewFD->getReturnType()->isVoidType()) {
10952 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10953 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_expected_kernel_void_return_type)
10954 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "void")
10955 : FixItHint());
10956 D.setInvalidType();
10957 }
10958
10959 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10960 for (auto *Param : NewFD->parameters())
10961 checkIsValidOpenCLKernelParameter(S&: *this, D, Param, ValidTypes);
10962
10963 if (getLangOpts().OpenCLCPlusPlus) {
10964 if (DC->isRecord()) {
10965 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_method_kernel);
10966 D.setInvalidType();
10967 }
10968 if (FunctionTemplate) {
10969 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_kernel);
10970 D.setInvalidType();
10971 }
10972 }
10973 }
10974
10975 if (getLangOpts().CPlusPlus) {
10976 // Precalculate whether this is a friend function template with a constraint
10977 // that depends on an enclosing template, per [temp.friend]p9.
10978 if (isFriend && FunctionTemplate &&
10979 FriendConstraintsDependOnEnclosingTemplate(FD: NewFD)) {
10980 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
10981
10982 // C++ [temp.friend]p9:
10983 // A friend function template with a constraint that depends on a
10984 // template parameter from an enclosing template shall be a definition.
10985 if (!D.isFunctionDefinition()) {
10986 Diag(Loc: NewFD->getBeginLoc(),
10987 DiagID: diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
10988 NewFD->setInvalidDecl();
10989 }
10990 }
10991
10992 if (FunctionTemplate) {
10993 if (NewFD->isInvalidDecl())
10994 FunctionTemplate->setInvalidDecl();
10995 return FunctionTemplate;
10996 }
10997
10998 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10999 CompleteMemberSpecialization(Member: NewFD, Previous);
11000 }
11001
11002 for (const ParmVarDecl *Param : NewFD->parameters()) {
11003 QualType PT = Param->getType();
11004
11005 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11006 // types.
11007 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11008 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11009 QualType ElemTy = PipeTy->getElementType();
11010 if (ElemTy->isPointerOrReferenceType()) {
11011 Diag(Loc: Param->getTypeSpecStartLoc(), DiagID: diag::err_reference_pipe_type);
11012 D.setInvalidType();
11013 }
11014 }
11015 }
11016 // WebAssembly tables can't be used as function parameters.
11017 if (Context.getTargetInfo().getTriple().isWasm()) {
11018 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
11019 Diag(Loc: Param->getTypeSpecStartLoc(),
11020 DiagID: diag::err_wasm_table_as_function_parameter);
11021 D.setInvalidType();
11022 }
11023 }
11024 }
11025
11026 // Diagnose availability attributes. Availability cannot be used on functions
11027 // that are run during load/unload.
11028 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11029 if (NewFD->hasAttr<ConstructorAttr>()) {
11030 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11031 << 1;
11032 NewFD->dropAttr<AvailabilityAttr>();
11033 }
11034 if (NewFD->hasAttr<DestructorAttr>()) {
11035 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11036 << 2;
11037 NewFD->dropAttr<AvailabilityAttr>();
11038 }
11039 }
11040
11041 // Diagnose no_builtin attribute on function declaration that are not a
11042 // definition.
11043 // FIXME: We should really be doing this in
11044 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11045 // the FunctionDecl and at this point of the code
11046 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11047 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11048 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11049 switch (D.getFunctionDefinitionKind()) {
11050 case FunctionDefinitionKind::Defaulted:
11051 case FunctionDefinitionKind::Deleted:
11052 Diag(Loc: NBA->getLocation(),
11053 DiagID: diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11054 << NBA->getSpelling();
11055 break;
11056 case FunctionDefinitionKind::Declaration:
11057 Diag(Loc: NBA->getLocation(), DiagID: diag::err_attribute_no_builtin_on_non_definition)
11058 << NBA->getSpelling();
11059 break;
11060 case FunctionDefinitionKind::Definition:
11061 break;
11062 }
11063
11064 // Similar to no_builtin logic above, at this point of the code
11065 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11066 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11067 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11068 !NewFD->isInvalidDecl() &&
11069 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
11070 ExternalDeclarations.push_back(Elt: NewFD);
11071
11072 // Used for a warning on the 'next' declaration when used with a
11073 // `routine(name)`.
11074 if (getLangOpts().OpenACC)
11075 OpenACC().ActOnFunctionDeclarator(FD: NewFD);
11076
11077 return NewFD;
11078}
11079
11080/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11081/// when __declspec(code_seg) "is applied to a class, all member functions of
11082/// the class and nested classes -- this includes compiler-generated special
11083/// member functions -- are put in the specified segment."
11084/// The actual behavior is a little more complicated. The Microsoft compiler
11085/// won't check outer classes if there is an active value from #pragma code_seg.
11086/// The CodeSeg is always applied from the direct parent but only from outer
11087/// classes when the #pragma code_seg stack is empty. See:
11088/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11089/// available since MS has removed the page.
11090static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
11091 const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
11092 if (!Method)
11093 return nullptr;
11094 const CXXRecordDecl *Parent = Method->getParent();
11095 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11096 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11097 NewAttr->setImplicit(true);
11098 return NewAttr;
11099 }
11100
11101 // The Microsoft compiler won't check outer classes for the CodeSeg
11102 // when the #pragma code_seg stack is active.
11103 if (S.CodeSegStack.CurrentValue)
11104 return nullptr;
11105
11106 while ((Parent = dyn_cast<CXXRecordDecl>(Val: Parent->getParent()))) {
11107 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11108 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11109 NewAttr->setImplicit(true);
11110 return NewAttr;
11111 }
11112 }
11113 return nullptr;
11114}
11115
11116Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
11117 bool IsDefinition) {
11118 if (Attr *A = getImplicitCodeSegAttrFromClass(S&: *this, FD))
11119 return A;
11120 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11121 CodeSegStack.CurrentValue)
11122 return SectionAttr::CreateImplicit(
11123 Ctx&: getASTContext(), Name: CodeSegStack.CurrentValue->getString(),
11124 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate);
11125 return nullptr;
11126}
11127
11128bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
11129 QualType NewT, QualType OldT) {
11130 if (!NewD->getLexicalDeclContext()->isDependentContext())
11131 return true;
11132
11133 // For dependently-typed local extern declarations and friends, we can't
11134 // perform a correct type check in general until instantiation:
11135 //
11136 // int f();
11137 // template<typename T> void g() { T f(); }
11138 //
11139 // (valid if g() is only instantiated with T = int).
11140 if (NewT->isDependentType() &&
11141 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11142 return false;
11143
11144 // Similarly, if the previous declaration was a dependent local extern
11145 // declaration, we don't really know its type yet.
11146 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11147 return false;
11148
11149 return true;
11150}
11151
11152bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11153 if (!D->getLexicalDeclContext()->isDependentContext())
11154 return true;
11155
11156 // Don't chain dependent friend function definitions until instantiation, to
11157 // permit cases like
11158 //
11159 // void func();
11160 // template<typename T> class C1 { friend void func() {} };
11161 // template<typename T> class C2 { friend void func() {} };
11162 //
11163 // ... which is valid if only one of C1 and C2 is ever instantiated.
11164 //
11165 // FIXME: This need only apply to function definitions. For now, we proxy
11166 // this by checking for a file-scope function. We do not want this to apply
11167 // to friend declarations nominating member functions, because that gets in
11168 // the way of access checks.
11169 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11170 return false;
11171
11172 auto *VD = dyn_cast<ValueDecl>(Val: D);
11173 auto *PrevVD = dyn_cast<ValueDecl>(Val: PrevDecl);
11174 return !VD || !PrevVD ||
11175 canFullyTypeCheckRedeclaration(NewD: VD, OldD: PrevVD, NewT: VD->getType(),
11176 OldT: PrevVD->getType());
11177}
11178
11179/// Check the target or target_version attribute of the function for
11180/// MultiVersion validity.
11181///
11182/// Returns true if there was an error, false otherwise.
11183static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11184 const auto *TA = FD->getAttr<TargetAttr>();
11185 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11186
11187 assert((TA || TVA) && "Expecting target or target_version attribute");
11188
11189 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11190 enum ErrType { Feature = 0, Architecture = 1 };
11191
11192 if (TA) {
11193 ParsedTargetAttr ParseInfo =
11194 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TA->getFeaturesStr());
11195 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(Name: ParseInfo.CPU)) {
11196 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11197 << Architecture << ParseInfo.CPU;
11198 return true;
11199 }
11200 for (const auto &Feat : ParseInfo.Features) {
11201 auto BareFeat = StringRef{Feat}.substr(Start: 1);
11202 if (Feat[0] == '-') {
11203 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11204 << Feature << ("no-" + BareFeat).str();
11205 return true;
11206 }
11207
11208 if (!TargetInfo.validateCpuSupports(Name: BareFeat) ||
11209 !TargetInfo.isValidFeatureName(Feature: BareFeat) ||
11210 (BareFeat != "default" && TargetInfo.getFMVPriority(Features: BareFeat) == 0)) {
11211 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11212 << Feature << BareFeat;
11213 return true;
11214 }
11215 }
11216 }
11217
11218 if (TVA) {
11219 llvm::SmallVector<StringRef, 8> Feats;
11220 ParsedTargetAttr ParseInfo;
11221 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11222 ParseInfo =
11223 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TVA->getName());
11224 for (auto &Feat : ParseInfo.Features)
11225 Feats.push_back(Elt: StringRef{Feat}.substr(Start: 1));
11226 } else {
11227 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11228 TVA->getFeatures(Out&: Feats);
11229 }
11230 for (const auto &Feat : Feats) {
11231 if (!TargetInfo.validateCpuSupports(Name: Feat)) {
11232 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11233 << Feature << Feat;
11234 return true;
11235 }
11236 }
11237 }
11238 return false;
11239}
11240
11241// Provide a white-list of attributes that are allowed to be combined with
11242// multiversion functions.
11243static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11244 MultiVersionKind MVKind) {
11245 // Note: this list/diagnosis must match the list in
11246 // checkMultiversionAttributesAllSame.
11247 switch (Kind) {
11248 default:
11249 return false;
11250 case attr::ArmLocallyStreaming:
11251 return MVKind == MultiVersionKind::TargetVersion ||
11252 MVKind == MultiVersionKind::TargetClones;
11253 case attr::Used:
11254 return MVKind == MultiVersionKind::Target;
11255 case attr::NonNull:
11256 case attr::NoThrow:
11257 return true;
11258 }
11259}
11260
11261static bool checkNonMultiVersionCompatAttributes(Sema &S,
11262 const FunctionDecl *FD,
11263 const FunctionDecl *CausedFD,
11264 MultiVersionKind MVKind) {
11265 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11266 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_disallowed_other_attr)
11267 << static_cast<unsigned>(MVKind) << A;
11268 if (CausedFD)
11269 S.Diag(Loc: CausedFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11270 return true;
11271 };
11272
11273 for (const Attr *A : FD->attrs()) {
11274 switch (A->getKind()) {
11275 case attr::CPUDispatch:
11276 case attr::CPUSpecific:
11277 if (MVKind != MultiVersionKind::CPUDispatch &&
11278 MVKind != MultiVersionKind::CPUSpecific)
11279 return Diagnose(S, A);
11280 break;
11281 case attr::Target:
11282 if (MVKind != MultiVersionKind::Target)
11283 return Diagnose(S, A);
11284 break;
11285 case attr::TargetVersion:
11286 if (MVKind != MultiVersionKind::TargetVersion &&
11287 MVKind != MultiVersionKind::TargetClones)
11288 return Diagnose(S, A);
11289 break;
11290 case attr::TargetClones:
11291 if (MVKind != MultiVersionKind::TargetClones &&
11292 MVKind != MultiVersionKind::TargetVersion)
11293 return Diagnose(S, A);
11294 break;
11295 default:
11296 if (!AttrCompatibleWithMultiVersion(Kind: A->getKind(), MVKind))
11297 return Diagnose(S, A);
11298 break;
11299 }
11300 }
11301 return false;
11302}
11303
11304bool Sema::areMultiversionVariantFunctionsCompatible(
11305 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11306 const PartialDiagnostic &NoProtoDiagID,
11307 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11308 const PartialDiagnosticAt &NoSupportDiagIDAt,
11309 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11310 bool ConstexprSupported, bool CLinkageMayDiffer) {
11311 enum DoesntSupport {
11312 FuncTemplates = 0,
11313 VirtFuncs = 1,
11314 DeducedReturn = 2,
11315 Constructors = 3,
11316 Destructors = 4,
11317 DeletedFuncs = 5,
11318 DefaultedFuncs = 6,
11319 ConstexprFuncs = 7,
11320 ConstevalFuncs = 8,
11321 Lambda = 9,
11322 };
11323 enum Different {
11324 CallingConv = 0,
11325 ReturnType = 1,
11326 ConstexprSpec = 2,
11327 InlineSpec = 3,
11328 Linkage = 4,
11329 LanguageLinkage = 5,
11330 };
11331
11332 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11333 !OldFD->getType()->getAs<FunctionProtoType>()) {
11334 Diag(Loc: OldFD->getLocation(), PD: NoProtoDiagID);
11335 Diag(Loc: NoteCausedDiagIDAt.first, PD: NoteCausedDiagIDAt.second);
11336 return true;
11337 }
11338
11339 if (NoProtoDiagID.getDiagID() != 0 &&
11340 !NewFD->getType()->getAs<FunctionProtoType>())
11341 return Diag(Loc: NewFD->getLocation(), PD: NoProtoDiagID);
11342
11343 if (!TemplatesSupported &&
11344 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11345 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11346 << FuncTemplates;
11347
11348 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
11349 if (NewCXXFD->isVirtual())
11350 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11351 << VirtFuncs;
11352
11353 if (isa<CXXConstructorDecl>(Val: NewCXXFD))
11354 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11355 << Constructors;
11356
11357 if (isa<CXXDestructorDecl>(Val: NewCXXFD))
11358 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11359 << Destructors;
11360 }
11361
11362 if (NewFD->isDeleted())
11363 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11364 << DeletedFuncs;
11365
11366 if (NewFD->isDefaulted())
11367 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11368 << DefaultedFuncs;
11369
11370 if (!ConstexprSupported && NewFD->isConstexpr())
11371 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11372 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11373
11374 QualType NewQType = Context.getCanonicalType(T: NewFD->getType());
11375 const auto *NewType = cast<FunctionType>(Val&: NewQType);
11376 QualType NewReturnType = NewType->getReturnType();
11377
11378 if (NewReturnType->isUndeducedType())
11379 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11380 << DeducedReturn;
11381
11382 // Ensure the return type is identical.
11383 if (OldFD) {
11384 QualType OldQType = Context.getCanonicalType(T: OldFD->getType());
11385 const auto *OldType = cast<FunctionType>(Val&: OldQType);
11386 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11387 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11388
11389 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11390 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11391
11392 bool ArmStreamingCCMismatched = false;
11393 if (OldFPT && NewFPT) {
11394 unsigned Diff =
11395 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11396 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11397 // cannot be mixed.
11398 if (Diff & (FunctionType::SME_PStateSMEnabledMask |
11399 FunctionType::SME_PStateSMCompatibleMask))
11400 ArmStreamingCCMismatched = true;
11401 }
11402
11403 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11404 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << CallingConv;
11405
11406 QualType OldReturnType = OldType->getReturnType();
11407
11408 if (OldReturnType != NewReturnType)
11409 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ReturnType;
11410
11411 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11412 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ConstexprSpec;
11413
11414 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11415 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << InlineSpec;
11416
11417 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11418 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << Linkage;
11419
11420 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11421 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << LanguageLinkage;
11422
11423 if (CheckEquivalentExceptionSpec(Old: OldFPT, OldLoc: OldFD->getLocation(), New: NewFPT,
11424 NewLoc: NewFD->getLocation()))
11425 return true;
11426 }
11427 return false;
11428}
11429
11430static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11431 const FunctionDecl *NewFD,
11432 bool CausesMV,
11433 MultiVersionKind MVKind) {
11434 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11435 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_supported);
11436 if (OldFD)
11437 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11438 return true;
11439 }
11440
11441 bool IsCPUSpecificCPUDispatchMVKind =
11442 MVKind == MultiVersionKind::CPUDispatch ||
11443 MVKind == MultiVersionKind::CPUSpecific;
11444
11445 if (CausesMV && OldFD &&
11446 checkNonMultiVersionCompatAttributes(S, FD: OldFD, CausedFD: NewFD, MVKind))
11447 return true;
11448
11449 if (checkNonMultiVersionCompatAttributes(S, FD: NewFD, CausedFD: nullptr, MVKind))
11450 return true;
11451
11452 // Only allow transition to MultiVersion if it hasn't been used.
11453 if (OldFD && CausesMV && OldFD->isUsed(CheckUsedAttr: false)) {
11454 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
11455 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11456 return true;
11457 }
11458
11459 return S.areMultiversionVariantFunctionsCompatible(
11460 OldFD, NewFD, NoProtoDiagID: S.PDiag(DiagID: diag::err_multiversion_noproto),
11461 NoteCausedDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11462 S.PDiag(DiagID: diag::note_multiversioning_caused_here)),
11463 NoSupportDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11464 S.PDiag(DiagID: diag::err_multiversion_doesnt_support)
11465 << static_cast<unsigned>(MVKind)),
11466 DiffDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11467 S.PDiag(DiagID: diag::err_multiversion_diff)),
11468 /*TemplatesSupported=*/false,
11469 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11470 /*CLinkageMayDiffer=*/false);
11471}
11472
11473/// Check the validity of a multiversion function declaration that is the
11474/// first of its kind. Also sets the multiversion'ness' of the function itself.
11475///
11476/// This sets NewFD->isInvalidDecl() to true if there was an error.
11477///
11478/// Returns true if there was an error, false otherwise.
11479static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11480 MultiVersionKind MVKind = FD->getMultiVersionKind();
11481 assert(MVKind != MultiVersionKind::None &&
11482 "Function lacks multiversion attribute");
11483 const auto *TA = FD->getAttr<TargetAttr>();
11484 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11485 // The target attribute only causes MV if this declaration is the default,
11486 // otherwise it is treated as a normal function.
11487 if (TA && !TA->isDefaultVersion())
11488 return false;
11489
11490 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11491 FD->setInvalidDecl();
11492 return true;
11493 }
11494
11495 if (CheckMultiVersionAdditionalRules(S, OldFD: nullptr, NewFD: FD, CausesMV: true, MVKind)) {
11496 FD->setInvalidDecl();
11497 return true;
11498 }
11499
11500 FD->setIsMultiVersion();
11501 return false;
11502}
11503
11504static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11505 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11506 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11507 return true;
11508 }
11509
11510 return false;
11511}
11512
11513static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
11514 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11515 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11516 return;
11517
11518 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11519 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11520
11521 if (MVKindTo == MultiVersionKind::None &&
11522 (MVKindFrom == MultiVersionKind::TargetVersion ||
11523 MVKindFrom == MultiVersionKind::TargetClones))
11524 To->addAttr(A: TargetVersionAttr::CreateImplicit(
11525 Ctx&: To->getASTContext(), NamesStr: "default", Range: To->getSourceRange()));
11526}
11527
11528static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11529 FunctionDecl *NewFD,
11530 bool &Redeclaration,
11531 NamedDecl *&OldDecl,
11532 LookupResult &Previous) {
11533 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11534
11535 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11536 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11537 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11538 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11539
11540 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11541
11542 // The definitions should be allowed in any order. If we have discovered
11543 // a new target version and the preceeding was the default, then add the
11544 // corresponding attribute to it.
11545 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11546
11547 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11548 // to change, this is a simple redeclaration.
11549 if (NewTA && !NewTA->isDefaultVersion() &&
11550 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11551 return false;
11552
11553 // Otherwise, this decl causes MultiVersioning.
11554 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, CausesMV: true,
11555 MVKind: NewTVA ? MultiVersionKind::TargetVersion
11556 : MultiVersionKind::Target)) {
11557 NewFD->setInvalidDecl();
11558 return true;
11559 }
11560
11561 if (CheckMultiVersionValue(S, FD: NewFD)) {
11562 NewFD->setInvalidDecl();
11563 return true;
11564 }
11565
11566 // If this is 'default', permit the forward declaration.
11567 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11568 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11569 Redeclaration = true;
11570 OldDecl = OldFD;
11571 OldFD->setIsMultiVersion();
11572 NewFD->setIsMultiVersion();
11573 return false;
11574 }
11575
11576 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, FD: OldFD)) {
11577 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11578 NewFD->setInvalidDecl();
11579 return true;
11580 }
11581
11582 if (NewTA) {
11583 ParsedTargetAttr OldParsed =
11584 S.getASTContext().getTargetInfo().parseTargetAttr(
11585 Str: OldTA->getFeaturesStr());
11586 llvm::sort(C&: OldParsed.Features);
11587 ParsedTargetAttr NewParsed =
11588 S.getASTContext().getTargetInfo().parseTargetAttr(
11589 Str: NewTA->getFeaturesStr());
11590 // Sort order doesn't matter, it just needs to be consistent.
11591 llvm::sort(C&: NewParsed.Features);
11592 if (OldParsed == NewParsed) {
11593 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11594 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11595 NewFD->setInvalidDecl();
11596 return true;
11597 }
11598 }
11599
11600 for (const auto *FD : OldFD->redecls()) {
11601 const auto *CurTA = FD->getAttr<TargetAttr>();
11602 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11603 // We allow forward declarations before ANY multiversioning attributes, but
11604 // nothing after the fact.
11605 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11606 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11607 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11608 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
11609 << (NewTA ? 0 : 2);
11610 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11611 NewFD->setInvalidDecl();
11612 return true;
11613 }
11614 }
11615
11616 OldFD->setIsMultiVersion();
11617 NewFD->setIsMultiVersion();
11618 Redeclaration = false;
11619 OldDecl = nullptr;
11620 Previous.clear();
11621 return false;
11622}
11623
11624static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {
11625 MultiVersionKind OldKind = Old->getMultiVersionKind();
11626 MultiVersionKind NewKind = New->getMultiVersionKind();
11627
11628 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11629 NewKind == MultiVersionKind::None)
11630 return true;
11631
11632 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11633 switch (OldKind) {
11634 case MultiVersionKind::TargetVersion:
11635 return NewKind == MultiVersionKind::TargetClones;
11636 case MultiVersionKind::TargetClones:
11637 return NewKind == MultiVersionKind::TargetVersion;
11638 default:
11639 return false;
11640 }
11641 } else {
11642 switch (OldKind) {
11643 case MultiVersionKind::CPUDispatch:
11644 return NewKind == MultiVersionKind::CPUSpecific;
11645 case MultiVersionKind::CPUSpecific:
11646 return NewKind == MultiVersionKind::CPUDispatch;
11647 default:
11648 return false;
11649 }
11650 }
11651}
11652
11653/// Check the validity of a new function declaration being added to an existing
11654/// multiversioned declaration collection.
11655static bool CheckMultiVersionAdditionalDecl(
11656 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11657 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11658 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11659 LookupResult &Previous) {
11660
11661 // Disallow mixing of multiversioning types.
11662 if (!MultiVersionTypesCompatible(Old: OldFD, New: NewFD)) {
11663 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_types_mixed);
11664 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11665 NewFD->setInvalidDecl();
11666 return true;
11667 }
11668
11669 // Add the default target_version attribute if it's missing.
11670 patchDefaultTargetVersion(From: OldFD, To: NewFD);
11671 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11672
11673 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11674 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11675 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11676 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11677
11678 ParsedTargetAttr NewParsed;
11679 if (NewTA) {
11680 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11681 Str: NewTA->getFeaturesStr());
11682 llvm::sort(C&: NewParsed.Features);
11683 }
11684 llvm::SmallVector<StringRef, 8> NewFeats;
11685 if (NewTVA) {
11686 NewTVA->getFeatures(Out&: NewFeats);
11687 llvm::sort(C&: NewFeats);
11688 }
11689
11690 bool UseMemberUsingDeclRules =
11691 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11692
11693 bool MayNeedOverloadableChecks =
11694 AllowOverloadingOfFunction(Previous, Context&: S.Context, New: NewFD);
11695
11696 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11697 // of a previous member of the MultiVersion set.
11698 for (NamedDecl *ND : Previous) {
11699 FunctionDecl *CurFD = ND->getAsFunction();
11700 if (!CurFD || CurFD->isInvalidDecl())
11701 continue;
11702 if (MayNeedOverloadableChecks &&
11703 S.IsOverload(New: NewFD, Old: CurFD, UseMemberUsingDeclRules))
11704 continue;
11705
11706 switch (NewMVKind) {
11707 case MultiVersionKind::None:
11708 assert(OldMVKind == MultiVersionKind::TargetClones &&
11709 "Only target_clones can be omitted in subsequent declarations");
11710 break;
11711 case MultiVersionKind::Target: {
11712 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11713 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11714 NewFD->setIsMultiVersion();
11715 Redeclaration = true;
11716 OldDecl = ND;
11717 return false;
11718 }
11719
11720 ParsedTargetAttr CurParsed =
11721 S.getASTContext().getTargetInfo().parseTargetAttr(
11722 Str: CurTA->getFeaturesStr());
11723 llvm::sort(C&: CurParsed.Features);
11724 if (CurParsed == NewParsed) {
11725 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11726 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11727 NewFD->setInvalidDecl();
11728 return true;
11729 }
11730 break;
11731 }
11732 case MultiVersionKind::TargetVersion: {
11733 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11734 if (CurTVA->getName() == NewTVA->getName()) {
11735 NewFD->setIsMultiVersion();
11736 Redeclaration = true;
11737 OldDecl = ND;
11738 return false;
11739 }
11740 llvm::SmallVector<StringRef, 8> CurFeats;
11741 CurTVA->getFeatures(Out&: CurFeats);
11742 llvm::sort(C&: CurFeats);
11743
11744 if (CurFeats == NewFeats) {
11745 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11746 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11747 NewFD->setInvalidDecl();
11748 return true;
11749 }
11750 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11751 // Default
11752 if (NewFeats.empty())
11753 break;
11754
11755 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11756 llvm::SmallVector<StringRef, 8> CurFeats;
11757 CurClones->getFeatures(Out&: CurFeats, Index: I);
11758 llvm::sort(C&: CurFeats);
11759
11760 if (CurFeats == NewFeats) {
11761 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11762 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11763 NewFD->setInvalidDecl();
11764 return true;
11765 }
11766 }
11767 }
11768 break;
11769 }
11770 case MultiVersionKind::TargetClones: {
11771 assert(NewClones && "MultiVersionKind does not match attribute type");
11772 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11773 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11774 !std::equal(first1: CurClones->featuresStrs_begin(),
11775 last1: CurClones->featuresStrs_end(),
11776 first2: NewClones->featuresStrs_begin())) {
11777 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_target_clone_doesnt_match);
11778 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11779 NewFD->setInvalidDecl();
11780 return true;
11781 }
11782 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11783 llvm::SmallVector<StringRef, 8> CurFeats;
11784 CurTVA->getFeatures(Out&: CurFeats);
11785 llvm::sort(C&: CurFeats);
11786
11787 // Default
11788 if (CurFeats.empty())
11789 break;
11790
11791 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11792 NewFeats.clear();
11793 NewClones->getFeatures(Out&: NewFeats, Index: I);
11794 llvm::sort(C&: NewFeats);
11795
11796 if (CurFeats == NewFeats) {
11797 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11798 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11799 NewFD->setInvalidDecl();
11800 return true;
11801 }
11802 }
11803 break;
11804 }
11805 Redeclaration = true;
11806 OldDecl = CurFD;
11807 NewFD->setIsMultiVersion();
11808 return false;
11809 }
11810 case MultiVersionKind::CPUSpecific:
11811 case MultiVersionKind::CPUDispatch: {
11812 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11813 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11814 // Handle CPUDispatch/CPUSpecific versions.
11815 // Only 1 CPUDispatch function is allowed, this will make it go through
11816 // the redeclaration errors.
11817 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11818 CurFD->hasAttr<CPUDispatchAttr>()) {
11819 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11820 std::equal(
11821 first1: CurCPUDisp->cpus_begin(), last1: CurCPUDisp->cpus_end(),
11822 first2: NewCPUDisp->cpus_begin(),
11823 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11824 return Cur->getName() == New->getName();
11825 })) {
11826 NewFD->setIsMultiVersion();
11827 Redeclaration = true;
11828 OldDecl = ND;
11829 return false;
11830 }
11831
11832 // If the declarations don't match, this is an error condition.
11833 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_dispatch_mismatch);
11834 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11835 NewFD->setInvalidDecl();
11836 return true;
11837 }
11838 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11839 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11840 std::equal(
11841 first1: CurCPUSpec->cpus_begin(), last1: CurCPUSpec->cpus_end(),
11842 first2: NewCPUSpec->cpus_begin(),
11843 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11844 return Cur->getName() == New->getName();
11845 })) {
11846 NewFD->setIsMultiVersion();
11847 Redeclaration = true;
11848 OldDecl = ND;
11849 return false;
11850 }
11851
11852 // Only 1 version of CPUSpecific is allowed for each CPU.
11853 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11854 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11855 if (CurII == NewII) {
11856 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_specific_multiple_defs)
11857 << NewII;
11858 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11859 NewFD->setInvalidDecl();
11860 return true;
11861 }
11862 }
11863 }
11864 }
11865 break;
11866 }
11867 }
11868 }
11869
11870 // Else, this is simply a non-redecl case. Checking the 'value' is only
11871 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11872 // handled in the attribute adding step.
11873 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, FD: NewFD)) {
11874 NewFD->setInvalidDecl();
11875 return true;
11876 }
11877
11878 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11879 CausesMV: !OldFD->isMultiVersion(), MVKind: NewMVKind)) {
11880 NewFD->setInvalidDecl();
11881 return true;
11882 }
11883
11884 // Permit forward declarations in the case where these two are compatible.
11885 if (!OldFD->isMultiVersion()) {
11886 OldFD->setIsMultiVersion();
11887 NewFD->setIsMultiVersion();
11888 Redeclaration = true;
11889 OldDecl = OldFD;
11890 return false;
11891 }
11892
11893 NewFD->setIsMultiVersion();
11894 Redeclaration = false;
11895 OldDecl = nullptr;
11896 Previous.clear();
11897 return false;
11898}
11899
11900/// Check the validity of a mulitversion function declaration.
11901/// Also sets the multiversion'ness' of the function itself.
11902///
11903/// This sets NewFD->isInvalidDecl() to true if there was an error.
11904///
11905/// Returns true if there was an error, false otherwise.
11906static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11907 bool &Redeclaration, NamedDecl *&OldDecl,
11908 LookupResult &Previous) {
11909 const TargetInfo &TI = S.getASTContext().getTargetInfo();
11910
11911 // Check if FMV is disabled.
11912 if (TI.getTriple().isAArch64() && !TI.hasFeature(Feature: "fmv"))
11913 return false;
11914
11915 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11916 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11917 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11918 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11919 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11920 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11921
11922 // Main isn't allowed to become a multiversion function, however it IS
11923 // permitted to have 'main' be marked with the 'target' optimization hint,
11924 // for 'target_version' only default is allowed.
11925 if (NewFD->isMain()) {
11926 if (MVKind != MultiVersionKind::None &&
11927 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11928 !(MVKind == MultiVersionKind::TargetVersion &&
11929 NewTVA->isDefaultVersion())) {
11930 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_allowed_on_main);
11931 NewFD->setInvalidDecl();
11932 return true;
11933 }
11934 return false;
11935 }
11936
11937 // Target attribute on AArch64 is not used for multiversioning
11938 if (NewTA && TI.getTriple().isAArch64())
11939 return false;
11940
11941 // Target attribute on RISCV is not used for multiversioning
11942 if (NewTA && TI.getTriple().isRISCV())
11943 return false;
11944
11945 if (!OldDecl || !OldDecl->getAsFunction() ||
11946 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
11947 DC: NewFD->getDeclContext()->getRedeclContext())) {
11948 // If there's no previous declaration, AND this isn't attempting to cause
11949 // multiversioning, this isn't an error condition.
11950 if (MVKind == MultiVersionKind::None)
11951 return false;
11952 return CheckMultiVersionFirstFunction(S, FD: NewFD);
11953 }
11954
11955 FunctionDecl *OldFD = OldDecl->getAsFunction();
11956
11957 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11958 return false;
11959
11960 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11961 // for target_clones and target_version.
11962 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11963 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
11964 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
11965 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
11966 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11967 NewFD->setInvalidDecl();
11968 return true;
11969 }
11970
11971 if (!OldFD->isMultiVersion()) {
11972 switch (MVKind) {
11973 case MultiVersionKind::Target:
11974 case MultiVersionKind::TargetVersion:
11975 return CheckDeclarationCausesMultiVersioning(
11976 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
11977 case MultiVersionKind::TargetClones:
11978 if (OldFD->isUsed(CheckUsedAttr: false)) {
11979 NewFD->setInvalidDecl();
11980 return S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
11981 }
11982 OldFD->setIsMultiVersion();
11983 break;
11984
11985 case MultiVersionKind::CPUDispatch:
11986 case MultiVersionKind::CPUSpecific:
11987 case MultiVersionKind::None:
11988 break;
11989 }
11990 }
11991
11992 // At this point, we have a multiversion function decl (in OldFD) AND an
11993 // appropriate attribute in the current function decl. Resolve that these are
11994 // still compatible with previous declarations.
11995 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
11996 NewCPUSpec, NewClones, Redeclaration,
11997 OldDecl, Previous);
11998}
11999
12000static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {
12001 bool IsPure = NewFD->hasAttr<PureAttr>();
12002 bool IsConst = NewFD->hasAttr<ConstAttr>();
12003
12004 // If there are no pure or const attributes, there's nothing to check.
12005 if (!IsPure && !IsConst)
12006 return;
12007
12008 // If the function is marked both pure and const, we retain the const
12009 // attribute because it makes stronger guarantees than the pure attribute, and
12010 // we drop the pure attribute explicitly to prevent later confusion about
12011 // semantics.
12012 if (IsPure && IsConst) {
12013 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_const_attr_with_pure_attr);
12014 NewFD->dropAttrs<PureAttr>();
12015 }
12016
12017 // Constructors and destructors are functions which return void, so are
12018 // handled here as well.
12019 if (NewFD->getReturnType()->isVoidType()) {
12020 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_pure_function_returns_void)
12021 << IsConst;
12022 NewFD->dropAttrs<PureAttr, ConstAttr>();
12023 }
12024}
12025
12026bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
12027 LookupResult &Previous,
12028 bool IsMemberSpecialization,
12029 bool DeclIsDefn) {
12030 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12031 "Variably modified return types are not handled here");
12032
12033 // Determine whether the type of this function should be merged with
12034 // a previous visible declaration. This never happens for functions in C++,
12035 // and always happens in C if the previous declaration was visible.
12036 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12037 !Previous.isShadowed();
12038
12039 bool Redeclaration = false;
12040 NamedDecl *OldDecl = nullptr;
12041 bool MayNeedOverloadableChecks = false;
12042
12043 inferLifetimeCaptureByAttribute(FD: NewFD);
12044 // Merge or overload the declaration with an existing declaration of
12045 // the same name, if appropriate.
12046 if (!Previous.empty()) {
12047 // Determine whether NewFD is an overload of PrevDecl or
12048 // a declaration that requires merging. If it's an overload,
12049 // there's no more work to do here; we'll just add the new
12050 // function to the scope.
12051 if (!AllowOverloadingOfFunction(Previous, Context, New: NewFD)) {
12052 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12053 if (shouldLinkPossiblyHiddenDecl(Old: Candidate, New: NewFD)) {
12054 Redeclaration = true;
12055 OldDecl = Candidate;
12056 }
12057 } else {
12058 MayNeedOverloadableChecks = true;
12059 switch (CheckOverload(S, New: NewFD, OldDecls: Previous, OldDecl,
12060 /*NewIsUsingDecl*/ UseMemberUsingDeclRules: false)) {
12061 case OverloadKind::Match:
12062 Redeclaration = true;
12063 break;
12064
12065 case OverloadKind::NonFunction:
12066 Redeclaration = true;
12067 break;
12068
12069 case OverloadKind::Overload:
12070 Redeclaration = false;
12071 break;
12072 }
12073 }
12074 }
12075
12076 // Check for a previous extern "C" declaration with this name.
12077 if (!Redeclaration &&
12078 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewFD, Previous)) {
12079 if (!Previous.empty()) {
12080 // This is an extern "C" declaration with the same name as a previous
12081 // declaration, and thus redeclares that entity...
12082 Redeclaration = true;
12083 OldDecl = Previous.getFoundDecl();
12084 MergeTypeWithPrevious = false;
12085
12086 // ... except in the presence of __attribute__((overloadable)).
12087 if (OldDecl->hasAttr<OverloadableAttr>() ||
12088 NewFD->hasAttr<OverloadableAttr>()) {
12089 if (IsOverload(New: NewFD, Old: cast<FunctionDecl>(Val: OldDecl), UseMemberUsingDeclRules: false)) {
12090 MayNeedOverloadableChecks = true;
12091 Redeclaration = false;
12092 OldDecl = nullptr;
12093 }
12094 }
12095 }
12096 }
12097
12098 if (CheckMultiVersionFunction(S&: *this, NewFD, Redeclaration, OldDecl, Previous))
12099 return Redeclaration;
12100
12101 // PPC MMA non-pointer types are not allowed as function return types.
12102 if (Context.getTargetInfo().getTriple().isPPC64() &&
12103 PPC().CheckPPCMMAType(Type: NewFD->getReturnType(), TypeLoc: NewFD->getLocation())) {
12104 NewFD->setInvalidDecl();
12105 }
12106
12107 CheckConstPureAttributesUsage(S&: *this, NewFD);
12108
12109 // C++ [dcl.spec.auto.general]p12:
12110 // Return type deduction for a templated function with a placeholder in its
12111 // declared type occurs when the definition is instantiated even if the
12112 // function body contains a return statement with a non-type-dependent
12113 // operand.
12114 //
12115 // C++ [temp.dep.expr]p3:
12116 // An id-expression is type-dependent if it is a template-id that is not a
12117 // concept-id and is dependent; or if its terminal name is:
12118 // - [...]
12119 // - associated by name lookup with one or more declarations of member
12120 // functions of a class that is the current instantiation declared with a
12121 // return type that contains a placeholder type,
12122 // - [...]
12123 //
12124 // If this is a templated function with a placeholder in its return type,
12125 // make the placeholder type dependent since it won't be deduced until the
12126 // definition is instantiated. We do this here because it needs to happen
12127 // for implicitly instantiated member functions/member function templates.
12128 if (getLangOpts().CPlusPlus14 &&
12129 (NewFD->isDependentContext() &&
12130 NewFD->getReturnType()->isUndeducedType())) {
12131 const FunctionProtoType *FPT =
12132 NewFD->getType()->castAs<FunctionProtoType>();
12133 QualType NewReturnType = SubstAutoTypeDependent(TypeWithAuto: FPT->getReturnType());
12134 NewFD->setType(Context.getFunctionType(ResultTy: NewReturnType, Args: FPT->getParamTypes(),
12135 EPI: FPT->getExtProtoInfo()));
12136 }
12137
12138 // C++11 [dcl.constexpr]p8:
12139 // A constexpr specifier for a non-static member function that is not
12140 // a constructor declares that member function to be const.
12141 //
12142 // This needs to be delayed until we know whether this is an out-of-line
12143 // definition of a static member function.
12144 //
12145 // This rule is not present in C++1y, so we produce a backwards
12146 // compatibility warning whenever it happens in C++11.
12147 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
12148 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12149 !MD->isStatic() && !isa<CXXConstructorDecl>(Val: MD) &&
12150 !isa<CXXDestructorDecl>(Val: MD) && !MD->getMethodQualifiers().hasConst()) {
12151 CXXMethodDecl *OldMD = nullptr;
12152 if (OldDecl)
12153 OldMD = dyn_cast_or_null<CXXMethodDecl>(Val: OldDecl->getAsFunction());
12154 if (!OldMD || !OldMD->isStatic()) {
12155 const FunctionProtoType *FPT =
12156 MD->getType()->castAs<FunctionProtoType>();
12157 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12158 EPI.TypeQuals.addConst();
12159 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
12160 Args: FPT->getParamTypes(), EPI));
12161
12162 // Warn that we did this, if we're not performing template instantiation.
12163 // In that case, we'll have warned already when the template was defined.
12164 if (!inTemplateInstantiation()) {
12165 SourceLocation AddConstLoc;
12166 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
12167 .IgnoreParens().getAs<FunctionTypeLoc>())
12168 AddConstLoc = getLocForEndOfToken(Loc: FTL.getRParenLoc());
12169
12170 Diag(Loc: MD->getLocation(), DiagID: diag::warn_cxx14_compat_constexpr_not_const)
12171 << FixItHint::CreateInsertion(InsertionLoc: AddConstLoc, Code: " const");
12172 }
12173 }
12174 }
12175
12176 if (Redeclaration) {
12177 // NewFD and OldDecl represent declarations that need to be
12178 // merged.
12179 if (MergeFunctionDecl(New: NewFD, OldD&: OldDecl, S, MergeTypeWithOld: MergeTypeWithPrevious,
12180 NewDeclIsDefn: DeclIsDefn)) {
12181 NewFD->setInvalidDecl();
12182 return Redeclaration;
12183 }
12184
12185 Previous.clear();
12186 Previous.addDecl(D: OldDecl);
12187
12188 if (FunctionTemplateDecl *OldTemplateDecl =
12189 dyn_cast<FunctionTemplateDecl>(Val: OldDecl)) {
12190 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12191 FunctionTemplateDecl *NewTemplateDecl
12192 = NewFD->getDescribedFunctionTemplate();
12193 assert(NewTemplateDecl && "Template/non-template mismatch");
12194
12195 // The call to MergeFunctionDecl above may have created some state in
12196 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12197 // can add it as a redeclaration.
12198 NewTemplateDecl->mergePrevDecl(Prev: OldTemplateDecl);
12199
12200 NewFD->setPreviousDeclaration(OldFD);
12201 if (NewFD->isCXXClassMember()) {
12202 NewFD->setAccess(OldTemplateDecl->getAccess());
12203 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12204 }
12205
12206 // If this is an explicit specialization of a member that is a function
12207 // template, mark it as a member specialization.
12208 if (IsMemberSpecialization &&
12209 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12210 NewTemplateDecl->setMemberSpecialization();
12211 assert(OldTemplateDecl->isMemberSpecialization());
12212 // Explicit specializations of a member template do not inherit deleted
12213 // status from the parent member template that they are specializing.
12214 if (OldFD->isDeleted()) {
12215 // FIXME: This assert will not hold in the presence of modules.
12216 assert(OldFD->getCanonicalDecl() == OldFD);
12217 // FIXME: We need an update record for this AST mutation.
12218 OldFD->setDeletedAsWritten(D: false);
12219 }
12220 }
12221
12222 } else {
12223 if (shouldLinkDependentDeclWithPrevious(D: NewFD, PrevDecl: OldDecl)) {
12224 auto *OldFD = cast<FunctionDecl>(Val: OldDecl);
12225 // This needs to happen first so that 'inline' propagates.
12226 NewFD->setPreviousDeclaration(OldFD);
12227 if (NewFD->isCXXClassMember())
12228 NewFD->setAccess(OldFD->getAccess());
12229 }
12230 }
12231 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12232 !NewFD->getAttr<OverloadableAttr>()) {
12233 assert((Previous.empty() ||
12234 llvm::any_of(Previous,
12235 [](const NamedDecl *ND) {
12236 return ND->hasAttr<OverloadableAttr>();
12237 })) &&
12238 "Non-redecls shouldn't happen without overloadable present");
12239
12240 auto OtherUnmarkedIter = llvm::find_if(Range&: Previous, P: [](const NamedDecl *ND) {
12241 const auto *FD = dyn_cast<FunctionDecl>(Val: ND);
12242 return FD && !FD->hasAttr<OverloadableAttr>();
12243 });
12244
12245 if (OtherUnmarkedIter != Previous.end()) {
12246 Diag(Loc: NewFD->getLocation(),
12247 DiagID: diag::err_attribute_overloadable_multiple_unmarked_overloads);
12248 Diag(Loc: (*OtherUnmarkedIter)->getLocation(),
12249 DiagID: diag::note_attribute_overloadable_prev_overload)
12250 << false;
12251
12252 NewFD->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
12253 }
12254 }
12255
12256 if (LangOpts.OpenMP)
12257 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(D: NewFD);
12258
12259 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12260 SYCL().CheckSYCLEntryPointFunctionDecl(FD: NewFD);
12261
12262 // Semantic checking for this function declaration (in isolation).
12263
12264 if (getLangOpts().CPlusPlus) {
12265 // C++-specific checks.
12266 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: NewFD)) {
12267 CheckConstructor(Constructor);
12268 } else if (CXXDestructorDecl *Destructor =
12269 dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
12270 // We check here for invalid destructor names.
12271 // If we have a friend destructor declaration that is dependent, we can't
12272 // diagnose right away because cases like this are still valid:
12273 // template <class T> struct A { friend T::X::~Y(); };
12274 // struct B { struct Y { ~Y(); }; using X = Y; };
12275 // template struct A<B>;
12276 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12277 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12278 CXXRecordDecl *Record = Destructor->getParent();
12279 QualType ClassType = Context.getTypeDeclType(Decl: Record);
12280
12281 DeclarationName Name = Context.DeclarationNames.getCXXDestructorName(
12282 Ty: Context.getCanonicalType(T: ClassType));
12283 if (NewFD->getDeclName() != Name) {
12284 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_name);
12285 NewFD->setInvalidDecl();
12286 return Redeclaration;
12287 }
12288 }
12289 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: NewFD)) {
12290 if (auto *TD = Guide->getDescribedFunctionTemplate())
12291 CheckDeductionGuideTemplate(TD);
12292
12293 // A deduction guide is not on the list of entities that can be
12294 // explicitly specialized.
12295 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12296 Diag(Loc: Guide->getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
12297 << /*explicit specialization*/ 1;
12298 }
12299
12300 // Find any virtual functions that this function overrides.
12301 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
12302 if (!Method->isFunctionTemplateSpecialization() &&
12303 !Method->getDescribedFunctionTemplate() &&
12304 Method->isCanonicalDecl()) {
12305 AddOverriddenMethods(DC: Method->getParent(), MD: Method);
12306 }
12307 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12308 // C++2a [class.virtual]p6
12309 // A virtual method shall not have a requires-clause.
12310 Diag(Loc: NewFD->getTrailingRequiresClause().ConstraintExpr->getBeginLoc(),
12311 DiagID: diag::err_constrained_virtual_method);
12312
12313 if (Method->isStatic())
12314 checkThisInStaticMemberFunctionType(Method);
12315 }
12316
12317 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: NewFD))
12318 ActOnConversionDeclarator(Conversion);
12319
12320 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12321 if (NewFD->isOverloadedOperator() &&
12322 CheckOverloadedOperatorDeclaration(FnDecl: NewFD)) {
12323 NewFD->setInvalidDecl();
12324 return Redeclaration;
12325 }
12326
12327 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12328 if (NewFD->getLiteralIdentifier() &&
12329 CheckLiteralOperatorDeclaration(FnDecl: NewFD)) {
12330 NewFD->setInvalidDecl();
12331 return Redeclaration;
12332 }
12333
12334 // In C++, check default arguments now that we have merged decls. Unless
12335 // the lexical context is the class, because in this case this is done
12336 // during delayed parsing anyway.
12337 if (!CurContext->isRecord())
12338 CheckCXXDefaultArguments(FD: NewFD);
12339
12340 // If this function is declared as being extern "C", then check to see if
12341 // the function returns a UDT (class, struct, or union type) that is not C
12342 // compatible, and if it does, warn the user.
12343 // But, issue any diagnostic on the first declaration only.
12344 if (Previous.empty() && NewFD->isExternC()) {
12345 QualType R = NewFD->getReturnType();
12346 if (R->isIncompleteType() && !R->isVoidType())
12347 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt_incomplete)
12348 << NewFD << R;
12349 else if (!R.isPODType(Context) && !R->isVoidType() &&
12350 !R->isObjCObjectPointerType())
12351 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt) << NewFD << R;
12352 }
12353
12354 // C++1z [dcl.fct]p6:
12355 // [...] whether the function has a non-throwing exception-specification
12356 // [is] part of the function type
12357 //
12358 // This results in an ABI break between C++14 and C++17 for functions whose
12359 // declared type includes an exception-specification in a parameter or
12360 // return type. (Exception specifications on the function itself are OK in
12361 // most cases, and exception specifications are not permitted in most other
12362 // contexts where they could make it into a mangling.)
12363 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12364 auto HasNoexcept = [&](QualType T) -> bool {
12365 // Strip off declarator chunks that could be between us and a function
12366 // type. We don't need to look far, exception specifications are very
12367 // restricted prior to C++17.
12368 if (auto *RT = T->getAs<ReferenceType>())
12369 T = RT->getPointeeType();
12370 else if (T->isAnyPointerType())
12371 T = T->getPointeeType();
12372 else if (auto *MPT = T->getAs<MemberPointerType>())
12373 T = MPT->getPointeeType();
12374 if (auto *FPT = T->getAs<FunctionProtoType>())
12375 if (FPT->isNothrow())
12376 return true;
12377 return false;
12378 };
12379
12380 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12381 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12382 for (QualType T : FPT->param_types())
12383 AnyNoexcept |= HasNoexcept(T);
12384 if (AnyNoexcept)
12385 Diag(Loc: NewFD->getLocation(),
12386 DiagID: diag::warn_cxx17_compat_exception_spec_in_signature)
12387 << NewFD;
12388 }
12389
12390 if (!Redeclaration && LangOpts.CUDA) {
12391 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12392 for (auto *Parm : NewFD->parameters()) {
12393 if (!Parm->getType()->isDependentType() &&
12394 Parm->hasAttr<CUDAGridConstantAttr>() &&
12395 !(IsKernel && Parm->getType().isConstQualified()))
12396 Diag(Loc: Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12397 DiagID: diag::err_cuda_grid_constant_not_allowed);
12398 }
12399 CUDA().checkTargetOverload(NewFD, Previous);
12400 }
12401 }
12402
12403 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12404 ARM().CheckSMEFunctionDefAttributes(FD: NewFD);
12405
12406 return Redeclaration;
12407}
12408
12409void Sema::CheckMain(FunctionDecl *FD, const DeclSpec &DS) {
12410 // [basic.start.main]p3
12411 // The main function shall not be declared with C linkage-specification.
12412 if (FD->isExternCContext())
12413 Diag(Loc: FD->getLocation(), DiagID: diag::ext_main_invalid_linkage_specification);
12414
12415 // C++11 [basic.start.main]p3:
12416 // A program that [...] declares main to be inline, static or
12417 // constexpr is ill-formed.
12418 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12419 // appear in a declaration of main.
12420 // static main is not an error under C99, but we should warn about it.
12421 // We accept _Noreturn main as an extension.
12422 if (FD->getStorageClass() == SC_Static)
12423 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus
12424 ? diag::err_static_main : diag::warn_static_main)
12425 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
12426 if (FD->isInlineSpecified())
12427 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_main)
12428 << FixItHint::CreateRemoval(RemoveRange: DS.getInlineSpecLoc());
12429 if (DS.isNoreturnSpecified()) {
12430 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12431 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(Loc: NoreturnLoc));
12432 Diag(Loc: NoreturnLoc, DiagID: diag::ext_noreturn_main);
12433 Diag(Loc: NoreturnLoc, DiagID: diag::note_main_remove_noreturn)
12434 << FixItHint::CreateRemoval(RemoveRange: NoreturnRange);
12435 }
12436 if (FD->isConstexpr()) {
12437 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_main)
12438 << FD->isConsteval()
12439 << FixItHint::CreateRemoval(RemoveRange: DS.getConstexprSpecLoc());
12440 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12441 }
12442
12443 if (getLangOpts().OpenCL) {
12444 Diag(Loc: FD->getLocation(), DiagID: diag::err_opencl_no_main)
12445 << FD->hasAttr<DeviceKernelAttr>();
12446 FD->setInvalidDecl();
12447 return;
12448 }
12449
12450 // Functions named main in hlsl are default entries, but don't have specific
12451 // signatures they are required to conform to.
12452 if (getLangOpts().HLSL)
12453 return;
12454
12455 QualType T = FD->getType();
12456 assert(T->isFunctionType() && "function decl is not of function type");
12457 const FunctionType* FT = T->castAs<FunctionType>();
12458
12459 // Set default calling convention for main()
12460 if (FT->getCallConv() != CC_C) {
12461 FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12462 FD->setType(QualType(FT, 0));
12463 T = Context.getCanonicalType(T: FD->getType());
12464 }
12465
12466 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12467 // In C with GNU extensions we allow main() to have non-integer return
12468 // type, but we should warn about the extension, and we disable the
12469 // implicit-return-zero rule.
12470
12471 // GCC in C mode accepts qualified 'int'.
12472 if (Context.hasSameUnqualifiedType(T1: FT->getReturnType(), T2: Context.IntTy))
12473 FD->setHasImplicitReturnZero(true);
12474 else {
12475 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::ext_main_returns_nonint);
12476 SourceRange RTRange = FD->getReturnTypeSourceRange();
12477 if (RTRange.isValid())
12478 Diag(Loc: RTRange.getBegin(), DiagID: diag::note_main_change_return_type)
12479 << FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int");
12480 }
12481 } else {
12482 // In C and C++, main magically returns 0 if you fall off the end;
12483 // set the flag which tells us that.
12484 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12485
12486 // All the standards say that main() should return 'int'.
12487 if (Context.hasSameType(T1: FT->getReturnType(), T2: Context.IntTy))
12488 FD->setHasImplicitReturnZero(true);
12489 else {
12490 // Otherwise, this is just a flat-out error.
12491 SourceRange RTRange = FD->getReturnTypeSourceRange();
12492 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::err_main_returns_nonint)
12493 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int")
12494 : FixItHint());
12495 FD->setInvalidDecl(true);
12496 }
12497
12498 // [basic.start.main]p3:
12499 // A program that declares a function main that belongs to the global scope
12500 // and is attached to a named module is ill-formed.
12501 if (FD->isInNamedModule()) {
12502 const SourceLocation start = FD->getTypeSpecStartLoc();
12503 Diag(Loc: start, DiagID: diag::warn_main_in_named_module)
12504 << FixItHint::CreateInsertion(InsertionLoc: start, Code: "extern \"C++\" ", BeforePreviousInsertions: true);
12505 }
12506 }
12507
12508 // Treat protoless main() as nullary.
12509 if (isa<FunctionNoProtoType>(Val: FT)) return;
12510
12511 const FunctionProtoType* FTP = cast<const FunctionProtoType>(Val: FT);
12512 unsigned nparams = FTP->getNumParams();
12513 assert(FD->getNumParams() == nparams);
12514
12515 bool HasExtraParameters = (nparams > 3);
12516
12517 if (FTP->isVariadic()) {
12518 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variadic_main);
12519 // FIXME: if we had information about the location of the ellipsis, we
12520 // could add a FixIt hint to remove it as a parameter.
12521 }
12522
12523 // Darwin passes an undocumented fourth argument of type char**. If
12524 // other platforms start sprouting these, the logic below will start
12525 // getting shifty.
12526 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12527 HasExtraParameters = false;
12528
12529 if (HasExtraParameters) {
12530 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_surplus_args) << nparams;
12531 FD->setInvalidDecl(true);
12532 nparams = 3;
12533 }
12534
12535 // FIXME: a lot of the following diagnostics would be improved
12536 // if we had some location information about types.
12537
12538 QualType CharPP =
12539 Context.getPointerType(T: Context.getPointerType(T: Context.CharTy));
12540 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12541
12542 for (unsigned i = 0; i < nparams; ++i) {
12543 QualType AT = FTP->getParamType(i);
12544
12545 bool mismatch = true;
12546
12547 if (Context.hasSameUnqualifiedType(T1: AT, T2: Expected[i]))
12548 mismatch = false;
12549 else if (Expected[i] == CharPP) {
12550 // As an extension, the following forms are okay:
12551 // char const **
12552 // char const * const *
12553 // char * const *
12554
12555 QualifierCollector qs;
12556 const PointerType* PT;
12557 if ((PT = qs.strip(type: AT)->getAs<PointerType>()) &&
12558 (PT = qs.strip(type: PT->getPointeeType())->getAs<PointerType>()) &&
12559 Context.hasSameType(T1: QualType(qs.strip(type: PT->getPointeeType()), 0),
12560 T2: Context.CharTy)) {
12561 qs.removeConst();
12562 mismatch = !qs.empty();
12563 }
12564 }
12565
12566 if (mismatch) {
12567 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_arg_wrong) << i << Expected[i];
12568 // TODO: suggest replacing given type with expected type
12569 FD->setInvalidDecl(true);
12570 }
12571 }
12572
12573 if (nparams == 1 && !FD->isInvalidDecl()) {
12574 Diag(Loc: FD->getLocation(), DiagID: diag::warn_main_one_arg);
12575 }
12576
12577 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12578 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
12579 FD->setInvalidDecl();
12580 }
12581}
12582
12583static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12584
12585 // Default calling convention for main and wmain is __cdecl
12586 if (FD->getName() == "main" || FD->getName() == "wmain")
12587 return false;
12588
12589 // Default calling convention for MinGW is __cdecl
12590 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12591 if (T.isWindowsGNUEnvironment())
12592 return false;
12593
12594 // Default calling convention for WinMain, wWinMain and DllMain
12595 // is __stdcall on 32 bit Windows
12596 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12597 return true;
12598
12599 return false;
12600}
12601
12602void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12603 QualType T = FD->getType();
12604 assert(T->isFunctionType() && "function decl is not of function type");
12605 const FunctionType *FT = T->castAs<FunctionType>();
12606
12607 // Set an implicit return of 'zero' if the function can return some integral,
12608 // enumeration, pointer or nullptr type.
12609 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12610 FT->getReturnType()->isAnyPointerType() ||
12611 FT->getReturnType()->isNullPtrType())
12612 // DllMain is exempt because a return value of zero means it failed.
12613 if (FD->getName() != "DllMain")
12614 FD->setHasImplicitReturnZero(true);
12615
12616 // Explicitly specified calling conventions are applied to MSVC entry points
12617 if (!hasExplicitCallingConv(T)) {
12618 if (isDefaultStdCall(FD, S&: *this)) {
12619 if (FT->getCallConv() != CC_X86StdCall) {
12620 FT = Context.adjustFunctionType(
12621 Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_X86StdCall));
12622 FD->setType(QualType(FT, 0));
12623 }
12624 } else if (FT->getCallConv() != CC_C) {
12625 FT = Context.adjustFunctionType(Fn: FT,
12626 EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12627 FD->setType(QualType(FT, 0));
12628 }
12629 }
12630
12631 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12632 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
12633 FD->setInvalidDecl();
12634 }
12635}
12636
12637bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {
12638 // FIXME: Need strict checking. In C89, we need to check for
12639 // any assignment, increment, decrement, function-calls, or
12640 // commas outside of a sizeof. In C99, it's the same list,
12641 // except that the aforementioned are allowed in unevaluated
12642 // expressions. Everything else falls under the
12643 // "may accept other forms of constant expressions" exception.
12644 //
12645 // Regular C++ code will not end up here (exceptions: language extensions,
12646 // OpenCL C++ etc), so the constant expression rules there don't matter.
12647 if (Init->isValueDependent()) {
12648 assert(Init->containsErrors() &&
12649 "Dependent code should only occur in error-recovery path.");
12650 return true;
12651 }
12652 const Expr *Culprit;
12653 if (Init->isConstantInitializer(Ctx&: Context, ForRef: false, Culprit: &Culprit))
12654 return false;
12655 Diag(Loc: Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12656 return true;
12657}
12658
12659namespace {
12660 // Visits an initialization expression to see if OrigDecl is evaluated in
12661 // its own initialization and throws a warning if it does.
12662 class SelfReferenceChecker
12663 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12664 Sema &S;
12665 Decl *OrigDecl;
12666 bool isRecordType;
12667 bool isPODType;
12668 bool isReferenceType;
12669 bool isInCXXOperatorCall;
12670
12671 bool isInitList;
12672 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12673
12674 public:
12675 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12676
12677 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12678 S(S), OrigDecl(OrigDecl) {
12679 isPODType = false;
12680 isRecordType = false;
12681 isReferenceType = false;
12682 isInCXXOperatorCall = false;
12683 isInitList = false;
12684 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: OrigDecl)) {
12685 isPODType = VD->getType().isPODType(Context: S.Context);
12686 isRecordType = VD->getType()->isRecordType();
12687 isReferenceType = VD->getType()->isReferenceType();
12688 }
12689 }
12690
12691 // For most expressions, just call the visitor. For initializer lists,
12692 // track the index of the field being initialized since fields are
12693 // initialized in order allowing use of previously initialized fields.
12694 void CheckExpr(Expr *E) {
12695 InitListExpr *InitList = dyn_cast<InitListExpr>(Val: E);
12696 if (!InitList) {
12697 Visit(S: E);
12698 return;
12699 }
12700
12701 // Track and increment the index here.
12702 isInitList = true;
12703 InitFieldIndex.push_back(Elt: 0);
12704 for (auto *Child : InitList->children()) {
12705 CheckExpr(E: cast<Expr>(Val: Child));
12706 ++InitFieldIndex.back();
12707 }
12708 InitFieldIndex.pop_back();
12709 }
12710
12711 // Returns true if MemberExpr is checked and no further checking is needed.
12712 // Returns false if additional checking is required.
12713 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12714 llvm::SmallVector<FieldDecl*, 4> Fields;
12715 Expr *Base = E;
12716 bool ReferenceField = false;
12717
12718 // Get the field members used.
12719 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
12720 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
12721 if (!FD)
12722 return false;
12723 Fields.push_back(Elt: FD);
12724 if (FD->getType()->isReferenceType())
12725 ReferenceField = true;
12726 Base = ME->getBase()->IgnoreParenImpCasts();
12727 }
12728
12729 // Keep checking only if the base Decl is the same.
12730 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base);
12731 if (!DRE || DRE->getDecl() != OrigDecl)
12732 return false;
12733
12734 // A reference field can be bound to an unininitialized field.
12735 if (CheckReference && !ReferenceField)
12736 return true;
12737
12738 // Convert FieldDecls to their index number.
12739 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12740 for (const FieldDecl *I : llvm::reverse(C&: Fields))
12741 UsedFieldIndex.push_back(Elt: I->getFieldIndex());
12742
12743 // See if a warning is needed by checking the first difference in index
12744 // numbers. If field being used has index less than the field being
12745 // initialized, then the use is safe.
12746 for (auto UsedIter = UsedFieldIndex.begin(),
12747 UsedEnd = UsedFieldIndex.end(),
12748 OrigIter = InitFieldIndex.begin(),
12749 OrigEnd = InitFieldIndex.end();
12750 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12751 if (*UsedIter < *OrigIter)
12752 return true;
12753 if (*UsedIter > *OrigIter)
12754 break;
12755 }
12756
12757 // TODO: Add a different warning which will print the field names.
12758 HandleDeclRefExpr(DRE);
12759 return true;
12760 }
12761
12762 // For most expressions, the cast is directly above the DeclRefExpr.
12763 // For conditional operators, the cast can be outside the conditional
12764 // operator if both expressions are DeclRefExpr's.
12765 void HandleValue(Expr *E) {
12766 E = E->IgnoreParens();
12767 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Val: E)) {
12768 HandleDeclRefExpr(DRE);
12769 return;
12770 }
12771
12772 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
12773 Visit(S: CO->getCond());
12774 HandleValue(E: CO->getTrueExpr());
12775 HandleValue(E: CO->getFalseExpr());
12776 return;
12777 }
12778
12779 if (BinaryConditionalOperator *BCO =
12780 dyn_cast<BinaryConditionalOperator>(Val: E)) {
12781 Visit(S: BCO->getCond());
12782 HandleValue(E: BCO->getFalseExpr());
12783 return;
12784 }
12785
12786 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
12787 if (Expr *SE = OVE->getSourceExpr())
12788 HandleValue(E: SE);
12789 return;
12790 }
12791
12792 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
12793 if (BO->getOpcode() == BO_Comma) {
12794 Visit(S: BO->getLHS());
12795 HandleValue(E: BO->getRHS());
12796 return;
12797 }
12798 }
12799
12800 if (isa<MemberExpr>(Val: E)) {
12801 if (isInitList) {
12802 if (CheckInitListMemberExpr(E: cast<MemberExpr>(Val: E),
12803 CheckReference: false /*CheckReference*/))
12804 return;
12805 }
12806
12807 Expr *Base = E->IgnoreParenImpCasts();
12808 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
12809 // Check for static member variables and don't warn on them.
12810 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
12811 return;
12812 Base = ME->getBase()->IgnoreParenImpCasts();
12813 }
12814 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base))
12815 HandleDeclRefExpr(DRE);
12816 return;
12817 }
12818
12819 Visit(S: E);
12820 }
12821
12822 // Reference types not handled in HandleValue are handled here since all
12823 // uses of references are bad, not just r-value uses.
12824 void VisitDeclRefExpr(DeclRefExpr *E) {
12825 if (isReferenceType)
12826 HandleDeclRefExpr(DRE: E);
12827 }
12828
12829 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12830 if (E->getCastKind() == CK_LValueToRValue) {
12831 HandleValue(E: E->getSubExpr());
12832 return;
12833 }
12834
12835 Inherited::VisitImplicitCastExpr(S: E);
12836 }
12837
12838 void VisitMemberExpr(MemberExpr *E) {
12839 if (isInitList) {
12840 if (CheckInitListMemberExpr(E, CheckReference: true /*CheckReference*/))
12841 return;
12842 }
12843
12844 // Don't warn on arrays since they can be treated as pointers.
12845 if (E->getType()->canDecayToPointerType()) return;
12846
12847 // Warn when a non-static method call is followed by non-static member
12848 // field accesses, which is followed by a DeclRefExpr.
12849 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl());
12850 bool Warn = (MD && !MD->isStatic());
12851 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12852 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
12853 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
12854 Warn = false;
12855 Base = ME->getBase()->IgnoreParenImpCasts();
12856 }
12857
12858 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base)) {
12859 if (Warn)
12860 HandleDeclRefExpr(DRE);
12861 return;
12862 }
12863
12864 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12865 // Visit that expression.
12866 Visit(S: Base);
12867 }
12868
12869 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12870 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
12871 Expr *Callee = E->getCallee();
12872
12873 if (isa<UnresolvedLookupExpr>(Val: Callee))
12874 return Inherited::VisitCXXOperatorCallExpr(S: E);
12875
12876 Visit(S: Callee);
12877 for (auto Arg: E->arguments())
12878 HandleValue(E: Arg->IgnoreParenImpCasts());
12879 }
12880
12881 void VisitLambdaExpr(LambdaExpr *E) {
12882 if (!isInCXXOperatorCall) {
12883 Inherited::VisitLambdaExpr(LE: E);
12884 return;
12885 }
12886
12887 for (Expr *Init : E->capture_inits())
12888 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: Init))
12889 HandleDeclRefExpr(DRE);
12890 else if (Init)
12891 Visit(S: Init);
12892 }
12893
12894 void VisitUnaryOperator(UnaryOperator *E) {
12895 // For POD record types, addresses of its own members are well-defined.
12896 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12897 isa<MemberExpr>(Val: E->getSubExpr()->IgnoreParens())) {
12898 if (!isPODType)
12899 HandleValue(E: E->getSubExpr());
12900 return;
12901 }
12902
12903 if (E->isIncrementDecrementOp()) {
12904 HandleValue(E: E->getSubExpr());
12905 return;
12906 }
12907
12908 Inherited::VisitUnaryOperator(S: E);
12909 }
12910
12911 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12912
12913 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12914 if (E->getConstructor()->isCopyConstructor()) {
12915 Expr *ArgExpr = E->getArg(Arg: 0);
12916 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
12917 if (ILE->getNumInits() == 1)
12918 ArgExpr = ILE->getInit(Init: 0);
12919 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
12920 if (ICE->getCastKind() == CK_NoOp)
12921 ArgExpr = ICE->getSubExpr();
12922 HandleValue(E: ArgExpr);
12923 return;
12924 }
12925 Inherited::VisitCXXConstructExpr(S: E);
12926 }
12927
12928 void VisitCallExpr(CallExpr *E) {
12929 // Treat std::move as a use.
12930 if (E->isCallToStdMove()) {
12931 HandleValue(E: E->getArg(Arg: 0));
12932 return;
12933 }
12934
12935 Inherited::VisitCallExpr(CE: E);
12936 }
12937
12938 void VisitBinaryOperator(BinaryOperator *E) {
12939 if (E->isCompoundAssignmentOp()) {
12940 HandleValue(E: E->getLHS());
12941 Visit(S: E->getRHS());
12942 return;
12943 }
12944
12945 Inherited::VisitBinaryOperator(S: E);
12946 }
12947
12948 // A custom visitor for BinaryConditionalOperator is needed because the
12949 // regular visitor would check the condition and true expression separately
12950 // but both point to the same place giving duplicate diagnostics.
12951 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12952 Visit(S: E->getCond());
12953 Visit(S: E->getFalseExpr());
12954 }
12955
12956 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12957 Decl* ReferenceDecl = DRE->getDecl();
12958 if (OrigDecl != ReferenceDecl) return;
12959 unsigned diag;
12960 if (isReferenceType) {
12961 diag = diag::warn_uninit_self_reference_in_reference_init;
12962 } else if (cast<VarDecl>(Val: OrigDecl)->isStaticLocal()) {
12963 diag = diag::warn_static_self_reference_in_init;
12964 } else if (isa<TranslationUnitDecl>(Val: OrigDecl->getDeclContext()) ||
12965 isa<NamespaceDecl>(Val: OrigDecl->getDeclContext()) ||
12966 DRE->getDecl()->getType()->isRecordType()) {
12967 diag = diag::warn_uninit_self_reference_in_init;
12968 } else {
12969 // Local variables will be handled by the CFG analysis.
12970 return;
12971 }
12972
12973 S.DiagRuntimeBehavior(Loc: DRE->getBeginLoc(), Statement: DRE,
12974 PD: S.PDiag(DiagID: diag)
12975 << DRE->getDecl() << OrigDecl->getLocation()
12976 << DRE->getSourceRange());
12977 }
12978 };
12979
12980 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12981 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12982 bool DirectInit) {
12983 // Parameters arguments are occassionially constructed with itself,
12984 // for instance, in recursive functions. Skip them.
12985 if (isa<ParmVarDecl>(Val: OrigDecl))
12986 return;
12987
12988 E = E->IgnoreParens();
12989
12990 // Skip checking T a = a where T is not a record or reference type.
12991 // Doing so is a way to silence uninitialized warnings.
12992 if (!DirectInit && !cast<VarDecl>(Val: OrigDecl)->getType()->isRecordType())
12993 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
12994 if (ICE->getCastKind() == CK_LValueToRValue)
12995 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ICE->getSubExpr()))
12996 if (DRE->getDecl() == OrigDecl)
12997 return;
12998
12999 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13000 }
13001} // end anonymous namespace
13002
13003namespace {
13004 // Simple wrapper to add the name of a variable or (if no variable is
13005 // available) a DeclarationName into a diagnostic.
13006 struct VarDeclOrName {
13007 VarDecl *VDecl;
13008 DeclarationName Name;
13009
13010 friend const Sema::SemaDiagnosticBuilder &
13011 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13012 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13013 }
13014 };
13015} // end anonymous namespace
13016
13017QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
13018 DeclarationName Name, QualType Type,
13019 TypeSourceInfo *TSI,
13020 SourceRange Range, bool DirectInit,
13021 Expr *Init) {
13022 bool IsInitCapture = !VDecl;
13023 assert((!VDecl || !VDecl->isInitCapture()) &&
13024 "init captures are expected to be deduced prior to initialization");
13025
13026 VarDeclOrName VN{.VDecl: VDecl, .Name: Name};
13027
13028 DeducedType *Deduced = Type->getContainedDeducedType();
13029 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13030
13031 // Diagnose auto array declarations in C23, unless it's a supported extension.
13032 if (getLangOpts().C23 && Type->isArrayType() &&
13033 !isa_and_present<StringLiteral, InitListExpr>(Val: Init)) {
13034 Diag(Loc: Range.getBegin(), DiagID: diag::err_auto_not_allowed)
13035 << (int)Deduced->getContainedAutoType()->getKeyword()
13036 << /*in array decl*/ 23 << Range;
13037 return QualType();
13038 }
13039
13040 // C++11 [dcl.spec.auto]p3
13041 if (!Init) {
13042 assert(VDecl && "no init for init capture deduction?");
13043
13044 // Except for class argument deduction, and then for an initializing
13045 // declaration only, i.e. no static at class scope or extern.
13046 if (!isa<DeducedTemplateSpecializationType>(Val: Deduced) ||
13047 VDecl->hasExternalStorage() ||
13048 VDecl->isStaticDataMember()) {
13049 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_auto_var_requires_init)
13050 << VDecl->getDeclName() << Type;
13051 return QualType();
13052 }
13053 }
13054
13055 ArrayRef<Expr*> DeduceInits;
13056 if (Init)
13057 DeduceInits = Init;
13058
13059 auto *PL = dyn_cast_if_present<ParenListExpr>(Val: Init);
13060 if (DirectInit && PL)
13061 DeduceInits = PL->exprs();
13062
13063 if (isa<DeducedTemplateSpecializationType>(Val: Deduced)) {
13064 assert(VDecl && "non-auto type for init capture deduction?");
13065 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13066 InitializationKind Kind = InitializationKind::CreateForInit(
13067 Loc: VDecl->getLocation(), DirectInit, Init);
13068 // FIXME: Initialization should not be taking a mutable list of inits.
13069 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13070 return DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind,
13071 Init: InitsCopy);
13072 }
13073
13074 if (DirectInit) {
13075 if (auto *IL = dyn_cast<InitListExpr>(Val: Init))
13076 DeduceInits = IL->inits();
13077 }
13078
13079 // Deduction only works if we have exactly one source expression.
13080 if (DeduceInits.empty()) {
13081 // It isn't possible to write this directly, but it is possible to
13082 // end up in this situation with "auto x(some_pack...);"
13083 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13084 ? diag::err_init_capture_no_expression
13085 : diag::err_auto_var_init_no_expression)
13086 << VN << Type << Range;
13087 return QualType();
13088 }
13089
13090 if (DeduceInits.size() > 1) {
13091 Diag(Loc: DeduceInits[1]->getBeginLoc(),
13092 DiagID: IsInitCapture ? diag::err_init_capture_multiple_expressions
13093 : diag::err_auto_var_init_multiple_expressions)
13094 << VN << Type << Range;
13095 return QualType();
13096 }
13097
13098 Expr *DeduceInit = DeduceInits[0];
13099 if (DirectInit && isa<InitListExpr>(Val: DeduceInit)) {
13100 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13101 ? diag::err_init_capture_paren_braces
13102 : diag::err_auto_var_init_paren_braces)
13103 << isa<InitListExpr>(Val: Init) << VN << Type << Range;
13104 return QualType();
13105 }
13106
13107 // Expressions default to 'id' when we're in a debugger.
13108 bool DefaultedAnyToId = false;
13109 if (getLangOpts().DebuggerCastResultToId &&
13110 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13111 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13112 if (Result.isInvalid()) {
13113 return QualType();
13114 }
13115 Init = Result.get();
13116 DefaultedAnyToId = true;
13117 }
13118
13119 // C++ [dcl.decomp]p1:
13120 // If the assignment-expression [...] has array type A and no ref-qualifier
13121 // is present, e has type cv A
13122 if (VDecl && isa<DecompositionDecl>(Val: VDecl) &&
13123 Context.hasSameUnqualifiedType(T1: Type, T2: Context.getAutoDeductType()) &&
13124 DeduceInit->getType()->isConstantArrayType())
13125 return Context.getQualifiedType(T: DeduceInit->getType(),
13126 Qs: Type.getQualifiers());
13127
13128 QualType DeducedType;
13129 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13130 TemplateDeductionResult Result =
13131 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeduceInit, Result&: DeducedType, Info);
13132 if (Result != TemplateDeductionResult::Success &&
13133 Result != TemplateDeductionResult::AlreadyDiagnosed) {
13134 if (!IsInitCapture)
13135 DiagnoseAutoDeductionFailure(VDecl, Init: DeduceInit);
13136 else if (isa<InitListExpr>(Val: Init))
13137 Diag(Loc: Range.getBegin(),
13138 DiagID: diag::err_init_capture_deduction_failure_from_init_list)
13139 << VN
13140 << (DeduceInit->getType().isNull() ? TSI->getType()
13141 : DeduceInit->getType())
13142 << DeduceInit->getSourceRange();
13143 else
13144 Diag(Loc: Range.getBegin(), DiagID: diag::err_init_capture_deduction_failure)
13145 << VN << TSI->getType()
13146 << (DeduceInit->getType().isNull() ? TSI->getType()
13147 : DeduceInit->getType())
13148 << DeduceInit->getSourceRange();
13149 }
13150
13151 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13152 // 'id' instead of a specific object type prevents most of our usual
13153 // checks.
13154 // We only want to warn outside of template instantiations, though:
13155 // inside a template, the 'id' could have come from a parameter.
13156 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13157 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13158 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13159 Diag(Loc, DiagID: diag::warn_auto_var_is_id) << VN << Range;
13160 }
13161
13162 return DeducedType;
13163}
13164
13165bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13166 Expr *Init) {
13167 assert(!Init || !Init->containsErrors());
13168 QualType DeducedType = deduceVarTypeFromInitializer(
13169 VDecl, Name: VDecl->getDeclName(), Type: VDecl->getType(), TSI: VDecl->getTypeSourceInfo(),
13170 Range: VDecl->getSourceRange(), DirectInit, Init);
13171 if (DeducedType.isNull()) {
13172 VDecl->setInvalidDecl();
13173 return true;
13174 }
13175
13176 VDecl->setType(DeducedType);
13177 assert(VDecl->isLinkageValid());
13178
13179 // In ARC, infer lifetime.
13180 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: VDecl))
13181 VDecl->setInvalidDecl();
13182
13183 if (getLangOpts().OpenCL)
13184 deduceOpenCLAddressSpace(Decl: VDecl);
13185
13186 if (getLangOpts().HLSL)
13187 HLSL().deduceAddressSpace(Decl: VDecl);
13188
13189 // If this is a redeclaration, check that the type we just deduced matches
13190 // the previously declared type.
13191 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13192 // We never need to merge the type, because we cannot form an incomplete
13193 // array of auto, nor deduce such a type.
13194 MergeVarDeclTypes(New: VDecl, Old, /*MergeTypeWithPrevious*/ MergeTypeWithOld: false);
13195 }
13196
13197 // Check the deduced type is valid for a variable declaration.
13198 CheckVariableDeclarationType(NewVD: VDecl);
13199 return VDecl->isInvalidDecl();
13200}
13201
13202void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13203 SourceLocation Loc) {
13204 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Init))
13205 Init = EWC->getSubExpr();
13206
13207 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init))
13208 Init = CE->getSubExpr();
13209
13210 QualType InitType = Init->getType();
13211 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13212 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13213 "shouldn't be called if type doesn't have a non-trivial C struct");
13214 if (auto *ILE = dyn_cast<InitListExpr>(Val: Init)) {
13215 for (auto *I : ILE->inits()) {
13216 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13217 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13218 continue;
13219 SourceLocation SL = I->getExprLoc();
13220 checkNonTrivialCUnionInInitializer(Init: I, Loc: SL.isValid() ? SL : Loc);
13221 }
13222 return;
13223 }
13224
13225 if (isa<ImplicitValueInitExpr>(Val: Init)) {
13226 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13227 checkNonTrivialCUnion(QT: InitType, Loc,
13228 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
13229 NonTrivialKind: NTCUK_Init);
13230 } else {
13231 // Assume all other explicit initializers involving copying some existing
13232 // object.
13233 // TODO: ignore any explicit initializers where we can guarantee
13234 // copy-elision.
13235 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13236 checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NonTrivialCUnionContext::CopyInit,
13237 NonTrivialKind: NTCUK_Copy);
13238 }
13239}
13240
13241namespace {
13242
13243bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13244 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13245 // in the source code or implicitly by the compiler if it is in a union
13246 // defined in a system header and has non-trivial ObjC ownership
13247 // qualifications. We don't want those fields to participate in determining
13248 // whether the containing union is non-trivial.
13249 return FD->hasAttr<UnavailableAttr>();
13250}
13251
13252struct DiagNonTrivalCUnionDefaultInitializeVisitor
13253 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13254 void> {
13255 using Super =
13256 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13257 void>;
13258
13259 DiagNonTrivalCUnionDefaultInitializeVisitor(
13260 QualType OrigTy, SourceLocation OrigLoc,
13261 NonTrivialCUnionContext UseContext, Sema &S)
13262 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13263
13264 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13265 const FieldDecl *FD, bool InNonTrivialUnion) {
13266 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13267 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13268 Args&: InNonTrivialUnion);
13269 return Super::visitWithKind(PDIK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13270 }
13271
13272 void visitARCStrong(QualType QT, const FieldDecl *FD,
13273 bool InNonTrivialUnion) {
13274 if (InNonTrivialUnion)
13275 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13276 << 1 << 0 << QT << FD->getName();
13277 }
13278
13279 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13280 if (InNonTrivialUnion)
13281 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13282 << 1 << 0 << QT << FD->getName();
13283 }
13284
13285 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13286 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13287 if (RD->isUnion()) {
13288 if (OrigLoc.isValid()) {
13289 bool IsUnion = false;
13290 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13291 IsUnion = OrigRD->isUnion();
13292 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13293 << 0 << OrigTy << IsUnion << UseContext;
13294 // Reset OrigLoc so that this diagnostic is emitted only once.
13295 OrigLoc = SourceLocation();
13296 }
13297 InNonTrivialUnion = true;
13298 }
13299
13300 if (InNonTrivialUnion)
13301 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13302 << 0 << 0 << QT.getUnqualifiedType() << "";
13303
13304 for (const FieldDecl *FD : RD->fields())
13305 if (!shouldIgnoreForRecordTriviality(FD))
13306 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13307 }
13308
13309 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13310
13311 // The non-trivial C union type or the struct/union type that contains a
13312 // non-trivial C union.
13313 QualType OrigTy;
13314 SourceLocation OrigLoc;
13315 NonTrivialCUnionContext UseContext;
13316 Sema &S;
13317};
13318
13319struct DiagNonTrivalCUnionDestructedTypeVisitor
13320 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13321 using Super =
13322 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13323
13324 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13325 SourceLocation OrigLoc,
13326 NonTrivialCUnionContext UseContext,
13327 Sema &S)
13328 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13329
13330 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13331 const FieldDecl *FD, bool InNonTrivialUnion) {
13332 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13333 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13334 Args&: InNonTrivialUnion);
13335 return Super::visitWithKind(DK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13336 }
13337
13338 void visitARCStrong(QualType QT, const FieldDecl *FD,
13339 bool InNonTrivialUnion) {
13340 if (InNonTrivialUnion)
13341 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13342 << 1 << 1 << QT << FD->getName();
13343 }
13344
13345 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13346 if (InNonTrivialUnion)
13347 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13348 << 1 << 1 << QT << FD->getName();
13349 }
13350
13351 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13352 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13353 if (RD->isUnion()) {
13354 if (OrigLoc.isValid()) {
13355 bool IsUnion = false;
13356 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13357 IsUnion = OrigRD->isUnion();
13358 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13359 << 1 << OrigTy << IsUnion << UseContext;
13360 // Reset OrigLoc so that this diagnostic is emitted only once.
13361 OrigLoc = SourceLocation();
13362 }
13363 InNonTrivialUnion = true;
13364 }
13365
13366 if (InNonTrivialUnion)
13367 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13368 << 0 << 1 << QT.getUnqualifiedType() << "";
13369
13370 for (const FieldDecl *FD : RD->fields())
13371 if (!shouldIgnoreForRecordTriviality(FD))
13372 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13373 }
13374
13375 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13376 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13377 bool InNonTrivialUnion) {}
13378
13379 // The non-trivial C union type or the struct/union type that contains a
13380 // non-trivial C union.
13381 QualType OrigTy;
13382 SourceLocation OrigLoc;
13383 NonTrivialCUnionContext UseContext;
13384 Sema &S;
13385};
13386
13387struct DiagNonTrivalCUnionCopyVisitor
13388 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13389 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13390
13391 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13392 NonTrivialCUnionContext UseContext, Sema &S)
13393 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13394
13395 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13396 const FieldDecl *FD, bool InNonTrivialUnion) {
13397 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13398 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13399 Args&: InNonTrivialUnion);
13400 return Super::visitWithKind(PCK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13401 }
13402
13403 void visitARCStrong(QualType QT, const FieldDecl *FD,
13404 bool InNonTrivialUnion) {
13405 if (InNonTrivialUnion)
13406 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13407 << 1 << 2 << QT << FD->getName();
13408 }
13409
13410 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13411 if (InNonTrivialUnion)
13412 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13413 << 1 << 2 << QT << FD->getName();
13414 }
13415
13416 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13417 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13418 if (RD->isUnion()) {
13419 if (OrigLoc.isValid()) {
13420 bool IsUnion = false;
13421 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13422 IsUnion = OrigRD->isUnion();
13423 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13424 << 2 << OrigTy << IsUnion << UseContext;
13425 // Reset OrigLoc so that this diagnostic is emitted only once.
13426 OrigLoc = SourceLocation();
13427 }
13428 InNonTrivialUnion = true;
13429 }
13430
13431 if (InNonTrivialUnion)
13432 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13433 << 0 << 2 << QT.getUnqualifiedType() << "";
13434
13435 for (const FieldDecl *FD : RD->fields())
13436 if (!shouldIgnoreForRecordTriviality(FD))
13437 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13438 }
13439
13440 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13441 if (InNonTrivialUnion)
13442 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13443 << 1 << 2 << QT << FD->getName();
13444 }
13445
13446 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13447 const FieldDecl *FD, bool InNonTrivialUnion) {}
13448 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13449 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13450 bool InNonTrivialUnion) {}
13451
13452 // The non-trivial C union type or the struct/union type that contains a
13453 // non-trivial C union.
13454 QualType OrigTy;
13455 SourceLocation OrigLoc;
13456 NonTrivialCUnionContext UseContext;
13457 Sema &S;
13458};
13459
13460} // namespace
13461
13462void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13463 NonTrivialCUnionContext UseContext,
13464 unsigned NonTrivialKind) {
13465 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13466 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13467 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13468 "shouldn't be called if type doesn't have a non-trivial C union");
13469
13470 if ((NonTrivialKind & NTCUK_Init) &&
13471 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13472 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13473 .visit(FT: QT, Args: nullptr, Args: false);
13474 if ((NonTrivialKind & NTCUK_Destruct) &&
13475 QT.hasNonTrivialToPrimitiveDestructCUnion())
13476 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13477 .visit(FT: QT, Args: nullptr, Args: false);
13478 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13479 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13480 .visit(FT: QT, Args: nullptr, Args: false);
13481}
13482
13483bool Sema::GloballyUniqueObjectMightBeAccidentallyDuplicated(
13484 const VarDecl *Dcl) {
13485 if (!getLangOpts().CPlusPlus)
13486 return false;
13487
13488 // We only need to warn if the definition is in a header file, so wait to
13489 // diagnose until we've seen the definition.
13490 if (!Dcl->isThisDeclarationADefinition())
13491 return false;
13492
13493 // If an object is defined in a source file, its definition can't get
13494 // duplicated since it will never appear in more than one TU.
13495 if (Dcl->getASTContext().getSourceManager().isInMainFile(Loc: Dcl->getLocation()))
13496 return false;
13497
13498 // If the variable we're looking at is a static local, then we actually care
13499 // about the properties of the function containing it.
13500 const ValueDecl *Target = Dcl;
13501 // VarDecls and FunctionDecls have different functions for checking
13502 // inline-ness, and whether they were originally templated, so we have to
13503 // call the appropriate functions manually.
13504 bool TargetIsInline = Dcl->isInline();
13505 bool TargetWasTemplated =
13506 Dcl->getTemplateSpecializationKind() != TSK_Undeclared;
13507
13508 // Update the Target and TargetIsInline property if necessary
13509 if (Dcl->isStaticLocal()) {
13510 const DeclContext *Ctx = Dcl->getDeclContext();
13511 if (!Ctx)
13512 return false;
13513
13514 const FunctionDecl *FunDcl =
13515 dyn_cast_if_present<FunctionDecl>(Val: Ctx->getNonClosureAncestor());
13516 if (!FunDcl)
13517 return false;
13518
13519 Target = FunDcl;
13520 // IsInlined() checks for the C++ inline property
13521 TargetIsInline = FunDcl->isInlined();
13522 TargetWasTemplated =
13523 FunDcl->getTemplateSpecializationKind() != TSK_Undeclared;
13524 }
13525
13526 // Non-inline functions/variables can only legally appear in one TU
13527 // unless they were part of a template. Unfortunately, making complex
13528 // template instantiations visible is infeasible in practice, since
13529 // everything the template depends on also has to be visible. To avoid
13530 // giving impractical-to-fix warnings, don't warn if we're inside
13531 // something that was templated, even on inline stuff.
13532 if (!TargetIsInline || TargetWasTemplated)
13533 return false;
13534
13535 // If the object isn't hidden, the dynamic linker will prevent duplication.
13536 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13537
13538 // The target is "hidden" (from the dynamic linker) if:
13539 // 1. On posix, it has hidden visibility, or
13540 // 2. On windows, it has no import/export annotation, and neither does the
13541 // class which directly contains it.
13542 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13543 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13544 return false;
13545
13546 // If the variable isn't directly annotated, check to see if it's a member
13547 // of an annotated class.
13548 const CXXRecordDecl *Ctx =
13549 dyn_cast<CXXRecordDecl>(Val: Target->getDeclContext());
13550 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13551 return false;
13552
13553 } else if (Lnk.getVisibility() != HiddenVisibility) {
13554 // Posix case
13555 return false;
13556 }
13557
13558 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13559 if (!isExternalFormalLinkage(L: Lnk.getLinkage()))
13560 return false;
13561
13562 return true;
13563}
13564
13565// Determine whether the object seems mutable for the purpose of diagnosing
13566// possible unique object duplication, i.e. non-const-qualified, and
13567// not an always-constant type like a function.
13568// Not perfect: doesn't account for mutable members, for example, or
13569// elements of container types.
13570// For nested pointers, any individual level being non-const is sufficient.
13571static bool looksMutable(QualType T, const ASTContext &Ctx) {
13572 T = T.getNonReferenceType();
13573 if (T->isFunctionType())
13574 return false;
13575 if (!T.isConstant(Ctx))
13576 return true;
13577 if (T->isPointerType())
13578 return looksMutable(T: T->getPointeeType(), Ctx);
13579 return false;
13580}
13581
13582void Sema::DiagnoseUniqueObjectDuplication(const VarDecl *VD) {
13583 // If this object has external linkage and hidden visibility, it might be
13584 // duplicated when built into a shared library, which causes problems if it's
13585 // mutable (since the copies won't be in sync) or its initialization has side
13586 // effects (since it will run once per copy instead of once globally).
13587
13588 // Don't diagnose if we're inside a template, because it's not practical to
13589 // fix the warning in most cases.
13590 if (!VD->isTemplated() &&
13591 GloballyUniqueObjectMightBeAccidentallyDuplicated(Dcl: VD)) {
13592
13593 QualType Type = VD->getType();
13594 if (looksMutable(T: Type, Ctx: VD->getASTContext())) {
13595 Diag(Loc: VD->getLocation(), DiagID: diag::warn_possible_object_duplication_mutable)
13596 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13597 }
13598
13599 // To keep false positives low, only warn if we're certain that the
13600 // initializer has side effects. Don't warn on operator new, since a mutable
13601 // pointer will trigger the previous warning, and an immutable pointer
13602 // getting duplicated just results in a little extra memory usage.
13603 const Expr *Init = VD->getAnyInitializer();
13604 if (Init &&
13605 Init->HasSideEffects(Ctx: VD->getASTContext(),
13606 /*IncludePossibleEffects=*/false) &&
13607 !isa<CXXNewExpr>(Val: Init->IgnoreParenImpCasts())) {
13608 Diag(Loc: Init->getExprLoc(), DiagID: diag::warn_possible_object_duplication_init)
13609 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13610 }
13611 }
13612}
13613
13614void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13615 // If there is no declaration, there was an error parsing it. Just ignore
13616 // the initializer.
13617 if (!RealDecl) {
13618 return;
13619 }
13620
13621 if (auto *Method = dyn_cast<CXXMethodDecl>(Val: RealDecl)) {
13622 if (!Method->isInvalidDecl()) {
13623 // Pure-specifiers are handled in ActOnPureSpecifier.
13624 Diag(Loc: Method->getLocation(), DiagID: diag::err_member_function_initialization)
13625 << Method->getDeclName() << Init->getSourceRange();
13626 Method->setInvalidDecl();
13627 }
13628 return;
13629 }
13630
13631 VarDecl *VDecl = dyn_cast<VarDecl>(Val: RealDecl);
13632 if (!VDecl) {
13633 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13634 Diag(Loc: RealDecl->getLocation(), DiagID: diag::err_illegal_initializer);
13635 RealDecl->setInvalidDecl();
13636 return;
13637 }
13638
13639 if (VDecl->isInvalidDecl()) {
13640 ExprResult Recovery =
13641 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init});
13642 if (Expr *E = Recovery.get())
13643 VDecl->setInit(E);
13644 return;
13645 }
13646
13647 // WebAssembly tables can't be used to initialise a variable.
13648 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13649 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_wasm_table_art) << 0;
13650 VDecl->setInvalidDecl();
13651 return;
13652 }
13653
13654 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13655 if (VDecl->getType()->isUndeducedType()) {
13656 if (Init->containsErrors()) {
13657 // Invalidate the decl as we don't know the type for recovery-expr yet.
13658 RealDecl->setInvalidDecl();
13659 VDecl->setInit(Init);
13660 return;
13661 }
13662
13663 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
13664 return;
13665 }
13666
13667 // dllimport cannot be used on variable definitions.
13668 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13669 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_attribute_dllimport_data_definition);
13670 VDecl->setInvalidDecl();
13671 return;
13672 }
13673
13674 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13675 // the identifier has external or internal linkage, the declaration shall
13676 // have no initializer for the identifier.
13677 // C++14 [dcl.init]p5 is the same restriction for C++.
13678 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13679 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_block_extern_cant_init);
13680 VDecl->setInvalidDecl();
13681 return;
13682 }
13683
13684 if (!VDecl->getType()->isDependentType()) {
13685 // A definition must end up with a complete type, which means it must be
13686 // complete with the restriction that an array type might be completed by
13687 // the initializer; note that later code assumes this restriction.
13688 QualType BaseDeclType = VDecl->getType();
13689 if (const ArrayType *Array = Context.getAsIncompleteArrayType(T: BaseDeclType))
13690 BaseDeclType = Array->getElementType();
13691 if (RequireCompleteType(Loc: VDecl->getLocation(), T: BaseDeclType,
13692 DiagID: diag::err_typecheck_decl_incomplete_type)) {
13693 RealDecl->setInvalidDecl();
13694 return;
13695 }
13696
13697 // The variable can not have an abstract class type.
13698 if (RequireNonAbstractType(Loc: VDecl->getLocation(), T: VDecl->getType(),
13699 DiagID: diag::err_abstract_type_in_decl,
13700 Args: AbstractVariableType))
13701 VDecl->setInvalidDecl();
13702 }
13703
13704 // C++ [module.import/6] external definitions are not permitted in header
13705 // units.
13706 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13707 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13708 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13709 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(Val: VDecl) &&
13710 !VDecl->getInstantiatedFromStaticDataMember()) {
13711 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
13712 VDecl->setInvalidDecl();
13713 }
13714
13715 // If adding the initializer will turn this declaration into a definition,
13716 // and we already have a definition for this variable, diagnose or otherwise
13717 // handle the situation.
13718 if (VarDecl *Def = VDecl->getDefinition())
13719 if (Def != VDecl &&
13720 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13721 !VDecl->isThisDeclarationADemotedDefinition() &&
13722 checkVarDeclRedefinition(Old: Def, New: VDecl))
13723 return;
13724
13725 if (getLangOpts().CPlusPlus) {
13726 // C++ [class.static.data]p4
13727 // If a static data member is of const integral or const
13728 // enumeration type, its declaration in the class definition can
13729 // specify a constant-initializer which shall be an integral
13730 // constant expression (5.19). In that case, the member can appear
13731 // in integral constant expressions. The member shall still be
13732 // defined in a namespace scope if it is used in the program and the
13733 // namespace scope definition shall not contain an initializer.
13734 //
13735 // We already performed a redefinition check above, but for static
13736 // data members we also need to check whether there was an in-class
13737 // declaration with an initializer.
13738 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13739 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_static_data_member_reinitialization)
13740 << VDecl->getDeclName();
13741 Diag(Loc: VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13742 DiagID: diag::note_previous_initializer)
13743 << 0;
13744 return;
13745 }
13746
13747 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer)) {
13748 VDecl->setInvalidDecl();
13749 return;
13750 }
13751 }
13752
13753 // If the variable has an initializer and local storage, check whether
13754 // anything jumps over the initialization.
13755 if (VDecl->hasLocalStorage())
13756 setFunctionHasBranchProtectedScope();
13757
13758 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13759 // a kernel function cannot be initialized."
13760 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13761 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_local_cant_init);
13762 VDecl->setInvalidDecl();
13763 return;
13764 }
13765
13766 // The LoaderUninitialized attribute acts as a definition (of undef).
13767 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13768 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_loader_uninitialized_cant_init);
13769 VDecl->setInvalidDecl();
13770 return;
13771 }
13772
13773 if (getLangOpts().HLSL)
13774 if (!HLSL().handleInitialization(VDecl, Init))
13775 return;
13776
13777 // Get the decls type and save a reference for later, since
13778 // CheckInitializerTypes may change it.
13779 QualType DclT = VDecl->getType(), SavT = DclT;
13780
13781 // Expressions default to 'id' when we're in a debugger
13782 // and we are assigning it to a variable of Objective-C pointer type.
13783 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13784 Init->getType() == Context.UnknownAnyTy) {
13785 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13786 if (!Result.isUsable()) {
13787 VDecl->setInvalidDecl();
13788 return;
13789 }
13790 Init = Result.get();
13791 }
13792
13793 // Perform the initialization.
13794 bool InitializedFromParenListExpr = false;
13795 bool IsParenListInit = false;
13796 if (!VDecl->isInvalidDecl()) {
13797 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13798 InitializationKind Kind = InitializationKind::CreateForInit(
13799 Loc: VDecl->getLocation(), DirectInit, Init);
13800
13801 MultiExprArg Args = Init;
13802 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Val: Init)) {
13803 Args =
13804 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
13805 InitializedFromParenListExpr = true;
13806 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Val: Init)) {
13807 Args = CXXDirectInit->getInitExprs();
13808 InitializedFromParenListExpr = true;
13809 }
13810
13811 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13812 /*TopLevelOfInitList=*/false,
13813 /*TreatUnavailableAsInvalid=*/false);
13814 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args, ResultType: &DclT);
13815 if (!Result.isUsable()) {
13816 // If the provided initializer fails to initialize the var decl,
13817 // we attach a recovery expr for better recovery.
13818 auto RecoveryExpr =
13819 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: Args);
13820 if (RecoveryExpr.get())
13821 VDecl->setInit(RecoveryExpr.get());
13822 // In general, for error recovery purposes, the initializer doesn't play
13823 // part in the valid bit of the declaration. There are a few exceptions:
13824 // 1) if the var decl has a deduced auto type, and the type cannot be
13825 // deduced by an invalid initializer;
13826 // 2) if the var decl is a decomposition decl with a non-deduced type,
13827 // and the initialization fails (e.g. `int [a] = {1, 2};`);
13828 // Case 1) was already handled elsewhere.
13829 if (isa<DecompositionDecl>(Val: VDecl)) // Case 2)
13830 VDecl->setInvalidDecl();
13831 return;
13832 }
13833
13834 Init = Result.getAs<Expr>();
13835 IsParenListInit = !InitSeq.steps().empty() &&
13836 InitSeq.step_begin()->Kind ==
13837 InitializationSequence::SK_ParenthesizedListInit;
13838 QualType VDeclType = VDecl->getType();
13839 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
13840 !VDeclType->isDependentType() &&
13841 Context.getAsIncompleteArrayType(T: VDeclType) &&
13842 Context.getAsIncompleteArrayType(T: Init->getType())) {
13843 // Bail out if it is not possible to deduce array size from the
13844 // initializer.
13845 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
13846 << VDeclType;
13847 VDecl->setInvalidDecl();
13848 return;
13849 }
13850 }
13851
13852 // Check for self-references within variable initializers.
13853 // Variables declared within a function/method body (except for references)
13854 // are handled by a dataflow analysis.
13855 // This is undefined behavior in C++, but valid in C.
13856 if (getLangOpts().CPlusPlus)
13857 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13858 VDecl->getType()->isReferenceType())
13859 CheckSelfReference(S&: *this, OrigDecl: RealDecl, E: Init, DirectInit);
13860
13861 // If the type changed, it means we had an incomplete type that was
13862 // completed by the initializer. For example:
13863 // int ary[] = { 1, 3, 5 };
13864 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13865 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13866 VDecl->setType(DclT);
13867
13868 if (!VDecl->isInvalidDecl()) {
13869 checkUnsafeAssigns(Loc: VDecl->getLocation(), LHS: VDecl->getType(), RHS: Init);
13870
13871 if (VDecl->hasAttr<BlocksAttr>())
13872 ObjC().checkRetainCycles(Var: VDecl, Init);
13873
13874 // It is safe to assign a weak reference into a strong variable.
13875 // Although this code can still have problems:
13876 // id x = self.weakProp;
13877 // id y = self.weakProp;
13878 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13879 // paths through the function. This should be revisited if
13880 // -Wrepeated-use-of-weak is made flow-sensitive.
13881 if (FunctionScopeInfo *FSI = getCurFunction())
13882 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13883 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
13884 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
13885 Loc: Init->getBeginLoc()))
13886 FSI->markSafeWeakUse(E: Init);
13887 }
13888
13889 // The initialization is usually a full-expression.
13890 //
13891 // FIXME: If this is a braced initialization of an aggregate, it is not
13892 // an expression, and each individual field initializer is a separate
13893 // full-expression. For instance, in:
13894 //
13895 // struct Temp { ~Temp(); };
13896 // struct S { S(Temp); };
13897 // struct T { S a, b; } t = { Temp(), Temp() }
13898 //
13899 // we should destroy the first Temp before constructing the second.
13900 ExprResult Result =
13901 ActOnFinishFullExpr(Expr: Init, CC: VDecl->getLocation(),
13902 /*DiscardedValue*/ false, IsConstexpr: VDecl->isConstexpr());
13903 if (!Result.isUsable()) {
13904 VDecl->setInvalidDecl();
13905 return;
13906 }
13907 Init = Result.get();
13908
13909 // Attach the initializer to the decl.
13910 VDecl->setInit(Init);
13911
13912 if (VDecl->isLocalVarDecl()) {
13913 // Don't check the initializer if the declaration is malformed.
13914 if (VDecl->isInvalidDecl()) {
13915 // do nothing
13916
13917 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13918 // This is true even in C++ for OpenCL.
13919 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13920 CheckForConstantInitializer(Init);
13921
13922 // Otherwise, C++ does not restrict the initializer.
13923 } else if (getLangOpts().CPlusPlus) {
13924 // do nothing
13925
13926 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13927 // static storage duration shall be constant expressions or string literals.
13928 } else if (VDecl->getStorageClass() == SC_Static) {
13929 CheckForConstantInitializer(Init);
13930
13931 // C89 is stricter than C99 for aggregate initializers.
13932 // C89 6.5.7p3: All the expressions [...] in an initializer list
13933 // for an object that has aggregate or union type shall be
13934 // constant expressions.
13935 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13936 isa<InitListExpr>(Val: Init)) {
13937 CheckForConstantInitializer(Init, DiagID: diag::ext_aggregate_init_not_constant);
13938 }
13939
13940 if (auto *E = dyn_cast<ExprWithCleanups>(Val: Init))
13941 if (auto *BE = dyn_cast<BlockExpr>(Val: E->getSubExpr()->IgnoreParens()))
13942 if (VDecl->hasLocalStorage())
13943 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13944 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13945 VDecl->getLexicalDeclContext()->isRecord()) {
13946 // This is an in-class initialization for a static data member, e.g.,
13947 //
13948 // struct S {
13949 // static const int value = 17;
13950 // };
13951
13952 // C++ [class.mem]p4:
13953 // A member-declarator can contain a constant-initializer only
13954 // if it declares a static member (9.4) of const integral or
13955 // const enumeration type, see 9.4.2.
13956 //
13957 // C++11 [class.static.data]p3:
13958 // If a non-volatile non-inline const static data member is of integral
13959 // or enumeration type, its declaration in the class definition can
13960 // specify a brace-or-equal-initializer in which every initializer-clause
13961 // that is an assignment-expression is a constant expression. A static
13962 // data member of literal type can be declared in the class definition
13963 // with the constexpr specifier; if so, its declaration shall specify a
13964 // brace-or-equal-initializer in which every initializer-clause that is
13965 // an assignment-expression is a constant expression.
13966
13967 // Do nothing on dependent types.
13968 if (DclT->isDependentType()) {
13969
13970 // Allow any 'static constexpr' members, whether or not they are of literal
13971 // type. We separately check that every constexpr variable is of literal
13972 // type.
13973 } else if (VDecl->isConstexpr()) {
13974
13975 // Require constness.
13976 } else if (!DclT.isConstQualified()) {
13977 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_non_const)
13978 << Init->getSourceRange();
13979 VDecl->setInvalidDecl();
13980
13981 // We allow integer constant expressions in all cases.
13982 } else if (DclT->isIntegralOrEnumerationType()) {
13983 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
13984 // In C++11, a non-constexpr const static data member with an
13985 // in-class initializer cannot be volatile.
13986 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_volatile);
13987
13988 // We allow foldable floating-point constants as an extension.
13989 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13990 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13991 // it anyway and provide a fixit to add the 'constexpr'.
13992 if (getLangOpts().CPlusPlus11) {
13993 Diag(Loc: VDecl->getLocation(),
13994 DiagID: diag::ext_in_class_initializer_float_type_cxx11)
13995 << DclT << Init->getSourceRange();
13996 Diag(Loc: VDecl->getBeginLoc(),
13997 DiagID: diag::note_in_class_initializer_float_type_cxx11)
13998 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
13999 } else {
14000 Diag(Loc: VDecl->getLocation(), DiagID: diag::ext_in_class_initializer_float_type)
14001 << DclT << Init->getSourceRange();
14002
14003 if (!Init->isValueDependent() && !Init->isEvaluatable(Ctx: Context)) {
14004 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_in_class_initializer_non_constant)
14005 << Init->getSourceRange();
14006 VDecl->setInvalidDecl();
14007 }
14008 }
14009
14010 // Suggest adding 'constexpr' in C++11 for literal types.
14011 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Ctx: Context)) {
14012 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_literal_type)
14013 << DclT << Init->getSourceRange()
14014 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14015 VDecl->setConstexpr(true);
14016
14017 } else {
14018 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_bad_type)
14019 << DclT << Init->getSourceRange();
14020 VDecl->setInvalidDecl();
14021 }
14022 } else if (VDecl->isFileVarDecl()) {
14023 // In C, extern is typically used to avoid tentative definitions when
14024 // declaring variables in headers, but adding an initializer makes it a
14025 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14026 // In C++, extern is often used to give implicitly static const variables
14027 // external linkage, so don't warn in that case. If selectany is present,
14028 // this might be header code intended for C and C++ inclusion, so apply the
14029 // C++ rules.
14030 if (VDecl->getStorageClass() == SC_Extern &&
14031 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14032 !Context.getBaseElementType(QT: VDecl->getType()).isConstQualified()) &&
14033 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14034 !isTemplateInstantiation(Kind: VDecl->getTemplateSpecializationKind()))
14035 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_extern_init);
14036
14037 // In Microsoft C++ mode, a const variable defined in namespace scope has
14038 // external linkage by default if the variable is declared with
14039 // __declspec(dllexport).
14040 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14041 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
14042 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14043 VDecl->setStorageClass(SC_Extern);
14044
14045 // C99 6.7.8p4. All file scoped initializers need to be constant.
14046 // Avoid duplicate diagnostics for constexpr variables.
14047 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14048 !VDecl->isConstexpr())
14049 CheckForConstantInitializer(Init);
14050 }
14051
14052 QualType InitType = Init->getType();
14053 if (!InitType.isNull() &&
14054 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
14055 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
14056 checkNonTrivialCUnionInInitializer(Init, Loc: Init->getExprLoc());
14057
14058 // We will represent direct-initialization similarly to copy-initialization:
14059 // int x(1); -as-> int x = 1;
14060 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14061 //
14062 // Clients that want to distinguish between the two forms, can check for
14063 // direct initializer using VarDecl::getInitStyle().
14064 // A major benefit is that clients that don't particularly care about which
14065 // exactly form was it (like the CodeGen) can handle both cases without
14066 // special case code.
14067
14068 // C++ 8.5p11:
14069 // The form of initialization (using parentheses or '=') matters
14070 // when the entity being initialized has class type.
14071 if (InitializedFromParenListExpr) {
14072 assert(DirectInit && "Call-style initializer must be direct init.");
14073 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14074 : VarDecl::CallInit);
14075 } else if (DirectInit) {
14076 // This must be list-initialization. No other way is direct-initialization.
14077 VDecl->setInitStyle(VarDecl::ListInit);
14078 }
14079
14080 if (LangOpts.OpenMP &&
14081 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14082 VDecl->isFileVarDecl())
14083 DeclsToCheckForDeferredDiags.insert(X: VDecl);
14084 CheckCompleteVariableDeclaration(VD: VDecl);
14085
14086 if (LangOpts.OpenACC && !InitType.isNull())
14087 OpenACC().ActOnVariableInit(VD: VDecl, InitType);
14088}
14089
14090void Sema::ActOnInitializerError(Decl *D) {
14091 // Our main concern here is re-establishing invariants like "a
14092 // variable's type is either dependent or complete".
14093 if (!D || D->isInvalidDecl()) return;
14094
14095 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14096 if (!VD) return;
14097
14098 // Bindings are not usable if we can't make sense of the initializer.
14099 if (auto *DD = dyn_cast<DecompositionDecl>(Val: D))
14100 for (auto *BD : DD->bindings())
14101 BD->setInvalidDecl();
14102
14103 // Auto types are meaningless if we can't make sense of the initializer.
14104 if (VD->getType()->isUndeducedType()) {
14105 D->setInvalidDecl();
14106 return;
14107 }
14108
14109 QualType Ty = VD->getType();
14110 if (Ty->isDependentType()) return;
14111
14112 // Require a complete type.
14113 if (RequireCompleteType(Loc: VD->getLocation(),
14114 T: Context.getBaseElementType(QT: Ty),
14115 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14116 VD->setInvalidDecl();
14117 return;
14118 }
14119
14120 // Require a non-abstract type.
14121 if (RequireNonAbstractType(Loc: VD->getLocation(), T: Ty,
14122 DiagID: diag::err_abstract_type_in_decl,
14123 Args: AbstractVariableType)) {
14124 VD->setInvalidDecl();
14125 return;
14126 }
14127
14128 // Don't bother complaining about constructors or destructors,
14129 // though.
14130}
14131
14132void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
14133 // If there is no declaration, there was an error parsing it. Just ignore it.
14134 if (!RealDecl)
14135 return;
14136
14137 if (VarDecl *Var = dyn_cast<VarDecl>(Val: RealDecl)) {
14138 QualType Type = Var->getType();
14139
14140 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14141 if (isa<DecompositionDecl>(Val: RealDecl)) {
14142 Diag(Loc: Var->getLocation(), DiagID: diag::err_decomp_decl_requires_init) << Var;
14143 Var->setInvalidDecl();
14144 return;
14145 }
14146
14147 if (Type->isUndeducedType() &&
14148 DeduceVariableDeclarationType(VDecl: Var, DirectInit: false, Init: nullptr))
14149 return;
14150
14151 // C++11 [class.static.data]p3: A static data member can be declared with
14152 // the constexpr specifier; if so, its declaration shall specify
14153 // a brace-or-equal-initializer.
14154 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14155 // the definition of a variable [...] or the declaration of a static data
14156 // member.
14157 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14158 !Var->isThisDeclarationADemotedDefinition()) {
14159 if (Var->isStaticDataMember()) {
14160 // C++1z removes the relevant rule; the in-class declaration is always
14161 // a definition there.
14162 if (!getLangOpts().CPlusPlus17 &&
14163 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14164 Diag(Loc: Var->getLocation(),
14165 DiagID: diag::err_constexpr_static_mem_var_requires_init)
14166 << Var;
14167 Var->setInvalidDecl();
14168 return;
14169 }
14170 } else {
14171 Diag(Loc: Var->getLocation(), DiagID: diag::err_invalid_constexpr_var_decl);
14172 Var->setInvalidDecl();
14173 return;
14174 }
14175 }
14176
14177 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14178 // be initialized.
14179 if (!Var->isInvalidDecl() &&
14180 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14181 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14182 bool HasConstExprDefaultConstructor = false;
14183 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14184 for (auto *Ctor : RD->ctors()) {
14185 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14186 Ctor->getMethodQualifiers().getAddressSpace() ==
14187 LangAS::opencl_constant) {
14188 HasConstExprDefaultConstructor = true;
14189 }
14190 }
14191 }
14192 if (!HasConstExprDefaultConstructor) {
14193 Diag(Loc: Var->getLocation(), DiagID: diag::err_opencl_constant_no_init);
14194 Var->setInvalidDecl();
14195 return;
14196 }
14197 }
14198
14199 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14200 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14201 Diag(Loc: Var->getLocation(), DiagID: diag::err_specialization_const);
14202 Var->setInvalidDecl();
14203 return;
14204 }
14205
14206 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14207 if (Var->getStorageClass() == SC_Extern) {
14208 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_extern_decl)
14209 << Var;
14210 Var->setInvalidDecl();
14211 return;
14212 }
14213 if (RequireCompleteType(Loc: Var->getLocation(), T: Var->getType(),
14214 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14215 Var->setInvalidDecl();
14216 return;
14217 }
14218 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14219 if (!RD->hasTrivialDefaultConstructor()) {
14220 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_trivial_ctor);
14221 Var->setInvalidDecl();
14222 return;
14223 }
14224 }
14225 // The declaration is uninitialized, no need for further checks.
14226 return;
14227 }
14228
14229 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14230 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14231 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14232 checkNonTrivialCUnion(QT: Var->getType(), Loc: Var->getLocation(),
14233 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
14234 NonTrivialKind: NTCUK_Init);
14235
14236 switch (DefKind) {
14237 case VarDecl::Definition:
14238 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14239 break;
14240
14241 // We have an out-of-line definition of a static data member
14242 // that has an in-class initializer, so we type-check this like
14243 // a declaration.
14244 //
14245 [[fallthrough]];
14246
14247 case VarDecl::DeclarationOnly:
14248 // It's only a declaration.
14249
14250 // Block scope. C99 6.7p7: If an identifier for an object is
14251 // declared with no linkage (C99 6.2.2p6), the type for the
14252 // object shall be complete.
14253 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14254 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14255 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14256 DiagID: diag::err_typecheck_decl_incomplete_type))
14257 Var->setInvalidDecl();
14258
14259 // Make sure that the type is not abstract.
14260 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14261 RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14262 DiagID: diag::err_abstract_type_in_decl,
14263 Args: AbstractVariableType))
14264 Var->setInvalidDecl();
14265 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14266 Var->getStorageClass() == SC_PrivateExtern) {
14267 Diag(Loc: Var->getLocation(), DiagID: diag::warn_private_extern);
14268 Diag(Loc: Var->getLocation(), DiagID: diag::note_private_extern);
14269 }
14270
14271 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14272 !Var->isInvalidDecl())
14273 ExternalDeclarations.push_back(Elt: Var);
14274
14275 return;
14276
14277 case VarDecl::TentativeDefinition:
14278 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14279 // object that has file scope without an initializer, and without a
14280 // storage-class specifier or with the storage-class specifier "static",
14281 // constitutes a tentative definition. Note: A tentative definition with
14282 // external linkage is valid (C99 6.2.2p5).
14283 if (!Var->isInvalidDecl()) {
14284 if (const IncompleteArrayType *ArrayT
14285 = Context.getAsIncompleteArrayType(T: Type)) {
14286 if (RequireCompleteSizedType(
14287 Loc: Var->getLocation(), T: ArrayT->getElementType(),
14288 DiagID: diag::err_array_incomplete_or_sizeless_type))
14289 Var->setInvalidDecl();
14290 }
14291 if (Var->getStorageClass() == SC_Static) {
14292 // C99 6.9.2p3: If the declaration of an identifier for an object is
14293 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14294 // declared type shall not be an incomplete type.
14295 // NOTE: code such as the following
14296 // static struct s;
14297 // struct s { int a; };
14298 // is accepted by gcc. Hence here we issue a warning instead of
14299 // an error and we do not invalidate the static declaration.
14300 // NOTE: to avoid multiple warnings, only check the first declaration.
14301 if (Var->isFirstDecl())
14302 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14303 DiagID: diag::ext_typecheck_decl_incomplete_type,
14304 Args: Type->isArrayType());
14305 }
14306 }
14307
14308 // Record the tentative definition; we're done.
14309 if (!Var->isInvalidDecl())
14310 TentativeDefinitions.push_back(LocalValue: Var);
14311 return;
14312 }
14313
14314 // Provide a specific diagnostic for uninitialized variable
14315 // definitions with incomplete array type.
14316 if (Type->isIncompleteArrayType()) {
14317 if (Var->isConstexpr())
14318 Diag(Loc: Var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
14319 << Var;
14320 else
14321 Diag(Loc: Var->getLocation(),
14322 DiagID: diag::err_typecheck_incomplete_array_needs_initializer);
14323 Var->setInvalidDecl();
14324 return;
14325 }
14326
14327 // Provide a specific diagnostic for uninitialized variable
14328 // definitions with reference type.
14329 if (Type->isReferenceType()) {
14330 Diag(Loc: Var->getLocation(), DiagID: diag::err_reference_var_requires_init)
14331 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14332 return;
14333 }
14334
14335 // Do not attempt to type-check the default initializer for a
14336 // variable with dependent type.
14337 if (Type->isDependentType())
14338 return;
14339
14340 if (Var->isInvalidDecl())
14341 return;
14342
14343 if (!Var->hasAttr<AliasAttr>()) {
14344 if (RequireCompleteType(Loc: Var->getLocation(),
14345 T: Context.getBaseElementType(QT: Type),
14346 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14347 Var->setInvalidDecl();
14348 return;
14349 }
14350 } else {
14351 return;
14352 }
14353
14354 // The variable can not have an abstract class type.
14355 if (RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14356 DiagID: diag::err_abstract_type_in_decl,
14357 Args: AbstractVariableType)) {
14358 Var->setInvalidDecl();
14359 return;
14360 }
14361
14362 // In C, if the definition is const-qualified and has no initializer, it
14363 // is left uninitialized unless it has static or thread storage duration.
14364 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14365 unsigned DiagID = diag::warn_default_init_const_unsafe;
14366 if (Var->getStorageDuration() == SD_Static ||
14367 Var->getStorageDuration() == SD_Thread)
14368 DiagID = diag::warn_default_init_const;
14369
14370 bool EmitCppCompat = !Diags.isIgnored(
14371 DiagID: diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14372 Loc: Var->getLocation());
14373
14374 Diag(Loc: Var->getLocation(), DiagID) << Type << EmitCppCompat;
14375 }
14376
14377 // Check for jumps past the implicit initializer. C++0x
14378 // clarifies that this applies to a "variable with automatic
14379 // storage duration", not a "local variable".
14380 // C++11 [stmt.dcl]p3
14381 // A program that jumps from a point where a variable with automatic
14382 // storage duration is not in scope to a point where it is in scope is
14383 // ill-formed unless the variable has scalar type, class type with a
14384 // trivial default constructor and a trivial destructor, a cv-qualified
14385 // version of one of these types, or an array of one of the preceding
14386 // types and is declared without an initializer.
14387 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14388 if (const RecordType *Record
14389 = Context.getBaseElementType(QT: Type)->getAs<RecordType>()) {
14390 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record->getDecl());
14391 // Mark the function (if we're in one) for further checking even if the
14392 // looser rules of C++11 do not require such checks, so that we can
14393 // diagnose incompatibilities with C++98.
14394 if (!CXXRecord->isPOD())
14395 setFunctionHasBranchProtectedScope();
14396 }
14397 }
14398 // In OpenCL, we can't initialize objects in the __local address space,
14399 // even implicitly, so don't synthesize an implicit initializer.
14400 if (getLangOpts().OpenCL &&
14401 Var->getType().getAddressSpace() == LangAS::opencl_local)
14402 return;
14403
14404 // Handle HLSL uninitialized decls
14405 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(D: Var))
14406 return;
14407
14408 // HLSL input variables are expected to be externally initialized, even
14409 // when marked `static`.
14410 if (getLangOpts().HLSL &&
14411 Var->getType().getAddressSpace() == LangAS::hlsl_input)
14412 return;
14413
14414 // C++03 [dcl.init]p9:
14415 // If no initializer is specified for an object, and the
14416 // object is of (possibly cv-qualified) non-POD class type (or
14417 // array thereof), the object shall be default-initialized; if
14418 // the object is of const-qualified type, the underlying class
14419 // type shall have a user-declared default
14420 // constructor. Otherwise, if no initializer is specified for
14421 // a non- static object, the object and its subobjects, if
14422 // any, have an indeterminate initial value); if the object
14423 // or any of its subobjects are of const-qualified type, the
14424 // program is ill-formed.
14425 // C++0x [dcl.init]p11:
14426 // If no initializer is specified for an object, the object is
14427 // default-initialized; [...].
14428 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14429 InitializationKind Kind
14430 = InitializationKind::CreateDefault(InitLoc: Var->getLocation());
14431
14432 InitializationSequence InitSeq(*this, Entity, Kind, {});
14433 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: {});
14434
14435 if (Init.get()) {
14436 Var->setInit(MaybeCreateExprWithCleanups(SubExpr: Init.get()));
14437 // This is important for template substitution.
14438 Var->setInitStyle(VarDecl::CallInit);
14439 } else if (Init.isInvalid()) {
14440 // If default-init fails, attach a recovery-expr initializer to track
14441 // that initialization was attempted and failed.
14442 auto RecoveryExpr =
14443 CreateRecoveryExpr(Begin: Var->getLocation(), End: Var->getLocation(), SubExprs: {});
14444 if (RecoveryExpr.get())
14445 Var->setInit(RecoveryExpr.get());
14446 }
14447
14448 CheckCompleteVariableDeclaration(VD: Var);
14449 }
14450}
14451
14452void Sema::ActOnCXXForRangeDecl(Decl *D) {
14453 // If there is no declaration, there was an error parsing it. Ignore it.
14454 if (!D)
14455 return;
14456
14457 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14458 if (!VD) {
14459 Diag(Loc: D->getLocation(), DiagID: diag::err_for_range_decl_must_be_var);
14460 D->setInvalidDecl();
14461 return;
14462 }
14463
14464 VD->setCXXForRangeDecl(true);
14465
14466 // for-range-declaration cannot be given a storage class specifier.
14467 int Error = -1;
14468 switch (VD->getStorageClass()) {
14469 case SC_None:
14470 break;
14471 case SC_Extern:
14472 Error = 0;
14473 break;
14474 case SC_Static:
14475 Error = 1;
14476 break;
14477 case SC_PrivateExtern:
14478 Error = 2;
14479 break;
14480 case SC_Auto:
14481 Error = 3;
14482 break;
14483 case SC_Register:
14484 Error = 4;
14485 break;
14486 }
14487
14488 // for-range-declaration cannot be given a storage class specifier con't.
14489 switch (VD->getTSCSpec()) {
14490 case TSCS_thread_local:
14491 Error = 6;
14492 break;
14493 case TSCS___thread:
14494 case TSCS__Thread_local:
14495 case TSCS_unspecified:
14496 break;
14497 }
14498
14499 if (Error != -1) {
14500 Diag(Loc: VD->getOuterLocStart(), DiagID: diag::err_for_range_storage_class)
14501 << VD << Error;
14502 D->setInvalidDecl();
14503 }
14504}
14505
14506StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
14507 IdentifierInfo *Ident,
14508 ParsedAttributes &Attrs) {
14509 // C++1y [stmt.iter]p1:
14510 // A range-based for statement of the form
14511 // for ( for-range-identifier : for-range-initializer ) statement
14512 // is equivalent to
14513 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14514 DeclSpec DS(Attrs.getPool().getFactory());
14515
14516 const char *PrevSpec;
14517 unsigned DiagID;
14518 DS.SetTypeSpecType(T: DeclSpec::TST_auto, Loc: IdentLoc, PrevSpec, DiagID,
14519 Policy: getPrintingPolicy());
14520
14521 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14522 D.SetIdentifier(Id: Ident, IdLoc: IdentLoc);
14523 D.takeAttributes(attrs&: Attrs);
14524
14525 D.AddTypeInfo(TI: DeclaratorChunk::getReference(TypeQuals: 0, Loc: IdentLoc, /*lvalue*/ false),
14526 EndLoc: IdentLoc);
14527 Decl *Var = ActOnDeclarator(S, D);
14528 cast<VarDecl>(Val: Var)->setCXXForRangeDecl(true);
14529 FinalizeDeclaration(D: Var);
14530 return ActOnDeclStmt(Decl: FinalizeDeclaratorGroup(S, DS, Group: Var), StartLoc: IdentLoc,
14531 EndLoc: Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14532 : IdentLoc);
14533}
14534
14535void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14536 if (var->isInvalidDecl()) return;
14537
14538 CUDA().MaybeAddConstantAttr(VD: var);
14539
14540 if (getLangOpts().OpenCL) {
14541 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14542 // initialiser
14543 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14544 !var->hasInit()) {
14545 Diag(Loc: var->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
14546 << 1 /*Init*/;
14547 var->setInvalidDecl();
14548 return;
14549 }
14550 }
14551
14552 // In Objective-C, don't allow jumps past the implicit initialization of a
14553 // local retaining variable.
14554 if (getLangOpts().ObjC &&
14555 var->hasLocalStorage()) {
14556 switch (var->getType().getObjCLifetime()) {
14557 case Qualifiers::OCL_None:
14558 case Qualifiers::OCL_ExplicitNone:
14559 case Qualifiers::OCL_Autoreleasing:
14560 break;
14561
14562 case Qualifiers::OCL_Weak:
14563 case Qualifiers::OCL_Strong:
14564 setFunctionHasBranchProtectedScope();
14565 break;
14566 }
14567 }
14568
14569 if (var->hasLocalStorage() &&
14570 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14571 setFunctionHasBranchProtectedScope();
14572
14573 // Warn about externally-visible variables being defined without a
14574 // prior declaration. We only want to do this for global
14575 // declarations, but we also specifically need to avoid doing it for
14576 // class members because the linkage of an anonymous class can
14577 // change if it's later given a typedef name.
14578 if (var->isThisDeclarationADefinition() &&
14579 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14580 var->isExternallyVisible() && var->hasLinkage() &&
14581 !var->isInline() && !var->getDescribedVarTemplate() &&
14582 var->getStorageClass() != SC_Register &&
14583 !isa<VarTemplatePartialSpecializationDecl>(Val: var) &&
14584 !isTemplateInstantiation(Kind: var->getTemplateSpecializationKind()) &&
14585 !getDiagnostics().isIgnored(DiagID: diag::warn_missing_variable_declarations,
14586 Loc: var->getLocation())) {
14587 // Find a previous declaration that's not a definition.
14588 VarDecl *prev = var->getPreviousDecl();
14589 while (prev && prev->isThisDeclarationADefinition())
14590 prev = prev->getPreviousDecl();
14591
14592 if (!prev) {
14593 Diag(Loc: var->getLocation(), DiagID: diag::warn_missing_variable_declarations) << var;
14594 Diag(Loc: var->getTypeSpecStartLoc(), DiagID: diag::note_static_for_internal_linkage)
14595 << /* variable */ 0;
14596 }
14597 }
14598
14599 // Cache the result of checking for constant initialization.
14600 std::optional<bool> CacheHasConstInit;
14601 const Expr *CacheCulprit = nullptr;
14602 auto checkConstInit = [&]() mutable {
14603 const Expr *Init = var->getInit();
14604 if (Init->isInstantiationDependent())
14605 return true;
14606
14607 if (!CacheHasConstInit)
14608 CacheHasConstInit = var->getInit()->isConstantInitializer(
14609 Ctx&: Context, ForRef: var->getType()->isReferenceType(), Culprit: &CacheCulprit);
14610 return *CacheHasConstInit;
14611 };
14612
14613 if (var->getTLSKind() == VarDecl::TLS_Static) {
14614 if (var->getType().isDestructedType()) {
14615 // GNU C++98 edits for __thread, [basic.start.term]p3:
14616 // The type of an object with thread storage duration shall not
14617 // have a non-trivial destructor.
14618 Diag(Loc: var->getLocation(), DiagID: diag::err_thread_nontrivial_dtor);
14619 if (getLangOpts().CPlusPlus11)
14620 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
14621 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14622 if (!checkConstInit()) {
14623 // GNU C++98 edits for __thread, [basic.start.init]p4:
14624 // An object of thread storage duration shall not require dynamic
14625 // initialization.
14626 // FIXME: Need strict checking here.
14627 Diag(Loc: CacheCulprit->getExprLoc(), DiagID: diag::err_thread_dynamic_init)
14628 << CacheCulprit->getSourceRange();
14629 if (getLangOpts().CPlusPlus11)
14630 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
14631 }
14632 }
14633 }
14634
14635
14636 if (!var->getType()->isStructureType() && var->hasInit() &&
14637 isa<InitListExpr>(Val: var->getInit())) {
14638 const auto *ILE = cast<InitListExpr>(Val: var->getInit());
14639 unsigned NumInits = ILE->getNumInits();
14640 if (NumInits > 2)
14641 for (unsigned I = 0; I < NumInits; ++I) {
14642 const auto *Init = ILE->getInit(Init: I);
14643 if (!Init)
14644 break;
14645 const auto *SL = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
14646 if (!SL)
14647 break;
14648
14649 unsigned NumConcat = SL->getNumConcatenated();
14650 // Diagnose missing comma in string array initialization.
14651 // Do not warn when all the elements in the initializer are concatenated
14652 // together. Do not warn for macros too.
14653 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14654 bool OnlyOneMissingComma = true;
14655 for (unsigned J = I + 1; J < NumInits; ++J) {
14656 const auto *Init = ILE->getInit(Init: J);
14657 if (!Init)
14658 break;
14659 const auto *SLJ = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
14660 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14661 OnlyOneMissingComma = false;
14662 break;
14663 }
14664 }
14665
14666 if (OnlyOneMissingComma) {
14667 SmallVector<FixItHint, 1> Hints;
14668 for (unsigned i = 0; i < NumConcat - 1; ++i)
14669 Hints.push_back(Elt: FixItHint::CreateInsertion(
14670 InsertionLoc: PP.getLocForEndOfToken(Loc: SL->getStrTokenLoc(TokNum: i)), Code: ","));
14671
14672 Diag(Loc: SL->getStrTokenLoc(TokNum: 1),
14673 DiagID: diag::warn_concatenated_literal_array_init)
14674 << Hints;
14675 Diag(Loc: SL->getBeginLoc(),
14676 DiagID: diag::note_concatenated_string_literal_silence);
14677 }
14678 // In any case, stop now.
14679 break;
14680 }
14681 }
14682 }
14683
14684
14685 QualType type = var->getType();
14686
14687 if (var->hasAttr<BlocksAttr>())
14688 getCurFunction()->addByrefBlockVar(VD: var);
14689
14690 Expr *Init = var->getInit();
14691 bool GlobalStorage = var->hasGlobalStorage();
14692 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14693 QualType baseType = Context.getBaseElementType(QT: type);
14694 bool HasConstInit = true;
14695
14696 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14697 Diag(Loc: var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
14698 << var;
14699
14700 // Check whether the initializer is sufficiently constant.
14701 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14702 !type->isDependentType() && Init && !Init->isValueDependent() &&
14703 (GlobalStorage || var->isConstexpr() ||
14704 var->mightBeUsableInConstantExpressions(C: Context))) {
14705 // If this variable might have a constant initializer or might be usable in
14706 // constant expressions, check whether or not it actually is now. We can't
14707 // do this lazily, because the result might depend on things that change
14708 // later, such as which constexpr functions happen to be defined.
14709 SmallVector<PartialDiagnosticAt, 8> Notes;
14710 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14711 // Prior to C++11, in contexts where a constant initializer is required,
14712 // the set of valid constant initializers is described by syntactic rules
14713 // in [expr.const]p2-6.
14714 // FIXME: Stricter checking for these rules would be useful for constinit /
14715 // -Wglobal-constructors.
14716 HasConstInit = checkConstInit();
14717
14718 // Compute and cache the constant value, and remember that we have a
14719 // constant initializer.
14720 if (HasConstInit) {
14721 if (var->isStaticDataMember() && !var->isInline() &&
14722 var->getLexicalDeclContext()->isRecord() &&
14723 type->isIntegralOrEnumerationType()) {
14724 // In C++98, in-class initialization for a static data member must
14725 // be an integer constant expression.
14726 SourceLocation Loc;
14727 if (!Init->isIntegerConstantExpr(Ctx: Context, Loc: &Loc)) {
14728 Diag(Loc, DiagID: diag::ext_in_class_initializer_non_constant)
14729 << Init->getSourceRange();
14730 }
14731 }
14732 (void)var->checkForConstantInitialization(Notes);
14733 Notes.clear();
14734 } else if (CacheCulprit) {
14735 Notes.emplace_back(Args: CacheCulprit->getExprLoc(),
14736 Args: PDiag(DiagID: diag::note_invalid_subexpr_in_const_expr));
14737 Notes.back().second << CacheCulprit->getSourceRange();
14738 }
14739 } else {
14740 // Evaluate the initializer to see if it's a constant initializer.
14741 HasConstInit = var->checkForConstantInitialization(Notes);
14742 }
14743
14744 if (HasConstInit) {
14745 // FIXME: Consider replacing the initializer with a ConstantExpr.
14746 } else if (var->isConstexpr()) {
14747 SourceLocation DiagLoc = var->getLocation();
14748 // If the note doesn't add any useful information other than a source
14749 // location, fold it into the primary diagnostic.
14750 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14751 diag::note_invalid_subexpr_in_const_expr) {
14752 DiagLoc = Notes[0].first;
14753 Notes.clear();
14754 }
14755 Diag(Loc: DiagLoc, DiagID: diag::err_constexpr_var_requires_const_init)
14756 << var << Init->getSourceRange();
14757 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14758 Diag(Loc: Notes[I].first, PD: Notes[I].second);
14759 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14760 auto *Attr = var->getAttr<ConstInitAttr>();
14761 Diag(Loc: var->getLocation(), DiagID: diag::err_require_constant_init_failed)
14762 << Init->getSourceRange();
14763 Diag(Loc: Attr->getLocation(), DiagID: diag::note_declared_required_constant_init_here)
14764 << Attr->getRange() << Attr->isConstinit();
14765 for (auto &it : Notes)
14766 Diag(Loc: it.first, PD: it.second);
14767 } else if (var->isStaticDataMember() && !var->isInline() &&
14768 var->getLexicalDeclContext()->isRecord()) {
14769 Diag(Loc: var->getLocation(), DiagID: diag::err_in_class_initializer_non_constant)
14770 << Init->getSourceRange();
14771 for (auto &it : Notes)
14772 Diag(Loc: it.first, PD: it.second);
14773 var->setInvalidDecl();
14774 } else if (IsGlobal &&
14775 !getDiagnostics().isIgnored(DiagID: diag::warn_global_constructor,
14776 Loc: var->getLocation())) {
14777 // Warn about globals which don't have a constant initializer. Don't
14778 // warn about globals with a non-trivial destructor because we already
14779 // warned about them.
14780 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14781 if (!(RD && !RD->hasTrivialDestructor())) {
14782 // checkConstInit() here permits trivial default initialization even in
14783 // C++11 onwards, where such an initializer is not a constant initializer
14784 // but nonetheless doesn't require a global constructor.
14785 if (!checkConstInit())
14786 Diag(Loc: var->getLocation(), DiagID: diag::warn_global_constructor)
14787 << Init->getSourceRange();
14788 }
14789 }
14790 }
14791
14792 // Apply section attributes and pragmas to global variables.
14793 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14794 !inTemplateInstantiation()) {
14795 PragmaStack<StringLiteral *> *Stack = nullptr;
14796 int SectionFlags = ASTContext::PSF_Read;
14797 bool MSVCEnv =
14798 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14799 std::optional<QualType::NonConstantStorageReason> Reason;
14800 if (HasConstInit &&
14801 !(Reason = var->getType().isNonConstantStorage(Ctx: Context, ExcludeCtor: true, ExcludeDtor: false))) {
14802 Stack = &ConstSegStack;
14803 } else {
14804 SectionFlags |= ASTContext::PSF_Write;
14805 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14806 }
14807 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14808 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14809 SectionFlags |= ASTContext::PSF_Implicit;
14810 UnifySection(SectionName: SA->getName(), SectionFlags, TheDecl: var);
14811 } else if (Stack->CurrentValue) {
14812 if (Stack != &ConstSegStack && MSVCEnv &&
14813 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14814 var->getType().isConstQualified()) {
14815 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14816 NonConstNonReferenceType) &&
14817 "This case should've already been handled elsewhere");
14818 Diag(Loc: var->getLocation(), DiagID: diag::warn_section_msvc_compat)
14819 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14820 ? QualType::NonConstantStorageReason::NonTrivialCtor
14821 : *Reason);
14822 }
14823 SectionFlags |= ASTContext::PSF_Implicit;
14824 auto SectionName = Stack->CurrentValue->getString();
14825 var->addAttr(A: SectionAttr::CreateImplicit(Ctx&: Context, Name: SectionName,
14826 Range: Stack->CurrentPragmaLocation,
14827 S: SectionAttr::Declspec_allocate));
14828 if (UnifySection(SectionName, SectionFlags, TheDecl: var))
14829 var->dropAttr<SectionAttr>();
14830 }
14831
14832 // Apply the init_seg attribute if this has an initializer. If the
14833 // initializer turns out to not be dynamic, we'll end up ignoring this
14834 // attribute.
14835 if (CurInitSeg && var->getInit())
14836 var->addAttr(A: InitSegAttr::CreateImplicit(Ctx&: Context, Section: CurInitSeg->getString(),
14837 Range: CurInitSegLoc));
14838 }
14839
14840 // All the following checks are C++ only.
14841 if (!getLangOpts().CPlusPlus) {
14842 // If this variable must be emitted, add it as an initializer for the
14843 // current module.
14844 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty())
14845 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
14846 return;
14847 }
14848
14849 DiagnoseUniqueObjectDuplication(VD: var);
14850
14851 // Require the destructor.
14852 if (!type->isDependentType())
14853 if (const RecordType *recordType = baseType->getAs<RecordType>())
14854 FinalizeVarWithDestructor(VD: var, DeclInitType: recordType);
14855
14856 // If this variable must be emitted, add it as an initializer for the current
14857 // module.
14858 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty())
14859 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
14860
14861 // Build the bindings if this is a structured binding declaration.
14862 if (auto *DD = dyn_cast<DecompositionDecl>(Val: var))
14863 CheckCompleteDecompositionDeclaration(DD);
14864}
14865
14866void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
14867 assert(VD->isStaticLocal());
14868
14869 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
14870
14871 // Find outermost function when VD is in lambda function.
14872 while (FD && !getDLLAttr(D: FD) &&
14873 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14874 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14875 FD = dyn_cast_or_null<FunctionDecl>(Val: FD->getParentFunctionOrMethod());
14876 }
14877
14878 if (!FD)
14879 return;
14880
14881 // Static locals inherit dll attributes from their function.
14882 if (Attr *A = getDLLAttr(D: FD)) {
14883 auto *NewAttr = cast<InheritableAttr>(Val: A->clone(C&: getASTContext()));
14884 NewAttr->setInherited(true);
14885 VD->addAttr(A: NewAttr);
14886 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14887 auto *NewAttr = DLLExportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
14888 NewAttr->setInherited(true);
14889 VD->addAttr(A: NewAttr);
14890
14891 // Export this function to enforce exporting this static variable even
14892 // if it is not used in this compilation unit.
14893 if (!FD->hasAttr<DLLExportAttr>())
14894 FD->addAttr(A: NewAttr);
14895
14896 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14897 auto *NewAttr = DLLImportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
14898 NewAttr->setInherited(true);
14899 VD->addAttr(A: NewAttr);
14900 }
14901}
14902
14903void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
14904 assert(VD->getTLSKind());
14905
14906 // Perform TLS alignment check here after attributes attached to the variable
14907 // which may affect the alignment have been processed. Only perform the check
14908 // if the target has a maximum TLS alignment (zero means no constraints).
14909 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14910 // Protect the check so that it's not performed on dependent types and
14911 // dependent alignments (we can't determine the alignment in that case).
14912 if (!VD->hasDependentAlignment()) {
14913 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(BitSize: MaxAlign);
14914 if (Context.getDeclAlign(D: VD) > MaxAlignChars) {
14915 Diag(Loc: VD->getLocation(), DiagID: diag::err_tls_var_aligned_over_maximum)
14916 << (unsigned)Context.getDeclAlign(D: VD).getQuantity() << VD
14917 << (unsigned)MaxAlignChars.getQuantity();
14918 }
14919 }
14920 }
14921}
14922
14923void Sema::FinalizeDeclaration(Decl *ThisDecl) {
14924 // Note that we are no longer parsing the initializer for this declaration.
14925 ParsingInitForAutoVars.erase(Ptr: ThisDecl);
14926
14927 VarDecl *VD = dyn_cast_or_null<VarDecl>(Val: ThisDecl);
14928 if (!VD)
14929 return;
14930
14931 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14932 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
14933 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14934 if (PragmaClangBSSSection.Valid)
14935 VD->addAttr(A: PragmaClangBSSSectionAttr::CreateImplicit(
14936 Ctx&: Context, Name: PragmaClangBSSSection.SectionName,
14937 Range: PragmaClangBSSSection.PragmaLocation));
14938 if (PragmaClangDataSection.Valid)
14939 VD->addAttr(A: PragmaClangDataSectionAttr::CreateImplicit(
14940 Ctx&: Context, Name: PragmaClangDataSection.SectionName,
14941 Range: PragmaClangDataSection.PragmaLocation));
14942 if (PragmaClangRodataSection.Valid)
14943 VD->addAttr(A: PragmaClangRodataSectionAttr::CreateImplicit(
14944 Ctx&: Context, Name: PragmaClangRodataSection.SectionName,
14945 Range: PragmaClangRodataSection.PragmaLocation));
14946 if (PragmaClangRelroSection.Valid)
14947 VD->addAttr(A: PragmaClangRelroSectionAttr::CreateImplicit(
14948 Ctx&: Context, Name: PragmaClangRelroSection.SectionName,
14949 Range: PragmaClangRelroSection.PragmaLocation));
14950 }
14951
14952 if (auto *DD = dyn_cast<DecompositionDecl>(Val: ThisDecl)) {
14953 for (auto *BD : DD->bindings()) {
14954 FinalizeDeclaration(ThisDecl: BD);
14955 }
14956 }
14957
14958 CheckInvalidBuiltinCountedByRef(E: VD->getInit(),
14959 K: BuiltinCountedByRefKind::Initializer);
14960
14961 checkAttributesAfterMerging(S&: *this, ND&: *VD);
14962
14963 if (VD->isStaticLocal())
14964 CheckStaticLocalForDllExport(VD);
14965
14966 if (VD->getTLSKind())
14967 CheckThreadLocalForLargeAlignment(VD);
14968
14969 // Perform check for initializers of device-side global variables.
14970 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14971 // 7.5). We must also apply the same checks to all __shared__
14972 // variables whether they are local or not. CUDA also allows
14973 // constant initializers for __constant__ and __device__ variables.
14974 if (getLangOpts().CUDA)
14975 CUDA().checkAllowedInitializer(VD);
14976
14977 // Grab the dllimport or dllexport attribute off of the VarDecl.
14978 const InheritableAttr *DLLAttr = getDLLAttr(D: VD);
14979
14980 // Imported static data members cannot be defined out-of-line.
14981 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(Val: DLLAttr)) {
14982 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14983 VD->isThisDeclarationADefinition()) {
14984 // We allow definitions of dllimport class template static data members
14985 // with a warning.
14986 CXXRecordDecl *Context =
14987 cast<CXXRecordDecl>(Val: VD->getFirstDecl()->getDeclContext());
14988 bool IsClassTemplateMember =
14989 isa<ClassTemplatePartialSpecializationDecl>(Val: Context) ||
14990 Context->getDescribedClassTemplate();
14991
14992 Diag(Loc: VD->getLocation(),
14993 DiagID: IsClassTemplateMember
14994 ? diag::warn_attribute_dllimport_static_field_definition
14995 : diag::err_attribute_dllimport_static_field_definition);
14996 Diag(Loc: IA->getLocation(), DiagID: diag::note_attribute);
14997 if (!IsClassTemplateMember)
14998 VD->setInvalidDecl();
14999 }
15000 }
15001
15002 // dllimport/dllexport variables cannot be thread local, their TLS index
15003 // isn't exported with the variable.
15004 if (DLLAttr && VD->getTLSKind()) {
15005 auto *F = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15006 if (F && getDLLAttr(D: F)) {
15007 assert(VD->isStaticLocal());
15008 // But if this is a static local in a dlimport/dllexport function, the
15009 // function will never be inlined, which means the var would never be
15010 // imported, so having it marked import/export is safe.
15011 } else {
15012 Diag(Loc: VD->getLocation(), DiagID: diag::err_attribute_dll_thread_local) << VD
15013 << DLLAttr;
15014 VD->setInvalidDecl();
15015 }
15016 }
15017
15018 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15019 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15020 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15021 << Attr;
15022 VD->dropAttr<UsedAttr>();
15023 }
15024 }
15025 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15026 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15027 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15028 << Attr;
15029 VD->dropAttr<RetainAttr>();
15030 }
15031 }
15032
15033 const DeclContext *DC = VD->getDeclContext();
15034 // If there's a #pragma GCC visibility in scope, and this isn't a class
15035 // member, set the visibility of this variable.
15036 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
15037 AddPushedVisibilityAttribute(RD: VD);
15038
15039 // FIXME: Warn on unused var template partial specializations.
15040 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(Val: VD))
15041 MarkUnusedFileScopedDecl(D: VD);
15042
15043 // Now we have parsed the initializer and can update the table of magic
15044 // tag values.
15045 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15046 !VD->getType()->isIntegralOrEnumerationType())
15047 return;
15048
15049 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15050 const Expr *MagicValueExpr = VD->getInit();
15051 if (!MagicValueExpr) {
15052 continue;
15053 }
15054 std::optional<llvm::APSInt> MagicValueInt;
15055 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Ctx: Context))) {
15056 Diag(Loc: I->getRange().getBegin(),
15057 DiagID: diag::err_type_tag_for_datatype_not_ice)
15058 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15059 continue;
15060 }
15061 if (MagicValueInt->getActiveBits() > 64) {
15062 Diag(Loc: I->getRange().getBegin(),
15063 DiagID: diag::err_type_tag_for_datatype_too_large)
15064 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15065 continue;
15066 }
15067 uint64_t MagicValue = MagicValueInt->getZExtValue();
15068 RegisterTypeTagForDatatype(ArgumentKind: I->getArgumentKind(),
15069 MagicValue,
15070 Type: I->getMatchingCType(),
15071 LayoutCompatible: I->getLayoutCompatible(),
15072 MustBeNull: I->getMustBeNull());
15073 }
15074}
15075
15076static bool hasDeducedAuto(DeclaratorDecl *DD) {
15077 auto *VD = dyn_cast<VarDecl>(Val: DD);
15078 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15079}
15080
15081Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
15082 ArrayRef<Decl *> Group) {
15083 SmallVector<Decl*, 8> Decls;
15084
15085 if (DS.isTypeSpecOwned())
15086 Decls.push_back(Elt: DS.getRepAsDecl());
15087
15088 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15089 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15090 bool DiagnosedMultipleDecomps = false;
15091 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15092 bool DiagnosedNonDeducedAuto = false;
15093
15094 for (Decl *D : Group) {
15095 if (!D)
15096 continue;
15097 // Check if the Decl has been declared in '#pragma omp declare target'
15098 // directive and has static storage duration.
15099 if (auto *VD = dyn_cast<VarDecl>(Val: D);
15100 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15101 VD->hasGlobalStorage())
15102 OpenMP().ActOnOpenMPDeclareTargetInitializer(D);
15103 // For declarators, there are some additional syntactic-ish checks we need
15104 // to perform.
15105 if (auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
15106 if (!FirstDeclaratorInGroup)
15107 FirstDeclaratorInGroup = DD;
15108 if (!FirstDecompDeclaratorInGroup)
15109 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(Val: D);
15110 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15111 !hasDeducedAuto(DD))
15112 FirstNonDeducedAutoInGroup = DD;
15113
15114 if (FirstDeclaratorInGroup != DD) {
15115 // A decomposition declaration cannot be combined with any other
15116 // declaration in the same group.
15117 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15118 Diag(Loc: FirstDecompDeclaratorInGroup->getLocation(),
15119 DiagID: diag::err_decomp_decl_not_alone)
15120 << FirstDeclaratorInGroup->getSourceRange()
15121 << DD->getSourceRange();
15122 DiagnosedMultipleDecomps = true;
15123 }
15124
15125 // A declarator that uses 'auto' in any way other than to declare a
15126 // variable with a deduced type cannot be combined with any other
15127 // declarator in the same group.
15128 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15129 Diag(Loc: FirstNonDeducedAutoInGroup->getLocation(),
15130 DiagID: diag::err_auto_non_deduced_not_alone)
15131 << FirstNonDeducedAutoInGroup->getType()
15132 ->hasAutoForTrailingReturnType()
15133 << FirstDeclaratorInGroup->getSourceRange()
15134 << DD->getSourceRange();
15135 DiagnosedNonDeducedAuto = true;
15136 }
15137 }
15138 }
15139
15140 Decls.push_back(Elt: D);
15141 }
15142
15143 if (DeclSpec::isDeclRep(T: DS.getTypeSpecType())) {
15144 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl())) {
15145 handleTagNumbering(Tag, TagScope: S);
15146 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15147 getLangOpts().CPlusPlus)
15148 Context.addDeclaratorForUnnamedTagDecl(TD: Tag, DD: FirstDeclaratorInGroup);
15149 }
15150 }
15151
15152 return BuildDeclaratorGroup(Group: Decls);
15153}
15154
15155Sema::DeclGroupPtrTy
15156Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
15157 // C++14 [dcl.spec.auto]p7: (DR1347)
15158 // If the type that replaces the placeholder type is not the same in each
15159 // deduction, the program is ill-formed.
15160 if (Group.size() > 1) {
15161 QualType Deduced;
15162 VarDecl *DeducedDecl = nullptr;
15163 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15164 VarDecl *D = dyn_cast<VarDecl>(Val: Group[i]);
15165 if (!D || D->isInvalidDecl())
15166 break;
15167 DeducedType *DT = D->getType()->getContainedDeducedType();
15168 if (!DT || DT->getDeducedType().isNull())
15169 continue;
15170 if (Deduced.isNull()) {
15171 Deduced = DT->getDeducedType();
15172 DeducedDecl = D;
15173 } else if (!Context.hasSameType(T1: DT->getDeducedType(), T2: Deduced)) {
15174 auto *AT = dyn_cast<AutoType>(Val: DT);
15175 auto Dia = Diag(Loc: D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15176 DiagID: diag::err_auto_different_deductions)
15177 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15178 << DeducedDecl->getDeclName() << DT->getDeducedType()
15179 << D->getDeclName();
15180 if (DeducedDecl->hasInit())
15181 Dia << DeducedDecl->getInit()->getSourceRange();
15182 if (D->getInit())
15183 Dia << D->getInit()->getSourceRange();
15184 D->setInvalidDecl();
15185 break;
15186 }
15187 }
15188 }
15189
15190 ActOnDocumentableDecls(Group);
15191
15192 return DeclGroupPtrTy::make(
15193 P: DeclGroupRef::Create(C&: Context, Decls: Group.data(), NumDecls: Group.size()));
15194}
15195
15196void Sema::ActOnDocumentableDecl(Decl *D) {
15197 ActOnDocumentableDecls(Group: D);
15198}
15199
15200void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
15201 // Don't parse the comment if Doxygen diagnostics are ignored.
15202 if (Group.empty() || !Group[0])
15203 return;
15204
15205 if (Diags.isIgnored(DiagID: diag::warn_doc_param_not_found,
15206 Loc: Group[0]->getLocation()) &&
15207 Diags.isIgnored(DiagID: diag::warn_unknown_comment_command_name,
15208 Loc: Group[0]->getLocation()))
15209 return;
15210
15211 if (Group.size() >= 2) {
15212 // This is a decl group. Normally it will contain only declarations
15213 // produced from declarator list. But in case we have any definitions or
15214 // additional declaration references:
15215 // 'typedef struct S {} S;'
15216 // 'typedef struct S *S;'
15217 // 'struct S *pS;'
15218 // FinalizeDeclaratorGroup adds these as separate declarations.
15219 Decl *MaybeTagDecl = Group[0];
15220 if (MaybeTagDecl && isa<TagDecl>(Val: MaybeTagDecl)) {
15221 Group = Group.slice(N: 1);
15222 }
15223 }
15224
15225 // FIMXE: We assume every Decl in the group is in the same file.
15226 // This is false when preprocessor constructs the group from decls in
15227 // different files (e. g. macros or #include).
15228 Context.attachCommentsToJustParsedDecls(Decls: Group, PP: &getPreprocessor());
15229}
15230
15231void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
15232 // Check that there are no default arguments inside the type of this
15233 // parameter.
15234 if (getLangOpts().CPlusPlus)
15235 CheckExtraCXXDefaultArguments(D);
15236
15237 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15238 if (D.getCXXScopeSpec().isSet()) {
15239 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_param_declarator)
15240 << D.getCXXScopeSpec().getRange();
15241 }
15242
15243 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15244 // simple identifier except [...irrelevant cases...].
15245 switch (D.getName().getKind()) {
15246 case UnqualifiedIdKind::IK_Identifier:
15247 break;
15248
15249 case UnqualifiedIdKind::IK_OperatorFunctionId:
15250 case UnqualifiedIdKind::IK_ConversionFunctionId:
15251 case UnqualifiedIdKind::IK_LiteralOperatorId:
15252 case UnqualifiedIdKind::IK_ConstructorName:
15253 case UnqualifiedIdKind::IK_DestructorName:
15254 case UnqualifiedIdKind::IK_ImplicitSelfParam:
15255 case UnqualifiedIdKind::IK_DeductionGuideName:
15256 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name)
15257 << GetNameForDeclarator(D).getName();
15258 break;
15259
15260 case UnqualifiedIdKind::IK_TemplateId:
15261 case UnqualifiedIdKind::IK_ConstructorTemplateId:
15262 // GetNameForDeclarator would not produce a useful name in this case.
15263 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name_template_id);
15264 break;
15265 }
15266}
15267
15268void Sema::warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D) {
15269 // This only matters in C.
15270 if (getLangOpts().CPlusPlus)
15271 return;
15272
15273 // This only matters if the declaration has a type.
15274 const auto *VD = dyn_cast<ValueDecl>(Val: D);
15275 if (!VD)
15276 return;
15277
15278 // Get the type, this only matters for tag types.
15279 QualType QT = VD->getType();
15280 const auto *TD = QT->getAsTagDecl();
15281 if (!TD)
15282 return;
15283
15284 // Check if the tag declaration is lexically declared somewhere different
15285 // from the lexical declaration of the given object, then it will be hidden
15286 // in C++ and we should warn on it.
15287 if (!TD->getLexicalParent()->LexicallyEncloses(DC: D->getLexicalDeclContext())) {
15288 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15289 Diag(Loc: D->getLocation(), DiagID: diag::warn_decl_hidden_in_cpp) << Kind;
15290 Diag(Loc: TD->getLocation(), DiagID: diag::note_declared_at);
15291 }
15292}
15293
15294static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
15295 SourceLocation ExplicitThisLoc) {
15296 if (!ExplicitThisLoc.isValid())
15297 return;
15298 assert(S.getLangOpts().CPlusPlus &&
15299 "explicit parameter in non-cplusplus mode");
15300 if (!S.getLangOpts().CPlusPlus23)
15301 S.Diag(Loc: ExplicitThisLoc, DiagID: diag::err_cxx20_deducing_this)
15302 << P->getSourceRange();
15303
15304 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15305 // parameter pack.
15306 if (P->isParameterPack()) {
15307 S.Diag(Loc: P->getBeginLoc(), DiagID: diag::err_explicit_object_parameter_pack)
15308 << P->getSourceRange();
15309 return;
15310 }
15311 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15312 if (LambdaScopeInfo *LSI = S.getCurLambda())
15313 LSI->ExplicitObjectParameter = P;
15314}
15315
15316Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15317 SourceLocation ExplicitThisLoc) {
15318 const DeclSpec &DS = D.getDeclSpec();
15319
15320 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15321 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15322 // except for the special case of a single unnamed parameter of type void
15323 // with no storage class specifier, no type qualifier, and no following
15324 // ellipsis terminator.
15325 // Clang applies the C2y rules for 'register void' in all C language modes,
15326 // same as GCC, because it's questionable what that could possibly mean.
15327
15328 // C++03 [dcl.stc]p2 also permits 'auto'.
15329 StorageClass SC = SC_None;
15330 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15331 SC = SC_Register;
15332 // In C++11, the 'register' storage class specifier is deprecated.
15333 // In C++17, it is not allowed, but we tolerate it as an extension.
15334 if (getLangOpts().CPlusPlus11) {
15335 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus17
15336 ? diag::ext_register_storage_class
15337 : diag::warn_deprecated_register)
15338 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15339 } else if (!getLangOpts().CPlusPlus &&
15340 DS.getTypeSpecType() == DeclSpec::TST_void &&
15341 D.getNumTypeObjects() == 0) {
15342 Diag(Loc: DS.getStorageClassSpecLoc(),
15343 DiagID: diag::err_invalid_storage_class_in_func_decl)
15344 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15345 D.getMutableDeclSpec().ClearStorageClassSpecs();
15346 }
15347 } else if (getLangOpts().CPlusPlus &&
15348 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
15349 SC = SC_Auto;
15350 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15351 Diag(Loc: DS.getStorageClassSpecLoc(),
15352 DiagID: diag::err_invalid_storage_class_in_func_decl);
15353 D.getMutableDeclSpec().ClearStorageClassSpecs();
15354 }
15355
15356 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15357 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID: diag::err_invalid_thread)
15358 << DeclSpec::getSpecifierName(S: TSCS);
15359 if (DS.isInlineSpecified())
15360 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
15361 << getLangOpts().CPlusPlus17;
15362 if (DS.hasConstexprSpecifier())
15363 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
15364 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15365
15366 DiagnoseFunctionSpecifiers(DS);
15367
15368 CheckFunctionOrTemplateParamDeclarator(S, D);
15369
15370 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
15371 QualType parmDeclType = TInfo->getType();
15372
15373 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15374 const IdentifierInfo *II = D.getIdentifier();
15375 if (II) {
15376 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15377 RedeclarationKind::ForVisibleRedeclaration);
15378 LookupName(R, S);
15379 if (!R.empty()) {
15380 NamedDecl *PrevDecl = *R.begin();
15381 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15382 // Maybe we will complain about the shadowed template parameter.
15383 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
15384 // Just pretend that we didn't see the previous declaration.
15385 PrevDecl = nullptr;
15386 }
15387 if (PrevDecl && S->isDeclScope(D: PrevDecl)) {
15388 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_param_redefinition) << II;
15389 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
15390 // Recover by removing the name
15391 II = nullptr;
15392 D.SetIdentifier(Id: nullptr, IdLoc: D.getIdentifierLoc());
15393 D.setInvalidType(true);
15394 }
15395 }
15396 }
15397
15398 // Temporarily put parameter variables in the translation unit, not
15399 // the enclosing context. This prevents them from accidentally
15400 // looking like class members in C++.
15401 ParmVarDecl *New =
15402 CheckParameter(DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
15403 NameLoc: D.getIdentifierLoc(), Name: II, T: parmDeclType, TSInfo: TInfo, SC);
15404
15405 if (D.isInvalidType())
15406 New->setInvalidDecl();
15407
15408 CheckExplicitObjectParameter(S&: *this, P: New, ExplicitThisLoc);
15409
15410 assert(S->isFunctionPrototypeScope());
15411 assert(S->getFunctionPrototypeDepth() >= 1);
15412 New->setScopeInfo(scopeDepth: S->getFunctionPrototypeDepth() - 1,
15413 parameterIndex: S->getNextFunctionPrototypeIndex());
15414
15415 warnOnCTypeHiddenInCPlusPlus(D: New);
15416
15417 // Add the parameter declaration into this scope.
15418 S->AddDecl(D: New);
15419 if (II)
15420 IdResolver.AddDecl(D: New);
15421
15422 ProcessDeclAttributes(S, D: New, PD: D);
15423
15424 if (D.getDeclSpec().isModulePrivateSpecified())
15425 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_local)
15426 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15427 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
15428
15429 if (New->hasAttr<BlocksAttr>()) {
15430 Diag(Loc: New->getLocation(), DiagID: diag::err_block_on_nonlocal);
15431 }
15432
15433 if (getLangOpts().OpenCL)
15434 deduceOpenCLAddressSpace(Decl: New);
15435
15436 return New;
15437}
15438
15439ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
15440 SourceLocation Loc,
15441 QualType T) {
15442 /* FIXME: setting StartLoc == Loc.
15443 Would it be worth to modify callers so as to provide proper source
15444 location for the unnamed parameters, embedding the parameter's type? */
15445 ParmVarDecl *Param = ParmVarDecl::Create(C&: Context, DC, StartLoc: Loc, IdLoc: Loc, Id: nullptr,
15446 T, TInfo: Context.getTrivialTypeSourceInfo(T, Loc),
15447 S: SC_None, DefArg: nullptr);
15448 Param->setImplicit();
15449 return Param;
15450}
15451
15452void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
15453 // Don't diagnose unused-parameter errors in template instantiations; we
15454 // will already have done so in the template itself.
15455 if (inTemplateInstantiation())
15456 return;
15457
15458 for (const ParmVarDecl *Parameter : Parameters) {
15459 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15460 !Parameter->hasAttr<UnusedAttr>() &&
15461 !Parameter->getIdentifier()->isPlaceholder()) {
15462 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_unused_parameter)
15463 << Parameter->getDeclName();
15464 }
15465 }
15466}
15467
15468void Sema::DiagnoseSizeOfParametersAndReturnValue(
15469 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15470 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15471 return;
15472
15473 // Warn if the return value is pass-by-value and larger than the specified
15474 // threshold.
15475 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15476 unsigned Size = Context.getTypeSizeInChars(T: ReturnTy).getQuantity();
15477 if (Size > LangOpts.NumLargeByValueCopy)
15478 Diag(Loc: D->getLocation(), DiagID: diag::warn_return_value_size) << D << Size;
15479 }
15480
15481 // Warn if any parameter is pass-by-value and larger than the specified
15482 // threshold.
15483 for (const ParmVarDecl *Parameter : Parameters) {
15484 QualType T = Parameter->getType();
15485 if (T->isDependentType() || !T.isPODType(Context))
15486 continue;
15487 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15488 if (Size > LangOpts.NumLargeByValueCopy)
15489 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_parameter_size)
15490 << Parameter << Size;
15491 }
15492}
15493
15494ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
15495 SourceLocation NameLoc,
15496 const IdentifierInfo *Name, QualType T,
15497 TypeSourceInfo *TSInfo, StorageClass SC) {
15498 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15499 if (getLangOpts().ObjCAutoRefCount &&
15500 T.getObjCLifetime() == Qualifiers::OCL_None &&
15501 T->isObjCLifetimeType()) {
15502
15503 Qualifiers::ObjCLifetime lifetime;
15504
15505 // Special cases for arrays:
15506 // - if it's const, use __unsafe_unretained
15507 // - otherwise, it's an error
15508 if (T->isArrayType()) {
15509 if (!T.isConstQualified()) {
15510 if (DelayedDiagnostics.shouldDelayDiagnostics())
15511 DelayedDiagnostics.add(
15512 diag: sema::DelayedDiagnostic::makeForbiddenType(
15513 loc: NameLoc, diagnostic: diag::err_arc_array_param_no_ownership, type: T, argument: false));
15514 else
15515 Diag(Loc: NameLoc, DiagID: diag::err_arc_array_param_no_ownership)
15516 << TSInfo->getTypeLoc().getSourceRange();
15517 }
15518 lifetime = Qualifiers::OCL_ExplicitNone;
15519 } else {
15520 lifetime = T->getObjCARCImplicitLifetime();
15521 }
15522 T = Context.getLifetimeQualifiedType(type: T, lifetime);
15523 }
15524
15525 ParmVarDecl *New = ParmVarDecl::Create(C&: Context, DC, StartLoc, IdLoc: NameLoc, Id: Name,
15526 T: Context.getAdjustedParameterType(T),
15527 TInfo: TSInfo, S: SC, DefArg: nullptr);
15528
15529 // Make a note if we created a new pack in the scope of a lambda, so that
15530 // we know that references to that pack must also be expanded within the
15531 // lambda scope.
15532 if (New->isParameterPack())
15533 if (auto *CSI = getEnclosingLambdaOrBlock())
15534 CSI->LocalPacks.push_back(Elt: New);
15535
15536 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15537 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15538 checkNonTrivialCUnion(QT: New->getType(), Loc: New->getLocation(),
15539 UseContext: NonTrivialCUnionContext::FunctionParam,
15540 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
15541
15542 // Parameter declarators cannot be interface types. All ObjC objects are
15543 // passed by reference.
15544 if (T->isObjCObjectType()) {
15545 SourceLocation TypeEndLoc =
15546 getLocForEndOfToken(Loc: TSInfo->getTypeLoc().getEndLoc());
15547 Diag(Loc: NameLoc,
15548 DiagID: diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15549 << FixItHint::CreateInsertion(InsertionLoc: TypeEndLoc, Code: "*");
15550 T = Context.getObjCObjectPointerType(OIT: T);
15551 New->setType(T);
15552 }
15553
15554 // __ptrauth is forbidden on parameters.
15555 if (T.getPointerAuth()) {
15556 Diag(Loc: NameLoc, DiagID: diag::err_ptrauth_qualifier_invalid) << T << 1;
15557 New->setInvalidDecl();
15558 }
15559
15560 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15561 // duration shall not be qualified by an address-space qualifier."
15562 // Since all parameters have automatic store duration, they can not have
15563 // an address space.
15564 if (T.getAddressSpace() != LangAS::Default &&
15565 // OpenCL allows function arguments declared to be an array of a type
15566 // to be qualified with an address space.
15567 !(getLangOpts().OpenCL &&
15568 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15569 // WebAssembly allows reference types as parameters. Funcref in particular
15570 // lives in a different address space.
15571 !(T->isFunctionPointerType() &&
15572 T.getAddressSpace() == LangAS::wasm_funcref)) {
15573 Diag(Loc: NameLoc, DiagID: diag::err_arg_with_address_space);
15574 New->setInvalidDecl();
15575 }
15576
15577 // PPC MMA non-pointer types are not allowed as function argument types.
15578 if (Context.getTargetInfo().getTriple().isPPC64() &&
15579 PPC().CheckPPCMMAType(Type: New->getOriginalType(), TypeLoc: New->getLocation())) {
15580 New->setInvalidDecl();
15581 }
15582
15583 return New;
15584}
15585
15586void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
15587 SourceLocation LocAfterDecls) {
15588 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15589
15590 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15591 // in the declaration list shall have at least one declarator, those
15592 // declarators shall only declare identifiers from the identifier list, and
15593 // every identifier in the identifier list shall be declared.
15594 //
15595 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15596 // identifiers it names shall be declared in the declaration list."
15597 //
15598 // This is why we only diagnose in C99 and later. Note, the other conditions
15599 // listed are checked elsewhere.
15600 if (!FTI.hasPrototype) {
15601 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15602 --i;
15603 if (FTI.Params[i].Param == nullptr) {
15604 if (getLangOpts().C99) {
15605 SmallString<256> Code;
15606 llvm::raw_svector_ostream(Code)
15607 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15608 Diag(Loc: FTI.Params[i].IdentLoc, DiagID: diag::ext_param_not_declared)
15609 << FTI.Params[i].Ident
15610 << FixItHint::CreateInsertion(InsertionLoc: LocAfterDecls, Code);
15611 }
15612
15613 // Implicitly declare the argument as type 'int' for lack of a better
15614 // type.
15615 AttributeFactory attrs;
15616 DeclSpec DS(attrs);
15617 const char* PrevSpec; // unused
15618 unsigned DiagID; // unused
15619 DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc: FTI.Params[i].IdentLoc, PrevSpec,
15620 DiagID, Policy: Context.getPrintingPolicy());
15621 // Use the identifier location for the type source range.
15622 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15623 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15624 Declarator ParamD(DS, ParsedAttributesView::none(),
15625 DeclaratorContext::KNRTypeList);
15626 ParamD.SetIdentifier(Id: FTI.Params[i].Ident, IdLoc: FTI.Params[i].IdentLoc);
15627 FTI.Params[i].Param = ActOnParamDeclarator(S, D&: ParamD);
15628 }
15629 }
15630 }
15631}
15632
15633Decl *
15634Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
15635 MultiTemplateParamsArg TemplateParameterLists,
15636 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15637 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15638 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15639 Scope *ParentScope = FnBodyScope->getParent();
15640
15641 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15642 // we define a non-templated function definition, we will create a declaration
15643 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15644 // The base function declaration will have the equivalent of an `omp declare
15645 // variant` annotation which specifies the mangled definition as a
15646 // specialization function under the OpenMP context defined as part of the
15647 // `omp begin declare variant`.
15648 SmallVector<FunctionDecl *, 4> Bases;
15649 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15650 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15651 S: ParentScope, D, TemplateParameterLists, Bases);
15652
15653 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15654 Decl *DP = HandleDeclarator(S: ParentScope, D, TemplateParamLists: TemplateParameterLists);
15655 Decl *Dcl = ActOnStartOfFunctionDef(S: FnBodyScope, D: DP, SkipBody, BodyKind);
15656
15657 if (!Bases.empty())
15658 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
15659 Bases);
15660
15661 return Dcl;
15662}
15663
15664void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
15665 Consumer.HandleInlineFunctionDefinition(D);
15666}
15667
15668static bool FindPossiblePrototype(const FunctionDecl *FD,
15669 const FunctionDecl *&PossiblePrototype) {
15670 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15671 Prev = Prev->getPreviousDecl()) {
15672 // Ignore any declarations that occur in function or method
15673 // scope, because they aren't visible from the header.
15674 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15675 continue;
15676
15677 PossiblePrototype = Prev;
15678 return Prev->getType()->isFunctionProtoType();
15679 }
15680 return false;
15681}
15682
15683static bool
15684ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
15685 const FunctionDecl *&PossiblePrototype) {
15686 // Don't warn about invalid declarations.
15687 if (FD->isInvalidDecl())
15688 return false;
15689
15690 // Or declarations that aren't global.
15691 if (!FD->isGlobal())
15692 return false;
15693
15694 // Don't warn about C++ member functions.
15695 if (isa<CXXMethodDecl>(Val: FD))
15696 return false;
15697
15698 // Don't warn about 'main'.
15699 if (isa<TranslationUnitDecl>(Val: FD->getDeclContext()->getRedeclContext()))
15700 if (IdentifierInfo *II = FD->getIdentifier())
15701 if (II->isStr(Str: "main") || II->isStr(Str: "efi_main"))
15702 return false;
15703
15704 if (FD->isMSVCRTEntryPoint())
15705 return false;
15706
15707 // Don't warn about inline functions.
15708 if (FD->isInlined())
15709 return false;
15710
15711 // Don't warn about function templates.
15712 if (FD->getDescribedFunctionTemplate())
15713 return false;
15714
15715 // Don't warn about function template specializations.
15716 if (FD->isFunctionTemplateSpecialization())
15717 return false;
15718
15719 // Don't warn for OpenCL kernels.
15720 if (FD->hasAttr<DeviceKernelAttr>())
15721 return false;
15722
15723 // Don't warn on explicitly deleted functions.
15724 if (FD->isDeleted())
15725 return false;
15726
15727 // Don't warn on implicitly local functions (such as having local-typed
15728 // parameters).
15729 if (!FD->isExternallyVisible())
15730 return false;
15731
15732 // If we were able to find a potential prototype, don't warn.
15733 if (FindPossiblePrototype(FD, PossiblePrototype))
15734 return false;
15735
15736 return true;
15737}
15738
15739void
15740Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
15741 const FunctionDecl *EffectiveDefinition,
15742 SkipBodyInfo *SkipBody) {
15743 const FunctionDecl *Definition = EffectiveDefinition;
15744 if (!Definition &&
15745 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15746 return;
15747
15748 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15749 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15750 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15751 // A merged copy of the same function, instantiated as a member of
15752 // the same class, is OK.
15753 if (declaresSameEntity(D1: OrigFD, D2: OrigDef) &&
15754 declaresSameEntity(D1: cast<Decl>(Val: Definition->getLexicalDeclContext()),
15755 D2: cast<Decl>(Val: FD->getLexicalDeclContext())))
15756 return;
15757 }
15758 }
15759 }
15760
15761 if (canRedefineFunction(FD: Definition, LangOpts: getLangOpts()))
15762 return;
15763
15764 // Don't emit an error when this is redefinition of a typo-corrected
15765 // definition.
15766 if (TypoCorrectedFunctionDefinitions.count(Ptr: Definition))
15767 return;
15768
15769 // If we don't have a visible definition of the function, and it's inline or
15770 // a template, skip the new definition.
15771 if (SkipBody && !hasVisibleDefinition(D: Definition) &&
15772 (Definition->getFormalLinkage() == Linkage::Internal ||
15773 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15774 Definition->getNumTemplateParameterLists())) {
15775 SkipBody->ShouldSkip = true;
15776 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15777 if (auto *TD = Definition->getDescribedFunctionTemplate())
15778 makeMergedDefinitionVisible(ND: TD);
15779 makeMergedDefinitionVisible(ND: const_cast<FunctionDecl*>(Definition));
15780 return;
15781 }
15782
15783 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15784 Definition->getStorageClass() == SC_Extern)
15785 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition_extern_inline)
15786 << FD << getLangOpts().CPlusPlus;
15787 else
15788 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition) << FD;
15789
15790 Diag(Loc: Definition->getLocation(), DiagID: diag::note_previous_definition);
15791 FD->setInvalidDecl();
15792}
15793
15794LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
15795 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15796
15797 LambdaScopeInfo *LSI = PushLambdaScope();
15798 LSI->CallOperator = CallOperator;
15799 LSI->Lambda = LambdaClass;
15800 LSI->ReturnType = CallOperator->getReturnType();
15801 // When this function is called in situation where the context of the call
15802 // operator is not entered, we set AfterParameterList to false, so that
15803 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15804 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
15805 // where we would set the CurContext to the lambda operator before
15806 // substituting into it. In this case the flag needs to be true such that
15807 // tryCaptureVariable can correctly handle potential captures thereof.
15808 LSI->AfterParameterList = CurContext == CallOperator;
15809
15810 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
15811 // used at the point of dealing with potential captures.
15812 //
15813 // We don't use LambdaClass->isGenericLambda() because this value doesn't
15814 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
15815 // associated. (Technically, we could recover that list from their
15816 // instantiation patterns, but for now, the GLTemplateParameterList seems
15817 // unnecessary in these cases.)
15818 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
15819 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
15820 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15821
15822 if (LCD == LCD_None)
15823 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
15824 else if (LCD == LCD_ByCopy)
15825 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
15826 else if (LCD == LCD_ByRef)
15827 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
15828 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15829
15830 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
15831 LSI->Mutable = !CallOperator->isConst();
15832 if (CallOperator->isExplicitObjectMemberFunction())
15833 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(i: 0);
15834
15835 // Add the captures to the LSI so they can be noted as already
15836 // captured within tryCaptureVar.
15837 auto I = LambdaClass->field_begin();
15838 for (const auto &C : LambdaClass->captures()) {
15839 if (C.capturesVariable()) {
15840 ValueDecl *VD = C.getCapturedVar();
15841 if (VD->isInitCapture())
15842 CurrentInstantiationScope->InstantiatedLocal(D: VD, Inst: VD);
15843 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15844 LSI->addCapture(Var: VD, /*IsBlock*/isBlock: false, isByref: ByRef,
15845 /*RefersToEnclosingVariableOrCapture*/isNested: true, Loc: C.getLocation(),
15846 /*EllipsisLoc*/C.isPackExpansion()
15847 ? C.getEllipsisLoc() : SourceLocation(),
15848 CaptureType: I->getType(), /*Invalid*/false);
15849
15850 } else if (C.capturesThis()) {
15851 LSI->addThisCapture(/*Nested*/ isNested: false, Loc: C.getLocation(), CaptureType: I->getType(),
15852 ByCopy: C.getCaptureKind() == LCK_StarThis);
15853 } else {
15854 LSI->addVLATypeCapture(Loc: C.getLocation(), VLAType: I->getCapturedVLAType(),
15855 CaptureType: I->getType());
15856 }
15857 ++I;
15858 }
15859 return LSI;
15860}
15861
15862Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
15863 SkipBodyInfo *SkipBody,
15864 FnBodyKind BodyKind) {
15865 if (!D) {
15866 // Parsing the function declaration failed in some way. Push on a fake scope
15867 // anyway so we can try to parse the function body.
15868 PushFunctionScope();
15869 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
15870 return D;
15871 }
15872
15873 FunctionDecl *FD = nullptr;
15874
15875 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D))
15876 FD = FunTmpl->getTemplatedDecl();
15877 else
15878 FD = cast<FunctionDecl>(Val: D);
15879
15880 // Do not push if it is a lambda because one is already pushed when building
15881 // the lambda in ActOnStartOfLambdaDefinition().
15882 if (!isLambdaCallOperator(DC: FD))
15883 PushExpressionEvaluationContextForFunction(NewContext: ExprEvalContexts.back().Context,
15884 FD);
15885
15886 // Check for defining attributes before the check for redefinition.
15887 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15888 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 0;
15889 FD->dropAttr<AliasAttr>();
15890 FD->setInvalidDecl();
15891 }
15892 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15893 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 1;
15894 FD->dropAttr<IFuncAttr>();
15895 FD->setInvalidDecl();
15896 }
15897 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15898 if (Context.getTargetInfo().getTriple().isAArch64() &&
15899 !Context.getTargetInfo().hasFeature(Feature: "fmv") &&
15900 !Attr->isDefaultVersion()) {
15901 // If function multi versioning disabled skip parsing function body
15902 // defined with non-default target_version attribute
15903 if (SkipBody)
15904 SkipBody->ShouldSkip = true;
15905 return nullptr;
15906 }
15907 }
15908
15909 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
15910 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15911 Ctor->isDefaultConstructor() &&
15912 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15913 // If this is an MS ABI dllexport default constructor, instantiate any
15914 // default arguments.
15915 InstantiateDefaultCtorDefaultArgs(Ctor);
15916 }
15917 }
15918
15919 // See if this is a redefinition. If 'will have body' (or similar) is already
15920 // set, then these checks were already performed when it was set.
15921 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15922 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
15923 CheckForFunctionRedefinition(FD, EffectiveDefinition: nullptr, SkipBody);
15924
15925 // If we're skipping the body, we're done. Don't enter the scope.
15926 if (SkipBody && SkipBody->ShouldSkip)
15927 return D;
15928 }
15929
15930 // Mark this function as "will have a body eventually". This lets users to
15931 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15932 // this function.
15933 FD->setWillHaveBody();
15934
15935 // If we are instantiating a generic lambda call operator, push
15936 // a LambdaScopeInfo onto the function stack. But use the information
15937 // that's already been calculated (ActOnLambdaExpr) to prime the current
15938 // LambdaScopeInfo.
15939 // When the template operator is being specialized, the LambdaScopeInfo,
15940 // has to be properly restored so that tryCaptureVariable doesn't try
15941 // and capture any new variables. In addition when calculating potential
15942 // captures during transformation of nested lambdas, it is necessary to
15943 // have the LSI properly restored.
15944 if (isGenericLambdaCallOperatorSpecialization(DC: FD)) {
15945 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
15946 // instantiated, explicitly specialized.
15947 if (FD->getTemplateSpecializationInfo()
15948 ->isExplicitInstantiationOrSpecialization()) {
15949 Diag(Loc: FD->getLocation(), DiagID: diag::err_lambda_explicit_spec);
15950 FD->setInvalidDecl();
15951 PushFunctionScope();
15952 } else {
15953 assert(inTemplateInstantiation() &&
15954 "There should be an active template instantiation on the stack "
15955 "when instantiating a generic lambda!");
15956 RebuildLambdaScopeInfo(CallOperator: cast<CXXMethodDecl>(Val: D));
15957 }
15958 } else {
15959 // Enter a new function scope
15960 PushFunctionScope();
15961 }
15962
15963 // Builtin functions cannot be defined.
15964 if (unsigned BuiltinID = FD->getBuiltinID()) {
15965 if (!Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID) &&
15966 !Context.BuiltinInfo.isPredefinedRuntimeFunction(ID: BuiltinID)) {
15967 Diag(Loc: FD->getLocation(), DiagID: diag::err_builtin_definition) << FD;
15968 FD->setInvalidDecl();
15969 }
15970 }
15971
15972 // The return type of a function definition must be complete (C99 6.9.1p3).
15973 // C++23 [dcl.fct.def.general]/p2
15974 // The type of [...] the return for a function definition
15975 // shall not be a (possibly cv-qualified) class type that is incomplete
15976 // or abstract within the function body unless the function is deleted.
15977 QualType ResultType = FD->getReturnType();
15978 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15979 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15980 (RequireCompleteType(Loc: FD->getLocation(), T: ResultType,
15981 DiagID: diag::err_func_def_incomplete_result) ||
15982 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getReturnType(),
15983 DiagID: diag::err_abstract_type_in_decl,
15984 Args: AbstractReturnType)))
15985 FD->setInvalidDecl();
15986
15987 if (FnBodyScope)
15988 PushDeclContext(S: FnBodyScope, DC: FD);
15989
15990 // Check the validity of our function parameters
15991 if (BodyKind != FnBodyKind::Delete)
15992 CheckParmsForFunctionDef(Parameters: FD->parameters(),
15993 /*CheckParameterNames=*/true);
15994
15995 // Add non-parameter declarations already in the function to the current
15996 // scope.
15997 if (FnBodyScope) {
15998 for (Decl *NPD : FD->decls()) {
15999 auto *NonParmDecl = dyn_cast<NamedDecl>(Val: NPD);
16000 if (!NonParmDecl)
16001 continue;
16002 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16003 "parameters should not be in newly created FD yet");
16004
16005 // If the decl has a name, make it accessible in the current scope.
16006 if (NonParmDecl->getDeclName())
16007 PushOnScopeChains(D: NonParmDecl, S: FnBodyScope, /*AddToContext=*/false);
16008
16009 // Similarly, dive into enums and fish their constants out, making them
16010 // accessible in this scope.
16011 if (auto *ED = dyn_cast<EnumDecl>(Val: NonParmDecl)) {
16012 for (auto *EI : ED->enumerators())
16013 PushOnScopeChains(D: EI, S: FnBodyScope, /*AddToContext=*/false);
16014 }
16015 }
16016 }
16017
16018 // Introduce our parameters into the function scope
16019 for (auto *Param : FD->parameters()) {
16020 Param->setOwningFunction(FD);
16021
16022 // If this has an identifier, add it to the scope stack.
16023 if (Param->getIdentifier() && FnBodyScope) {
16024 CheckShadow(S: FnBodyScope, D: Param);
16025
16026 PushOnScopeChains(D: Param, S: FnBodyScope);
16027 }
16028 }
16029
16030 // C++ [module.import/6] external definitions are not permitted in header
16031 // units. Deleted and Defaulted functions are implicitly inline (but the
16032 // inline state is not set at this point, so check the BodyKind explicitly).
16033 // FIXME: Consider an alternate location for the test where the inlined()
16034 // state is complete.
16035 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16036 !FD->isInvalidDecl() && !FD->isInlined() &&
16037 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16038 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16039 !FD->isTemplateInstantiation()) {
16040 assert(FD->isThisDeclarationADefinition());
16041 Diag(Loc: FD->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
16042 FD->setInvalidDecl();
16043 }
16044
16045 // Ensure that the function's exception specification is instantiated.
16046 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16047 ResolveExceptionSpec(Loc: D->getLocation(), FPT);
16048
16049 // dllimport cannot be applied to non-inline function definitions.
16050 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16051 !FD->isTemplateInstantiation()) {
16052 assert(!FD->hasAttr<DLLExportAttr>());
16053 Diag(Loc: FD->getLocation(), DiagID: diag::err_attribute_dllimport_function_definition);
16054 FD->setInvalidDecl();
16055 return D;
16056 }
16057
16058 // Some function attributes (like OptimizeNoneAttr) need actions before
16059 // parsing body started.
16060 applyFunctionAttributesBeforeParsingBody(FD: D);
16061
16062 // We want to attach documentation to original Decl (which might be
16063 // a function template).
16064 ActOnDocumentableDecl(D);
16065 if (getCurLexicalContext()->isObjCContainer() &&
16066 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16067 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16068 Diag(Loc: FD->getLocation(), DiagID: diag::warn_function_def_in_objc_container);
16069
16070 maybeAddDeclWithEffects(D: FD);
16071
16072 return D;
16073}
16074
16075void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {
16076 if (!FD || FD->isInvalidDecl())
16077 return;
16078 if (auto *TD = dyn_cast<FunctionTemplateDecl>(Val: FD))
16079 FD = TD->getTemplatedDecl();
16080 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16081 FPOptionsOverride FPO;
16082 FPO.setDisallowOptimizations();
16083 CurFPFeatures.applyChanges(FPO);
16084 FpPragmaStack.CurrentValue =
16085 CurFPFeatures.getChangesFrom(Base: FPOptions(LangOpts));
16086 }
16087}
16088
16089void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
16090 ReturnStmt **Returns = Scope->Returns.data();
16091
16092 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16093 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16094 if (!NRVOCandidate->isNRVOVariable()) {
16095 Diag(Loc: Returns[I]->getRetValue()->getExprLoc(),
16096 DiagID: diag::warn_not_eliding_copy_on_return);
16097 Returns[I]->setNRVOCandidate(nullptr);
16098 }
16099 }
16100 }
16101}
16102
16103bool Sema::canDelayFunctionBody(const Declarator &D) {
16104 // We can't delay parsing the body of a constexpr function template (yet).
16105 if (D.getDeclSpec().hasConstexprSpecifier())
16106 return false;
16107
16108 // We can't delay parsing the body of a function template with a deduced
16109 // return type (yet).
16110 if (D.getDeclSpec().hasAutoTypeSpec()) {
16111 // If the placeholder introduces a non-deduced trailing return type,
16112 // we can still delay parsing it.
16113 if (D.getNumTypeObjects()) {
16114 const auto &Outer = D.getTypeObject(i: D.getNumTypeObjects() - 1);
16115 if (Outer.Kind == DeclaratorChunk::Function &&
16116 Outer.Fun.hasTrailingReturnType()) {
16117 QualType Ty = GetTypeFromParser(Ty: Outer.Fun.getTrailingReturnType());
16118 return Ty.isNull() || !Ty->isUndeducedType();
16119 }
16120 }
16121 return false;
16122 }
16123
16124 return true;
16125}
16126
16127bool Sema::canSkipFunctionBody(Decl *D) {
16128 // We cannot skip the body of a function (or function template) which is
16129 // constexpr, since we may need to evaluate its body in order to parse the
16130 // rest of the file.
16131 // We cannot skip the body of a function with an undeduced return type,
16132 // because any callers of that function need to know the type.
16133 if (const FunctionDecl *FD = D->getAsFunction()) {
16134 if (FD->isConstexpr())
16135 return false;
16136 // We can't simply call Type::isUndeducedType here, because inside template
16137 // auto can be deduced to a dependent type, which is not considered
16138 // "undeduced".
16139 if (FD->getReturnType()->getContainedDeducedType())
16140 return false;
16141 }
16142 return Consumer.shouldSkipFunctionBody(D);
16143}
16144
16145Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
16146 if (!Decl)
16147 return nullptr;
16148 if (FunctionDecl *FD = Decl->getAsFunction())
16149 FD->setHasSkippedBody();
16150 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: Decl))
16151 MD->setHasSkippedBody();
16152 return Decl;
16153}
16154
16155Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
16156 return ActOnFinishFunctionBody(Decl: D, Body: BodyArg, /*IsInstantiation=*/false);
16157}
16158
16159/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16160/// body.
16161class ExitFunctionBodyRAII {
16162public:
16163 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16164 ~ExitFunctionBodyRAII() {
16165 if (!IsLambda)
16166 S.PopExpressionEvaluationContext();
16167 }
16168
16169private:
16170 Sema &S;
16171 bool IsLambda = false;
16172};
16173
16174static void diagnoseImplicitlyRetainedSelf(Sema &S) {
16175 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16176
16177 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16178 auto [It, Inserted] = EscapeInfo.try_emplace(Key: BD);
16179 if (!Inserted)
16180 return It->second;
16181
16182 bool R = false;
16183 const BlockDecl *CurBD = BD;
16184
16185 do {
16186 R = !CurBD->doesNotEscape();
16187 if (R)
16188 break;
16189 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16190 } while (CurBD);
16191
16192 return It->second = R;
16193 };
16194
16195 // If the location where 'self' is implicitly retained is inside a escaping
16196 // block, emit a diagnostic.
16197 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16198 S.ImplicitlyRetainedSelfLocs)
16199 if (IsOrNestedInEscapingBlock(P.second))
16200 S.Diag(Loc: P.first, DiagID: diag::warn_implicitly_retains_self)
16201 << FixItHint::CreateInsertion(InsertionLoc: P.first, Code: "self->");
16202}
16203
16204static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16205 return isa<CXXMethodDecl>(Val: FD) && FD->param_empty() &&
16206 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16207}
16208
16209bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {
16210 return methodHasName(FD, Name: "get_return_object");
16211}
16212
16213bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {
16214 return FD->isStatic() &&
16215 methodHasName(FD, Name: "get_return_object_on_allocation_failure");
16216}
16217
16218void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
16219 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
16220 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16221 return;
16222 // Allow some_promise_type::get_return_object().
16223 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
16224 return;
16225 if (!FD->hasAttr<CoroWrapperAttr>())
16226 Diag(Loc: FD->getLocation(), DiagID: diag::err_coroutine_return_type) << RD;
16227}
16228
16229Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
16230 bool IsInstantiation) {
16231 FunctionScopeInfo *FSI = getCurFunction();
16232 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16233
16234 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16235 FD->addAttr(A: StrictFPAttr::CreateImplicit(Ctx&: Context));
16236
16237 SourceLocation AnalysisLoc;
16238 if (Body)
16239 AnalysisLoc = Body->getEndLoc();
16240 else if (FD)
16241 AnalysisLoc = FD->getEndLoc();
16242 sema::AnalysisBasedWarnings::Policy WP =
16243 AnalysisWarnings.getPolicyInEffectAt(Loc: AnalysisLoc);
16244 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16245
16246 // If we skip function body, we can't tell if a function is a coroutine.
16247 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16248 if (FSI->isCoroutine())
16249 CheckCompletedCoroutineBody(FD, Body);
16250 else
16251 CheckCoroutineWrapper(FD);
16252 }
16253
16254 // Diagnose invalid SYCL kernel entry point function declarations
16255 // and build SYCLKernelCallStmts for valid ones.
16256 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16257 SYCLKernelEntryPointAttr *SKEPAttr =
16258 FD->getAttr<SYCLKernelEntryPointAttr>();
16259 if (FD->isDefaulted()) {
16260 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16261 << /*defaulted function*/ 3;
16262 SKEPAttr->setInvalidAttr();
16263 } else if (FD->isDeleted()) {
16264 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16265 << /*deleted function*/ 2;
16266 SKEPAttr->setInvalidAttr();
16267 } else if (FSI->isCoroutine()) {
16268 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16269 << /*coroutine*/ 7;
16270 SKEPAttr->setInvalidAttr();
16271 } else if (Body && isa<CXXTryStmt>(Val: Body)) {
16272 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16273 << /*function defined with a function try block*/ 8;
16274 SKEPAttr->setInvalidAttr();
16275 }
16276
16277 if (Body && !FD->isTemplated() && !SKEPAttr->isInvalidAttr()) {
16278 StmtResult SR =
16279 SYCL().BuildSYCLKernelCallStmt(FD, Body: cast<CompoundStmt>(Val: Body));
16280 if (SR.isInvalid())
16281 return nullptr;
16282 Body = SR.get();
16283 }
16284 }
16285
16286 {
16287 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16288 // one is already popped when finishing the lambda in BuildLambdaExpr().
16289 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16290 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(DC: FD));
16291 if (FD) {
16292 // The function body and the DefaultedOrDeletedInfo, if present, use
16293 // the same storage; don't overwrite the latter if the former is null
16294 // (the body is initialised to null anyway, so even if the latter isn't
16295 // present, this would still be a no-op).
16296 if (Body)
16297 FD->setBody(Body);
16298 FD->setWillHaveBody(false);
16299
16300 if (getLangOpts().CPlusPlus14) {
16301 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16302 FD->getReturnType()->isUndeducedType()) {
16303 // For a function with a deduced result type to return void,
16304 // the result type as written must be 'auto' or 'decltype(auto)',
16305 // possibly cv-qualified or constrained, but not ref-qualified.
16306 if (!FD->getReturnType()->getAs<AutoType>()) {
16307 Diag(Loc: dcl->getLocation(), DiagID: diag::err_auto_fn_no_return_but_not_auto)
16308 << FD->getReturnType();
16309 FD->setInvalidDecl();
16310 } else {
16311 // Falling off the end of the function is the same as 'return;'.
16312 Expr *Dummy = nullptr;
16313 if (DeduceFunctionTypeFromReturnExpr(
16314 FD, ReturnLoc: dcl->getLocation(), RetExpr: Dummy,
16315 AT: FD->getReturnType()->getAs<AutoType>()))
16316 FD->setInvalidDecl();
16317 }
16318 }
16319 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(DC: FD)) {
16320 // In C++11, we don't use 'auto' deduction rules for lambda call
16321 // operators because we don't support return type deduction.
16322 auto *LSI = getCurLambda();
16323 if (LSI->HasImplicitReturnType) {
16324 deduceClosureReturnType(CSI&: *LSI);
16325
16326 // C++11 [expr.prim.lambda]p4:
16327 // [...] if there are no return statements in the compound-statement
16328 // [the deduced type is] the type void
16329 QualType RetType =
16330 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16331
16332 // Update the return type to the deduced type.
16333 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16334 FD->setType(Context.getFunctionType(ResultTy: RetType, Args: Proto->getParamTypes(),
16335 EPI: Proto->getExtProtoInfo()));
16336 }
16337 }
16338
16339 // If the function implicitly returns zero (like 'main') or is naked,
16340 // don't complain about missing return statements.
16341 // Clang implicitly returns 0 in C89 mode, but that's considered an
16342 // extension. The check is necessary to ensure the expected extension
16343 // warning is emitted in C89 mode.
16344 if ((FD->hasImplicitReturnZero() &&
16345 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16346 FD->hasAttr<NakedAttr>())
16347 WP.disableCheckFallThrough();
16348
16349 // MSVC permits the use of pure specifier (=0) on function definition,
16350 // defined at class scope, warn about this non-standard construct.
16351 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16352 !FD->isOutOfLine())
16353 Diag(Loc: FD->getLocation(), DiagID: diag::ext_pure_function_definition);
16354
16355 if (!FD->isInvalidDecl()) {
16356 // Don't diagnose unused parameters of defaulted, deleted or naked
16357 // functions.
16358 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16359 !FD->hasAttr<NakedAttr>())
16360 DiagnoseUnusedParameters(Parameters: FD->parameters());
16361 DiagnoseSizeOfParametersAndReturnValue(Parameters: FD->parameters(),
16362 ReturnTy: FD->getReturnType(), D: FD);
16363
16364 // If this is a structor, we need a vtable.
16365 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: FD))
16366 MarkVTableUsed(Loc: FD->getLocation(), Class: Constructor->getParent());
16367 else if (CXXDestructorDecl *Destructor =
16368 dyn_cast<CXXDestructorDecl>(Val: FD))
16369 MarkVTableUsed(Loc: FD->getLocation(), Class: Destructor->getParent());
16370
16371 // Try to apply the named return value optimization. We have to check
16372 // if we can do this here because lambdas keep return statements around
16373 // to deduce an implicit return type.
16374 if (FD->getReturnType()->isRecordType() &&
16375 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
16376 computeNRVO(Body, Scope: FSI);
16377 }
16378
16379 // GNU warning -Wmissing-prototypes:
16380 // Warn if a global function is defined without a previous
16381 // prototype declaration. This warning is issued even if the
16382 // definition itself provides a prototype. The aim is to detect
16383 // global functions that fail to be declared in header files.
16384 const FunctionDecl *PossiblePrototype = nullptr;
16385 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16386 Diag(Loc: FD->getLocation(), DiagID: diag::warn_missing_prototype) << FD;
16387
16388 if (PossiblePrototype) {
16389 // We found a declaration that is not a prototype,
16390 // but that could be a zero-parameter prototype
16391 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16392 TypeLoc TL = TI->getTypeLoc();
16393 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
16394 Diag(Loc: PossiblePrototype->getLocation(),
16395 DiagID: diag::note_declaration_not_a_prototype)
16396 << (FD->getNumParams() != 0)
16397 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
16398 InsertionLoc: FTL.getRParenLoc(), Code: "void")
16399 : FixItHint{});
16400 }
16401 } else {
16402 // Returns true if the token beginning at this Loc is `const`.
16403 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16404 const LangOptions &LangOpts) {
16405 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16406 if (LocInfo.first.isInvalid())
16407 return false;
16408
16409 bool Invalid = false;
16410 StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid);
16411 if (Invalid)
16412 return false;
16413
16414 if (LocInfo.second > Buffer.size())
16415 return false;
16416
16417 const char *LexStart = Buffer.data() + LocInfo.second;
16418 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16419
16420 return StartTok.consume_front(Prefix: "const") &&
16421 (StartTok.empty() || isWhitespace(c: StartTok[0]) ||
16422 StartTok.starts_with(Prefix: "/*") || StartTok.starts_with(Prefix: "//"));
16423 };
16424
16425 auto findBeginLoc = [&]() {
16426 // If the return type has `const` qualifier, we want to insert
16427 // `static` before `const` (and not before the typename).
16428 if ((FD->getReturnType()->isAnyPointerType() &&
16429 FD->getReturnType()->getPointeeType().isConstQualified()) ||
16430 FD->getReturnType().isConstQualified()) {
16431 // But only do this if we can determine where the `const` is.
16432
16433 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16434 getLangOpts()))
16435
16436 return FD->getBeginLoc();
16437 }
16438 return FD->getTypeSpecStartLoc();
16439 };
16440 Diag(Loc: FD->getTypeSpecStartLoc(),
16441 DiagID: diag::note_static_for_internal_linkage)
16442 << /* function */ 1
16443 << (FD->getStorageClass() == SC_None
16444 ? FixItHint::CreateInsertion(InsertionLoc: findBeginLoc(), Code: "static ")
16445 : FixItHint{});
16446 }
16447 }
16448
16449 // We might not have found a prototype because we didn't wish to warn on
16450 // the lack of a missing prototype. Try again without the checks for
16451 // whether we want to warn on the missing prototype.
16452 if (!PossiblePrototype)
16453 (void)FindPossiblePrototype(FD, PossiblePrototype);
16454
16455 // If the function being defined does not have a prototype, then we may
16456 // need to diagnose it as changing behavior in C23 because we now know
16457 // whether the function accepts arguments or not. This only handles the
16458 // case where the definition has no prototype but does have parameters
16459 // and either there is no previous potential prototype, or the previous
16460 // potential prototype also has no actual prototype. This handles cases
16461 // like:
16462 // void f(); void f(a) int a; {}
16463 // void g(a) int a; {}
16464 // See MergeFunctionDecl() for other cases of the behavior change
16465 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16466 // type without a prototype.
16467 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16468 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16469 !PossiblePrototype->isImplicit()))) {
16470 // The function definition has parameters, so this will change behavior
16471 // in C23. If there is a possible prototype, it comes before the
16472 // function definition.
16473 // FIXME: The declaration may have already been diagnosed as being
16474 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16475 // there's no way to test for the "changes behavior" condition in
16476 // SemaType.cpp when forming the declaration's function type. So, we do
16477 // this awkward dance instead.
16478 //
16479 // If we have a possible prototype and it declares a function with a
16480 // prototype, we don't want to diagnose it; if we have a possible
16481 // prototype and it has no prototype, it may have already been
16482 // diagnosed in SemaType.cpp as deprecated depending on whether
16483 // -Wstrict-prototypes is enabled. If we already warned about it being
16484 // deprecated, add a note that it also changes behavior. If we didn't
16485 // warn about it being deprecated (because the diagnostic is not
16486 // enabled), warn now that it is deprecated and changes behavior.
16487
16488 // This K&R C function definition definitely changes behavior in C23,
16489 // so diagnose it.
16490 Diag(Loc: FD->getLocation(), DiagID: diag::warn_non_prototype_changes_behavior)
16491 << /*definition*/ 1 << /* not supported in C23 */ 0;
16492
16493 // If we have a possible prototype for the function which is a user-
16494 // visible declaration, we already tested that it has no prototype.
16495 // This will change behavior in C23. This gets a warning rather than a
16496 // note because it's the same behavior-changing problem as with the
16497 // definition.
16498 if (PossiblePrototype)
16499 Diag(Loc: PossiblePrototype->getLocation(),
16500 DiagID: diag::warn_non_prototype_changes_behavior)
16501 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16502 << /*definition*/ 1;
16503 }
16504
16505 // Warn on CPUDispatch with an actual body.
16506 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16507 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Val: Body))
16508 if (!CmpndBody->body_empty())
16509 Diag(Loc: CmpndBody->body_front()->getBeginLoc(),
16510 DiagID: diag::warn_dispatch_body_ignored);
16511
16512 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
16513 const CXXMethodDecl *KeyFunction;
16514 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16515 MD->isVirtual() &&
16516 (KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent())) &&
16517 MD == KeyFunction->getCanonicalDecl()) {
16518 // Update the key-function state if necessary for this ABI.
16519 if (FD->isInlined() &&
16520 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16521 Context.setNonKeyFunction(MD);
16522
16523 // If the newly-chosen key function is already defined, then we
16524 // need to mark the vtable as used retroactively.
16525 KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent());
16526 const FunctionDecl *Definition;
16527 if (KeyFunction && KeyFunction->isDefined(Definition))
16528 MarkVTableUsed(Loc: Definition->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16529 } else {
16530 // We just defined they key function; mark the vtable as used.
16531 MarkVTableUsed(Loc: FD->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16532 }
16533 }
16534 }
16535
16536 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16537 "Function parsing confused");
16538 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Val: dcl)) {
16539 assert(MD == getCurMethodDecl() && "Method parsing confused");
16540 MD->setBody(Body);
16541 if (!MD->isInvalidDecl()) {
16542 DiagnoseSizeOfParametersAndReturnValue(Parameters: MD->parameters(),
16543 ReturnTy: MD->getReturnType(), D: MD);
16544
16545 if (Body)
16546 computeNRVO(Body, Scope: FSI);
16547 }
16548 if (FSI->ObjCShouldCallSuper) {
16549 Diag(Loc: MD->getEndLoc(), DiagID: diag::warn_objc_missing_super_call)
16550 << MD->getSelector().getAsString();
16551 FSI->ObjCShouldCallSuper = false;
16552 }
16553 if (FSI->ObjCWarnForNoDesignatedInitChain) {
16554 const ObjCMethodDecl *InitMethod = nullptr;
16555 bool isDesignated =
16556 MD->isDesignatedInitializerForTheInterface(InitMethod: &InitMethod);
16557 assert(isDesignated && InitMethod);
16558 (void)isDesignated;
16559
16560 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16561 auto IFace = MD->getClassInterface();
16562 if (!IFace)
16563 return false;
16564 auto SuperD = IFace->getSuperClass();
16565 if (!SuperD)
16566 return false;
16567 return SuperD->getIdentifier() ==
16568 ObjC().NSAPIObj->getNSClassId(K: NSAPI::ClassId_NSObject);
16569 };
16570 // Don't issue this warning for unavailable inits or direct subclasses
16571 // of NSObject.
16572 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16573 Diag(Loc: MD->getLocation(),
16574 DiagID: diag::warn_objc_designated_init_missing_super_call);
16575 Diag(Loc: InitMethod->getLocation(),
16576 DiagID: diag::note_objc_designated_init_marked_here);
16577 }
16578 FSI->ObjCWarnForNoDesignatedInitChain = false;
16579 }
16580 if (FSI->ObjCWarnForNoInitDelegation) {
16581 // Don't issue this warning for unavailable inits.
16582 if (!MD->isUnavailable())
16583 Diag(Loc: MD->getLocation(),
16584 DiagID: diag::warn_objc_secondary_init_missing_init_call);
16585 FSI->ObjCWarnForNoInitDelegation = false;
16586 }
16587
16588 diagnoseImplicitlyRetainedSelf(S&: *this);
16589 } else {
16590 // Parsing the function declaration failed in some way. Pop the fake scope
16591 // we pushed on.
16592 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
16593 return nullptr;
16594 }
16595
16596 if (Body && FSI->HasPotentialAvailabilityViolations)
16597 DiagnoseUnguardedAvailabilityViolations(FD: dcl);
16598
16599 assert(!FSI->ObjCShouldCallSuper &&
16600 "This should only be set for ObjC methods, which should have been "
16601 "handled in the block above.");
16602
16603 // Verify and clean out per-function state.
16604 if (Body && (!FD || !FD->isDefaulted())) {
16605 // C++ constructors that have function-try-blocks can't have return
16606 // statements in the handlers of that block. (C++ [except.handle]p14)
16607 // Verify this.
16608 if (FD && isa<CXXConstructorDecl>(Val: FD) && isa<CXXTryStmt>(Val: Body))
16609 DiagnoseReturnInConstructorExceptionHandler(TryBlock: cast<CXXTryStmt>(Val: Body));
16610
16611 // Verify that gotos and switch cases don't jump into scopes illegally.
16612 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16613 DiagnoseInvalidJumps(Body);
16614
16615 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: dcl)) {
16616 if (!Destructor->getParent()->isDependentType())
16617 CheckDestructor(Destructor);
16618
16619 MarkBaseAndMemberDestructorsReferenced(Loc: Destructor->getLocation(),
16620 Record: Destructor->getParent());
16621 }
16622
16623 // If any errors have occurred, clear out any temporaries that may have
16624 // been leftover. This ensures that these temporaries won't be picked up
16625 // for deletion in some later function.
16626 if (hasUncompilableErrorOccurred() ||
16627 hasAnyUnrecoverableErrorsInThisFunction() ||
16628 getDiagnostics().getSuppressAllDiagnostics()) {
16629 DiscardCleanupsInEvaluationContext();
16630 }
16631 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(Val: dcl)) {
16632 // Since the body is valid, issue any analysis-based warnings that are
16633 // enabled.
16634 ActivePolicy = &WP;
16635 }
16636
16637 if (!IsInstantiation && FD &&
16638 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16639 !FD->isInvalidDecl() &&
16640 !CheckConstexprFunctionDefinition(FD, Kind: CheckConstexprKind::Diagnose))
16641 FD->setInvalidDecl();
16642
16643 if (FD && FD->hasAttr<NakedAttr>()) {
16644 for (const Stmt *S : Body->children()) {
16645 // Allow local register variables without initializer as they don't
16646 // require prologue.
16647 bool RegisterVariables = false;
16648 if (auto *DS = dyn_cast<DeclStmt>(Val: S)) {
16649 for (const auto *Decl : DS->decls()) {
16650 if (const auto *Var = dyn_cast<VarDecl>(Val: Decl)) {
16651 RegisterVariables =
16652 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16653 if (!RegisterVariables)
16654 break;
16655 }
16656 }
16657 }
16658 if (RegisterVariables)
16659 continue;
16660 if (!isa<AsmStmt>(Val: S) && !isa<NullStmt>(Val: S)) {
16661 Diag(Loc: S->getBeginLoc(), DiagID: diag::err_non_asm_stmt_in_naked_function);
16662 Diag(Loc: FD->getAttr<NakedAttr>()->getLocation(), DiagID: diag::note_attribute);
16663 FD->setInvalidDecl();
16664 break;
16665 }
16666 }
16667 }
16668
16669 assert(ExprCleanupObjects.size() ==
16670 ExprEvalContexts.back().NumCleanupObjects &&
16671 "Leftover temporaries in function");
16672 assert(!Cleanup.exprNeedsCleanups() &&
16673 "Unaccounted cleanups in function");
16674 assert(MaybeODRUseExprs.empty() &&
16675 "Leftover expressions for odr-use checking");
16676 }
16677 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16678 // the declaration context below. Otherwise, we're unable to transform
16679 // 'this' expressions when transforming immediate context functions.
16680
16681 if (FD)
16682 CheckImmediateEscalatingFunctionDefinition(FD, FSI: getCurFunction());
16683
16684 if (!IsInstantiation)
16685 PopDeclContext();
16686
16687 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
16688 // If any errors have occurred, clear out any temporaries that may have
16689 // been leftover. This ensures that these temporaries won't be picked up for
16690 // deletion in some later function.
16691 if (hasUncompilableErrorOccurred()) {
16692 DiscardCleanupsInEvaluationContext();
16693 }
16694
16695 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
16696 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
16697 auto ES = getEmissionStatus(Decl: FD);
16698 if (ES == Sema::FunctionEmissionStatus::Emitted ||
16699 ES == Sema::FunctionEmissionStatus::Unknown)
16700 DeclsToCheckForDeferredDiags.insert(X: FD);
16701 }
16702
16703 if (FD && !FD->isDeleted())
16704 checkTypeSupport(Ty: FD->getType(), Loc: FD->getLocation(), D: FD);
16705
16706 return dcl;
16707}
16708
16709/// When we finish delayed parsing of an attribute, we must attach it to the
16710/// relevant Decl.
16711void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
16712 ParsedAttributes &Attrs) {
16713 // Always attach attributes to the underlying decl.
16714 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D))
16715 D = TD->getTemplatedDecl();
16716 ProcessDeclAttributeList(S, D, AttrList: Attrs);
16717 ProcessAPINotes(D);
16718
16719 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: D))
16720 if (Method->isStatic())
16721 checkThisInStaticMemberFunctionAttributes(Method);
16722}
16723
16724NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
16725 IdentifierInfo &II, Scope *S) {
16726 // It is not valid to implicitly define a function in C23.
16727 assert(LangOpts.implicitFunctionsAllowed() &&
16728 "Implicit function declarations aren't allowed in this language mode");
16729
16730 // Find the scope in which the identifier is injected and the corresponding
16731 // DeclContext.
16732 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16733 // In that case, we inject the declaration into the translation unit scope
16734 // instead.
16735 Scope *BlockScope = S;
16736 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16737 BlockScope = BlockScope->getParent();
16738
16739 // Loop until we find a DeclContext that is either a function/method or the
16740 // translation unit, which are the only two valid places to implicitly define
16741 // a function. This avoids accidentally defining the function within a tag
16742 // declaration, for example.
16743 Scope *ContextScope = BlockScope;
16744 while (!ContextScope->getEntity() ||
16745 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16746 !ContextScope->getEntity()->isTranslationUnit()))
16747 ContextScope = ContextScope->getParent();
16748 ContextRAII SavedContext(*this, ContextScope->getEntity());
16749
16750 // Before we produce a declaration for an implicitly defined
16751 // function, see whether there was a locally-scoped declaration of
16752 // this name as a function or variable. If so, use that
16753 // (non-visible) declaration, and complain about it.
16754 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(Name: &II);
16755 if (ExternCPrev) {
16756 // We still need to inject the function into the enclosing block scope so
16757 // that later (non-call) uses can see it.
16758 PushOnScopeChains(D: ExternCPrev, S: BlockScope, /*AddToContext*/false);
16759
16760 // C89 footnote 38:
16761 // If in fact it is not defined as having type "function returning int",
16762 // the behavior is undefined.
16763 if (!isa<FunctionDecl>(Val: ExternCPrev) ||
16764 !Context.typesAreCompatible(
16765 T1: cast<FunctionDecl>(Val: ExternCPrev)->getType(),
16766 T2: Context.getFunctionNoProtoType(ResultTy: Context.IntTy))) {
16767 Diag(Loc, DiagID: diag::ext_use_out_of_scope_declaration)
16768 << ExternCPrev << !getLangOpts().C99;
16769 Diag(Loc: ExternCPrev->getLocation(), DiagID: diag::note_previous_declaration);
16770 return ExternCPrev;
16771 }
16772 }
16773
16774 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16775 unsigned diag_id;
16776 if (II.getName().starts_with(Prefix: "__builtin_"))
16777 diag_id = diag::warn_builtin_unknown;
16778 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16779 else if (getLangOpts().C99)
16780 diag_id = diag::ext_implicit_function_decl_c99;
16781 else
16782 diag_id = diag::warn_implicit_function_decl;
16783
16784 TypoCorrection Corrected;
16785 // Because typo correction is expensive, only do it if the implicit
16786 // function declaration is going to be treated as an error.
16787 //
16788 // Perform the correction before issuing the main diagnostic, as some
16789 // consumers use typo-correction callbacks to enhance the main diagnostic.
16790 if (S && !ExternCPrev &&
16791 (Diags.getDiagnosticLevel(DiagID: diag_id, Loc) >= DiagnosticsEngine::Error)) {
16792 DeclFilterCCC<FunctionDecl> CCC{};
16793 Corrected = CorrectTypo(Typo: DeclarationNameInfo(&II, Loc), LookupKind: LookupOrdinaryName,
16794 S, SS: nullptr, CCC, Mode: CorrectTypoKind::NonError);
16795 }
16796
16797 Diag(Loc, DiagID: diag_id) << &II;
16798 if (Corrected) {
16799 // If the correction is going to suggest an implicitly defined function,
16800 // skip the correction as not being a particularly good idea.
16801 bool Diagnose = true;
16802 if (const auto *D = Corrected.getCorrectionDecl())
16803 Diagnose = !D->isImplicit();
16804 if (Diagnose)
16805 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::note_function_suggestion),
16806 /*ErrorRecovery*/ false);
16807 }
16808
16809 // If we found a prior declaration of this function, don't bother building
16810 // another one. We've already pushed that one into scope, so there's nothing
16811 // more to do.
16812 if (ExternCPrev)
16813 return ExternCPrev;
16814
16815 // Set a Declarator for the implicit definition: int foo();
16816 const char *Dummy;
16817 AttributeFactory attrFactory;
16818 DeclSpec DS(attrFactory);
16819 unsigned DiagID;
16820 bool Error = DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc, PrevSpec&: Dummy, DiagID,
16821 Policy: Context.getPrintingPolicy());
16822 (void)Error; // Silence warning.
16823 assert(!Error && "Error setting up implicit decl!");
16824 SourceLocation NoLoc;
16825 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
16826 D.AddTypeInfo(TI: DeclaratorChunk::getFunction(/*HasProto=*/false,
16827 /*IsAmbiguous=*/false,
16828 /*LParenLoc=*/NoLoc,
16829 /*Params=*/nullptr,
16830 /*NumParams=*/0,
16831 /*EllipsisLoc=*/NoLoc,
16832 /*RParenLoc=*/NoLoc,
16833 /*RefQualifierIsLvalueRef=*/true,
16834 /*RefQualifierLoc=*/NoLoc,
16835 /*MutableLoc=*/NoLoc, ESpecType: EST_None,
16836 /*ESpecRange=*/SourceRange(),
16837 /*Exceptions=*/nullptr,
16838 /*ExceptionRanges=*/nullptr,
16839 /*NumExceptions=*/0,
16840 /*NoexceptExpr=*/nullptr,
16841 /*ExceptionSpecTokens=*/nullptr,
16842 /*DeclsInPrototype=*/{}, LocalRangeBegin: Loc, LocalRangeEnd: Loc,
16843 TheDeclarator&: D),
16844 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
16845 D.SetIdentifier(Id: &II, IdLoc: Loc);
16846
16847 // Insert this function into the enclosing block scope.
16848 FunctionDecl *FD = cast<FunctionDecl>(Val: ActOnDeclarator(S: BlockScope, D));
16849 FD->setImplicit();
16850
16851 AddKnownFunctionAttributes(FD);
16852
16853 return FD;
16854}
16855
16856void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
16857 FunctionDecl *FD) {
16858 if (FD->isInvalidDecl())
16859 return;
16860
16861 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16862 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16863 return;
16864
16865 UnsignedOrNone AlignmentParam = std::nullopt;
16866 bool IsNothrow = false;
16867 if (!FD->isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam, IsNothrow: &IsNothrow))
16868 return;
16869
16870 // C++2a [basic.stc.dynamic.allocation]p4:
16871 // An allocation function that has a non-throwing exception specification
16872 // indicates failure by returning a null pointer value. Any other allocation
16873 // function never returns a null pointer value and indicates failure only by
16874 // throwing an exception [...]
16875 //
16876 // However, -fcheck-new invalidates this possible assumption, so don't add
16877 // NonNull when that is enabled.
16878 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16879 !getLangOpts().CheckNew)
16880 FD->addAttr(A: ReturnsNonNullAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
16881
16882 // C++2a [basic.stc.dynamic.allocation]p2:
16883 // An allocation function attempts to allocate the requested amount of
16884 // storage. [...] If the request succeeds, the value returned by a
16885 // replaceable allocation function is a [...] pointer value p0 different
16886 // from any previously returned value p1 [...]
16887 //
16888 // However, this particular information is being added in codegen,
16889 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16890
16891 // C++2a [basic.stc.dynamic.allocation]p2:
16892 // An allocation function attempts to allocate the requested amount of
16893 // storage. If it is successful, it returns the address of the start of a
16894 // block of storage whose length in bytes is at least as large as the
16895 // requested size.
16896 if (!FD->hasAttr<AllocSizeAttr>()) {
16897 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
16898 Ctx&: Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16899 /*NumElemsParam=*/ParamIdx(), Range: FD->getLocation()));
16900 }
16901
16902 // C++2a [basic.stc.dynamic.allocation]p3:
16903 // For an allocation function [...], the pointer returned on a successful
16904 // call shall represent the address of storage that is aligned as follows:
16905 // (3.1) If the allocation function takes an argument of type
16906 // std​::​align_­val_­t, the storage will have the alignment
16907 // specified by the value of this argument.
16908 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16909 FD->addAttr(A: AllocAlignAttr::CreateImplicit(
16910 Ctx&: Context, ParamIndex: ParamIdx(*AlignmentParam, FD), Range: FD->getLocation()));
16911 }
16912
16913 // FIXME:
16914 // C++2a [basic.stc.dynamic.allocation]p3:
16915 // For an allocation function [...], the pointer returned on a successful
16916 // call shall represent the address of storage that is aligned as follows:
16917 // (3.2) Otherwise, if the allocation function is named operator new[],
16918 // the storage is aligned for any object that does not have
16919 // new-extended alignment ([basic.align]) and is no larger than the
16920 // requested size.
16921 // (3.3) Otherwise, the storage is aligned for any object that does not
16922 // have new-extended alignment and is of the requested size.
16923}
16924
16925void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
16926 if (FD->isInvalidDecl())
16927 return;
16928
16929 // If this is a built-in function, map its builtin attributes to
16930 // actual attributes.
16931 if (unsigned BuiltinID = FD->getBuiltinID()) {
16932 // Handle printf-formatting attributes.
16933 unsigned FormatIdx;
16934 bool HasVAListArg;
16935 if (Context.BuiltinInfo.isPrintfLike(ID: BuiltinID, FormatIdx, HasVAListArg)) {
16936 if (!FD->hasAttr<FormatAttr>()) {
16937 const char *fmt = "printf";
16938 unsigned int NumParams = FD->getNumParams();
16939 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16940 FD->getParamDecl(i: FormatIdx)->getType()->isObjCObjectPointerType())
16941 fmt = "NSString";
16942 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
16943 Type: &Context.Idents.get(Name: fmt),
16944 FormatIdx: FormatIdx+1,
16945 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
16946 Range: FD->getLocation()));
16947 }
16948 }
16949 if (Context.BuiltinInfo.isScanfLike(ID: BuiltinID, FormatIdx,
16950 HasVAListArg)) {
16951 if (!FD->hasAttr<FormatAttr>())
16952 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
16953 Type: &Context.Idents.get(Name: "scanf"),
16954 FormatIdx: FormatIdx+1,
16955 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
16956 Range: FD->getLocation()));
16957 }
16958
16959 // Handle automatically recognized callbacks.
16960 SmallVector<int, 4> Encoding;
16961 if (!FD->hasAttr<CallbackAttr>() &&
16962 Context.BuiltinInfo.performsCallback(ID: BuiltinID, Encoding))
16963 FD->addAttr(A: CallbackAttr::CreateImplicit(
16964 Ctx&: Context, Encoding: Encoding.data(), EncodingSize: Encoding.size(), Range: FD->getLocation()));
16965
16966 // Mark const if we don't care about errno and/or floating point exceptions
16967 // that are the only thing preventing the function from being const. This
16968 // allows IRgen to use LLVM intrinsics for such functions.
16969 bool NoExceptions =
16970 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
16971 bool ConstWithoutErrnoAndExceptions =
16972 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(ID: BuiltinID);
16973 bool ConstWithoutExceptions =
16974 Context.BuiltinInfo.isConstWithoutExceptions(ID: BuiltinID);
16975 if (!FD->hasAttr<ConstAttr>() &&
16976 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16977 (!ConstWithoutErrnoAndExceptions ||
16978 (!getLangOpts().MathErrno && NoExceptions)) &&
16979 (!ConstWithoutExceptions || NoExceptions))
16980 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
16981
16982 // We make "fma" on GNU or Windows const because we know it does not set
16983 // errno in those environments even though it could set errno based on the
16984 // C standard.
16985 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16986 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16987 !FD->hasAttr<ConstAttr>()) {
16988 switch (BuiltinID) {
16989 case Builtin::BI__builtin_fma:
16990 case Builtin::BI__builtin_fmaf:
16991 case Builtin::BI__builtin_fmal:
16992 case Builtin::BIfma:
16993 case Builtin::BIfmaf:
16994 case Builtin::BIfmal:
16995 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
16996 break;
16997 default:
16998 break;
16999 }
17000 }
17001
17002 if (Context.BuiltinInfo.isReturnsTwice(ID: BuiltinID) &&
17003 !FD->hasAttr<ReturnsTwiceAttr>())
17004 FD->addAttr(A: ReturnsTwiceAttr::CreateImplicit(Ctx&: Context,
17005 Range: FD->getLocation()));
17006 if (Context.BuiltinInfo.isNoThrow(ID: BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17007 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17008 if (Context.BuiltinInfo.isPure(ID: BuiltinID) && !FD->hasAttr<PureAttr>())
17009 FD->addAttr(A: PureAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17010 if (Context.BuiltinInfo.isConst(ID: BuiltinID) && !FD->hasAttr<ConstAttr>())
17011 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17012 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID) &&
17013 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17014 // Add the appropriate attribute, depending on the CUDA compilation mode
17015 // and which target the builtin belongs to. For example, during host
17016 // compilation, aux builtins are __device__, while the rest are __host__.
17017 if (getLangOpts().CUDAIsDevice !=
17018 Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID))
17019 FD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17020 else
17021 FD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17022 }
17023
17024 // Add known guaranteed alignment for allocation functions.
17025 switch (BuiltinID) {
17026 case Builtin::BImemalign:
17027 case Builtin::BIaligned_alloc:
17028 if (!FD->hasAttr<AllocAlignAttr>())
17029 FD->addAttr(A: AllocAlignAttr::CreateImplicit(Ctx&: Context, ParamIndex: ParamIdx(1, FD),
17030 Range: FD->getLocation()));
17031 break;
17032 default:
17033 break;
17034 }
17035
17036 // Add allocsize attribute for allocation functions.
17037 switch (BuiltinID) {
17038 case Builtin::BIcalloc:
17039 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17040 Ctx&: Context, ElemSizeParam: ParamIdx(1, FD), NumElemsParam: ParamIdx(2, FD), Range: FD->getLocation()));
17041 break;
17042 case Builtin::BImemalign:
17043 case Builtin::BIaligned_alloc:
17044 case Builtin::BIrealloc:
17045 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(2, FD),
17046 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17047 break;
17048 case Builtin::BImalloc:
17049 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(1, FD),
17050 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17051 break;
17052 default:
17053 break;
17054 }
17055 }
17056
17057 LazyProcessLifetimeCaptureByParams(FD);
17058 inferLifetimeBoundAttribute(FD);
17059 inferLifetimeCaptureByAttribute(FD);
17060 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
17061
17062 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17063 // throw, add an implicit nothrow attribute to any extern "C" function we come
17064 // across.
17065 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17066 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17067 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17068 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17069 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17070 }
17071
17072 IdentifierInfo *Name = FD->getIdentifier();
17073 if (!Name)
17074 return;
17075 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
17076 (isa<LinkageSpecDecl>(Val: FD->getDeclContext()) &&
17077 cast<LinkageSpecDecl>(Val: FD->getDeclContext())->getLanguage() ==
17078 LinkageSpecLanguageIDs::C)) {
17079 // Okay: this could be a libc/libm/Objective-C function we know
17080 // about.
17081 } else
17082 return;
17083
17084 if (Name->isStr(Str: "asprintf") || Name->isStr(Str: "vasprintf")) {
17085 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17086 // target-specific builtins, perhaps?
17087 if (!FD->hasAttr<FormatAttr>())
17088 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17089 Type: &Context.Idents.get(Name: "printf"), FormatIdx: 2,
17090 FirstArg: Name->isStr(Str: "vasprintf") ? 0 : 3,
17091 Range: FD->getLocation()));
17092 }
17093
17094 if (Name->isStr(Str: "__CFStringMakeConstantString")) {
17095 // We already have a __builtin___CFStringMakeConstantString,
17096 // but builds that use -fno-constant-cfstrings don't go through that.
17097 if (!FD->hasAttr<FormatArgAttr>())
17098 FD->addAttr(A: FormatArgAttr::CreateImplicit(Ctx&: Context, FormatIdx: ParamIdx(1, FD),
17099 Range: FD->getLocation()));
17100 }
17101}
17102
17103TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
17104 TypeSourceInfo *TInfo) {
17105 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17106 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17107
17108 if (!TInfo) {
17109 assert(D.isInvalidType() && "no declarator info for valid type");
17110 TInfo = Context.getTrivialTypeSourceInfo(T);
17111 }
17112
17113 // Scope manipulation handled by caller.
17114 TypedefDecl *NewTD =
17115 TypedefDecl::Create(C&: Context, DC: CurContext, StartLoc: D.getBeginLoc(),
17116 IdLoc: D.getIdentifierLoc(), Id: D.getIdentifier(), TInfo);
17117
17118 // Bail out immediately if we have an invalid declaration.
17119 if (D.isInvalidType()) {
17120 NewTD->setInvalidDecl();
17121 return NewTD;
17122 }
17123
17124 if (D.getDeclSpec().isModulePrivateSpecified()) {
17125 if (CurContext->isFunctionOrMethod())
17126 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_module_private_local)
17127 << 2 << NewTD
17128 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
17129 << FixItHint::CreateRemoval(
17130 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
17131 else
17132 NewTD->setModulePrivate();
17133 }
17134
17135 // C++ [dcl.typedef]p8:
17136 // If the typedef declaration defines an unnamed class (or
17137 // enum), the first typedef-name declared by the declaration
17138 // to be that class type (or enum type) is used to denote the
17139 // class type (or enum type) for linkage purposes only.
17140 // We need to check whether the type was declared in the declaration.
17141 switch (D.getDeclSpec().getTypeSpecType()) {
17142 case TST_enum:
17143 case TST_struct:
17144 case TST_interface:
17145 case TST_union:
17146 case TST_class: {
17147 TagDecl *tagFromDeclSpec = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
17148 setTagNameForLinkagePurposes(TagFromDeclSpec: tagFromDeclSpec, NewTD);
17149 break;
17150 }
17151
17152 default:
17153 break;
17154 }
17155
17156 return NewTD;
17157}
17158
17159bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
17160 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17161 QualType T = TI->getType();
17162
17163 if (T->isDependentType())
17164 return false;
17165
17166 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17167 // integral type; any cv-qualification is ignored.
17168 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17169 // non-atomic version of the type specified by the type specifiers in the
17170 // specifier qualifier list.
17171 // Because of how odd C's rule is, we'll let the user know that operations
17172 // involving the enumeration type will be non-atomic.
17173 if (T->isAtomicType())
17174 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_atomic_stripped_in_enum);
17175
17176 Qualifiers Q = T.getQualifiers();
17177 std::optional<unsigned> QualSelect;
17178 if (Q.hasConst() && Q.hasVolatile())
17179 QualSelect = diag::CVQualList::Both;
17180 else if (Q.hasConst())
17181 QualSelect = diag::CVQualList::Const;
17182 else if (Q.hasVolatile())
17183 QualSelect = diag::CVQualList::Volatile;
17184
17185 if (QualSelect)
17186 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_cv_stripped_in_enum) << *QualSelect;
17187
17188 T = T.getAtomicUnqualifiedType();
17189
17190 // This doesn't use 'isIntegralType' despite the error message mentioning
17191 // integral type because isIntegralType would also allow enum types in C.
17192 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17193 if (BT->isInteger())
17194 return false;
17195
17196 return Diag(Loc: UnderlyingLoc, DiagID: diag::err_enum_invalid_underlying)
17197 << T << T->isBitIntType();
17198}
17199
17200bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
17201 QualType EnumUnderlyingTy, bool IsFixed,
17202 const EnumDecl *Prev) {
17203 if (IsScoped != Prev->isScoped()) {
17204 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_scoped_mismatch)
17205 << Prev->isScoped();
17206 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17207 return true;
17208 }
17209
17210 if (IsFixed && Prev->isFixed()) {
17211 if (!EnumUnderlyingTy->isDependentType() &&
17212 !Prev->getIntegerType()->isDependentType() &&
17213 !Context.hasSameUnqualifiedType(T1: EnumUnderlyingTy,
17214 T2: Prev->getIntegerType())) {
17215 // TODO: Highlight the underlying type of the redeclaration.
17216 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_type_mismatch)
17217 << EnumUnderlyingTy << Prev->getIntegerType();
17218 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration)
17219 << Prev->getIntegerTypeRange();
17220 return true;
17221 }
17222 } else if (IsFixed != Prev->isFixed()) {
17223 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_fixed_mismatch)
17224 << Prev->isFixed();
17225 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17226 return true;
17227 }
17228
17229 return false;
17230}
17231
17232/// Get diagnostic %select index for tag kind for
17233/// redeclaration diagnostic message.
17234/// WARNING: Indexes apply to particular diagnostics only!
17235///
17236/// \returns diagnostic %select index.
17237static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
17238 switch (Tag) {
17239 case TagTypeKind::Struct:
17240 return 0;
17241 case TagTypeKind::Interface:
17242 return 1;
17243 case TagTypeKind::Class:
17244 return 2;
17245 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17246 }
17247}
17248
17249/// Determine if tag kind is a class-key compatible with
17250/// class for redeclaration (class, struct, or __interface).
17251///
17252/// \returns true iff the tag kind is compatible.
17253static bool isClassCompatTagKind(TagTypeKind Tag)
17254{
17255 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17256 Tag == TagTypeKind::Interface;
17257}
17258
17259NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, TagTypeKind TTK) {
17260 if (isa<TypedefDecl>(Val: PrevDecl))
17261 return NonTagKind::Typedef;
17262 else if (isa<TypeAliasDecl>(Val: PrevDecl))
17263 return NonTagKind::TypeAlias;
17264 else if (isa<ClassTemplateDecl>(Val: PrevDecl))
17265 return NonTagKind::Template;
17266 else if (isa<TypeAliasTemplateDecl>(Val: PrevDecl))
17267 return NonTagKind::TypeAliasTemplate;
17268 else if (isa<TemplateTemplateParmDecl>(Val: PrevDecl))
17269 return NonTagKind::TemplateTemplateArgument;
17270 switch (TTK) {
17271 case TagTypeKind::Struct:
17272 case TagTypeKind::Interface:
17273 case TagTypeKind::Class:
17274 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17275 : NonTagKind::NonStruct;
17276 case TagTypeKind::Union:
17277 return NonTagKind::NonUnion;
17278 case TagTypeKind::Enum:
17279 return NonTagKind::NonEnum;
17280 }
17281 llvm_unreachable("invalid TTK");
17282}
17283
17284bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
17285 TagTypeKind NewTag, bool isDefinition,
17286 SourceLocation NewTagLoc,
17287 const IdentifierInfo *Name) {
17288 // C++ [dcl.type.elab]p3:
17289 // The class-key or enum keyword present in the
17290 // elaborated-type-specifier shall agree in kind with the
17291 // declaration to which the name in the elaborated-type-specifier
17292 // refers. This rule also applies to the form of
17293 // elaborated-type-specifier that declares a class-name or
17294 // friend class since it can be construed as referring to the
17295 // definition of the class. Thus, in any
17296 // elaborated-type-specifier, the enum keyword shall be used to
17297 // refer to an enumeration (7.2), the union class-key shall be
17298 // used to refer to a union (clause 9), and either the class or
17299 // struct class-key shall be used to refer to a class (clause 9)
17300 // declared using the class or struct class-key.
17301 TagTypeKind OldTag = Previous->getTagKind();
17302 if (OldTag != NewTag &&
17303 !(isClassCompatTagKind(Tag: OldTag) && isClassCompatTagKind(Tag: NewTag)))
17304 return false;
17305
17306 // Tags are compatible, but we might still want to warn on mismatched tags.
17307 // Non-class tags can't be mismatched at this point.
17308 if (!isClassCompatTagKind(Tag: NewTag))
17309 return true;
17310
17311 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17312 // by our warning analysis. We don't want to warn about mismatches with (eg)
17313 // declarations in system headers that are designed to be specialized, but if
17314 // a user asks us to warn, we should warn if their code contains mismatched
17315 // declarations.
17316 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17317 return getDiagnostics().isIgnored(DiagID: diag::warn_struct_class_tag_mismatch,
17318 Loc);
17319 };
17320 if (IsIgnoredLoc(NewTagLoc))
17321 return true;
17322
17323 auto IsIgnored = [&](const TagDecl *Tag) {
17324 return IsIgnoredLoc(Tag->getLocation());
17325 };
17326 while (IsIgnored(Previous)) {
17327 Previous = Previous->getPreviousDecl();
17328 if (!Previous)
17329 return true;
17330 OldTag = Previous->getTagKind();
17331 }
17332
17333 bool isTemplate = false;
17334 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Previous))
17335 isTemplate = Record->getDescribedClassTemplate();
17336
17337 if (inTemplateInstantiation()) {
17338 if (OldTag != NewTag) {
17339 // In a template instantiation, do not offer fix-its for tag mismatches
17340 // since they usually mess up the template instead of fixing the problem.
17341 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
17342 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17343 << getRedeclDiagFromTagKind(Tag: OldTag);
17344 // FIXME: Note previous location?
17345 }
17346 return true;
17347 }
17348
17349 if (isDefinition) {
17350 // On definitions, check all previous tags and issue a fix-it for each
17351 // one that doesn't match the current tag.
17352 if (Previous->getDefinition()) {
17353 // Don't suggest fix-its for redefinitions.
17354 return true;
17355 }
17356
17357 bool previousMismatch = false;
17358 for (const TagDecl *I : Previous->redecls()) {
17359 if (I->getTagKind() != NewTag) {
17360 // Ignore previous declarations for which the warning was disabled.
17361 if (IsIgnored(I))
17362 continue;
17363
17364 if (!previousMismatch) {
17365 previousMismatch = true;
17366 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_previous_tag_mismatch)
17367 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17368 << getRedeclDiagFromTagKind(Tag: I->getTagKind());
17369 }
17370 Diag(Loc: I->getInnerLocStart(), DiagID: diag::note_struct_class_suggestion)
17371 << getRedeclDiagFromTagKind(Tag: NewTag)
17372 << FixItHint::CreateReplacement(RemoveRange: I->getInnerLocStart(),
17373 Code: TypeWithKeyword::getTagTypeKindName(Kind: NewTag));
17374 }
17375 }
17376 return true;
17377 }
17378
17379 // Identify the prevailing tag kind: this is the kind of the definition (if
17380 // there is a non-ignored definition), or otherwise the kind of the prior
17381 // (non-ignored) declaration.
17382 const TagDecl *PrevDef = Previous->getDefinition();
17383 if (PrevDef && IsIgnored(PrevDef))
17384 PrevDef = nullptr;
17385 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17386 if (Redecl->getTagKind() != NewTag) {
17387 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
17388 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17389 << getRedeclDiagFromTagKind(Tag: OldTag);
17390 Diag(Loc: Redecl->getLocation(), DiagID: diag::note_previous_use);
17391
17392 // If there is a previous definition, suggest a fix-it.
17393 if (PrevDef) {
17394 Diag(Loc: NewTagLoc, DiagID: diag::note_struct_class_suggestion)
17395 << getRedeclDiagFromTagKind(Tag: Redecl->getTagKind())
17396 << FixItHint::CreateReplacement(RemoveRange: SourceRange(NewTagLoc),
17397 Code: TypeWithKeyword::getTagTypeKindName(Kind: Redecl->getTagKind()));
17398 }
17399 }
17400
17401 return true;
17402}
17403
17404/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17405/// from an outer enclosing namespace or file scope inside a friend declaration.
17406/// This should provide the commented out code in the following snippet:
17407/// namespace N {
17408/// struct X;
17409/// namespace M {
17410/// struct Y { friend struct /*N::*/ X; };
17411/// }
17412/// }
17413static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
17414 SourceLocation NameLoc) {
17415 // While the decl is in a namespace, do repeated lookup of that name and see
17416 // if we get the same namespace back. If we do not, continue until
17417 // translation unit scope, at which point we have a fully qualified NNS.
17418 SmallVector<IdentifierInfo *, 4> Namespaces;
17419 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17420 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17421 // This tag should be declared in a namespace, which can only be enclosed by
17422 // other namespaces. Bail if there's an anonymous namespace in the chain.
17423 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: DC);
17424 if (!Namespace || Namespace->isAnonymousNamespace())
17425 return FixItHint();
17426 IdentifierInfo *II = Namespace->getIdentifier();
17427 Namespaces.push_back(Elt: II);
17428 NamedDecl *Lookup = SemaRef.LookupSingleName(
17429 S, Name: II, Loc: NameLoc, NameKind: Sema::LookupNestedNameSpecifierName);
17430 if (Lookup == Namespace)
17431 break;
17432 }
17433
17434 // Once we have all the namespaces, reverse them to go outermost first, and
17435 // build an NNS.
17436 SmallString<64> Insertion;
17437 llvm::raw_svector_ostream OS(Insertion);
17438 if (DC->isTranslationUnit())
17439 OS << "::";
17440 std::reverse(first: Namespaces.begin(), last: Namespaces.end());
17441 for (auto *II : Namespaces)
17442 OS << II->getName() << "::";
17443 return FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: Insertion);
17444}
17445
17446/// Determine whether a tag originally declared in context \p OldDC can
17447/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17448/// found a declaration in \p OldDC as a previous decl, perhaps through a
17449/// using-declaration).
17450static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
17451 DeclContext *NewDC) {
17452 OldDC = OldDC->getRedeclContext();
17453 NewDC = NewDC->getRedeclContext();
17454
17455 if (OldDC->Equals(DC: NewDC))
17456 return true;
17457
17458 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17459 // encloses the other).
17460 if (S.getLangOpts().MSVCCompat &&
17461 (OldDC->Encloses(DC: NewDC) || NewDC->Encloses(DC: OldDC)))
17462 return true;
17463
17464 return false;
17465}
17466
17467DeclResult
17468Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17469 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17470 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17471 SourceLocation ModulePrivateLoc,
17472 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17473 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17474 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17475 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17476 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17477 // If this is not a definition, it must have a name.
17478 IdentifierInfo *OrigName = Name;
17479 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17480 "Nameless record must be a definition!");
17481 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17482
17483 OwnedDecl = false;
17484 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
17485 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17486
17487 // FIXME: Check member specializations more carefully.
17488 bool isMemberSpecialization = false;
17489 bool Invalid = false;
17490
17491 // We only need to do this matching if we have template parameters
17492 // or a scope specifier, which also conveniently avoids this work
17493 // for non-C++ cases.
17494 if (TemplateParameterLists.size() > 0 ||
17495 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17496 TemplateParameterList *TemplateParams =
17497 MatchTemplateParametersToScopeSpecifier(
17498 DeclStartLoc: KWLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TemplateParameterLists,
17499 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
17500
17501 // C++23 [dcl.type.elab] p2:
17502 // If an elaborated-type-specifier is the sole constituent of a
17503 // declaration, the declaration is ill-formed unless it is an explicit
17504 // specialization, an explicit instantiation or it has one of the
17505 // following forms: [...]
17506 // C++23 [dcl.enum] p1:
17507 // If the enum-head-name of an opaque-enum-declaration contains a
17508 // nested-name-specifier, the declaration shall be an explicit
17509 // specialization.
17510 //
17511 // FIXME: Class template partial specializations can be forward declared
17512 // per CWG2213, but the resolution failed to allow qualified forward
17513 // declarations. This is almost certainly unintentional, so we allow them.
17514 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17515 !isMemberSpecialization)
17516 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_standalone_class_nested_name_specifier)
17517 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();
17518
17519 if (TemplateParams) {
17520 if (Kind == TagTypeKind::Enum) {
17521 Diag(Loc: KWLoc, DiagID: diag::err_enum_template);
17522 return true;
17523 }
17524
17525 if (TemplateParams->size() > 0) {
17526 // This is a declaration or definition of a class template (which may
17527 // be a member of another template).
17528
17529 if (Invalid)
17530 return true;
17531
17532 OwnedDecl = false;
17533 DeclResult Result = CheckClassTemplate(
17534 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attr: Attrs, TemplateParams,
17535 AS, ModulePrivateLoc,
17536 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
17537 OuterTemplateParamLists: TemplateParameterLists.data(), SkipBody);
17538 return Result.get();
17539 } else {
17540 // The "template<>" header is extraneous.
17541 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
17542 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17543 isMemberSpecialization = true;
17544 }
17545 }
17546
17547 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17548 CheckTemplateDeclScope(S, TemplateParams: TemplateParameterLists.back()))
17549 return true;
17550 }
17551
17552 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17553 // C++23 [dcl.type.elab]p4:
17554 // If an elaborated-type-specifier appears with the friend specifier as
17555 // an entire member-declaration, the member-declaration shall have one
17556 // of the following forms:
17557 // friend class-key nested-name-specifier(opt) identifier ;
17558 // friend class-key simple-template-id ;
17559 // friend class-key nested-name-specifier template(opt)
17560 // simple-template-id ;
17561 //
17562 // Since enum is not a class-key, so declarations like "friend enum E;"
17563 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17564 // invalid, most implementations accept so we issue a pedantic warning.
17565 Diag(Loc: KWLoc, DiagID: diag::ext_enum_friend) << FixItHint::CreateRemoval(
17566 RemoveRange: ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17567 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17568 Diag(Loc: KWLoc, DiagID: diag::note_enum_friend)
17569 << (ScopedEnum + ScopedEnumUsesClassTag);
17570 }
17571
17572 // Figure out the underlying type if this a enum declaration. We need to do
17573 // this early, because it's needed to detect if this is an incompatible
17574 // redeclaration.
17575 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17576 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17577
17578 if (Kind == TagTypeKind::Enum) {
17579 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17580 // No underlying type explicitly specified, or we failed to parse the
17581 // type, default to int.
17582 EnumUnderlying = Context.IntTy.getTypePtr();
17583 } else if (UnderlyingType.get()) {
17584 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17585 // integral type; any cv-qualification is ignored.
17586 // C23 6.7.3.3p5: The underlying type of the enumeration is the
17587 // unqualified, non-atomic version of the type specified by the type
17588 // specifiers in the specifier qualifier list.
17589 TypeSourceInfo *TI = nullptr;
17590 GetTypeFromParser(Ty: UnderlyingType.get(), TInfo: &TI);
17591 EnumUnderlying = TI;
17592
17593 if (CheckEnumUnderlyingType(TI))
17594 // Recover by falling back to int.
17595 EnumUnderlying = Context.IntTy.getTypePtr();
17596
17597 if (DiagnoseUnexpandedParameterPack(Loc: TI->getTypeLoc().getBeginLoc(), T: TI,
17598 UPPC: UPPC_FixedUnderlyingType))
17599 EnumUnderlying = Context.IntTy.getTypePtr();
17600
17601 // If the underlying type is atomic, we need to adjust the type before
17602 // continuing. This only happens in the case we stored a TypeSourceInfo
17603 // into EnumUnderlying because the other cases are error recovery up to
17604 // this point. But because it's not possible to gin up a TypeSourceInfo
17605 // for a non-atomic type from an atomic one, we'll store into the Type
17606 // field instead. FIXME: it would be nice to have an easy way to get a
17607 // derived TypeSourceInfo which strips qualifiers including the weird
17608 // ones like _Atomic where it forms a different type.
17609 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying);
17610 TI && TI->getType()->isAtomicType())
17611 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
17612
17613 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17614 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17615 // of 'int'. However, if this is an unfixed forward declaration, don't set
17616 // the underlying type unless the user enables -fms-compatibility. This
17617 // makes unfixed forward declared enums incomplete and is more conforming.
17618 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17619 EnumUnderlying = Context.IntTy.getTypePtr();
17620 }
17621 }
17622
17623 DeclContext *SearchDC = CurContext;
17624 DeclContext *DC = CurContext;
17625 bool isStdBadAlloc = false;
17626 bool isStdAlignValT = false;
17627
17628 RedeclarationKind Redecl = forRedeclarationInCurContext();
17629 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17630 Redecl = RedeclarationKind::NotForRedeclaration;
17631
17632 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17633 /// implemented asks for structural equivalence checking, the returned decl
17634 /// here is passed back to the parser, allowing the tag body to be parsed.
17635 auto createTagFromNewDecl = [&]() -> TagDecl * {
17636 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17637 // If there is an identifier, use the location of the identifier as the
17638 // location of the decl, otherwise use the location of the struct/union
17639 // keyword.
17640 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17641 TagDecl *New = nullptr;
17642
17643 if (Kind == TagTypeKind::Enum) {
17644 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, PrevDecl: nullptr,
17645 IsScoped: ScopedEnum, IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
17646 // If this is an undefined enum, bail.
17647 if (TUK != TagUseKind::Definition && !Invalid)
17648 return nullptr;
17649 if (EnumUnderlying) {
17650 EnumDecl *ED = cast<EnumDecl>(Val: New);
17651 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
17652 ED->setIntegerTypeSourceInfo(TI);
17653 else
17654 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
17655 QualType EnumTy = ED->getIntegerType();
17656 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
17657 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
17658 : EnumTy);
17659 }
17660 } else { // struct/union
17661 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
17662 PrevDecl: nullptr);
17663 }
17664
17665 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
17666 // Add alignment attributes if necessary; these attributes are checked
17667 // when the ASTContext lays out the structure.
17668 //
17669 // It is important for implementing the correct semantics that this
17670 // happen here (in ActOnTag). The #pragma pack stack is
17671 // maintained as a result of parser callbacks which can occur at
17672 // many points during the parsing of a struct declaration (because
17673 // the #pragma tokens are effectively skipped over during the
17674 // parsing of the struct).
17675 if (TUK == TagUseKind::Definition &&
17676 (!SkipBody || !SkipBody->ShouldSkip)) {
17677 if (LangOpts.HLSL)
17678 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
17679 AddAlignmentAttributesForRecord(RD);
17680 AddMsStructLayoutForRecord(RD);
17681 }
17682 }
17683 New->setLexicalDeclContext(CurContext);
17684 return New;
17685 };
17686
17687 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17688 if (Name && SS.isNotEmpty()) {
17689 // We have a nested-name tag ('struct foo::bar').
17690
17691 // Check for invalid 'foo::'.
17692 if (SS.isInvalid()) {
17693 Name = nullptr;
17694 goto CreateNewDecl;
17695 }
17696
17697 // If this is a friend or a reference to a class in a dependent
17698 // context, don't try to make a decl for it.
17699 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17700 DC = computeDeclContext(SS, EnteringContext: false);
17701 if (!DC) {
17702 IsDependent = true;
17703 return true;
17704 }
17705 } else {
17706 DC = computeDeclContext(SS, EnteringContext: true);
17707 if (!DC) {
17708 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_dependent_nested_name_spec)
17709 << SS.getRange();
17710 return true;
17711 }
17712 }
17713
17714 if (RequireCompleteDeclContext(SS, DC))
17715 return true;
17716
17717 SearchDC = DC;
17718 // Look-up name inside 'foo::'.
17719 LookupQualifiedName(R&: Previous, LookupCtx: DC);
17720
17721 if (Previous.isAmbiguous())
17722 return true;
17723
17724 if (Previous.empty()) {
17725 // Name lookup did not find anything. However, if the
17726 // nested-name-specifier refers to the current instantiation,
17727 // and that current instantiation has any dependent base
17728 // classes, we might find something at instantiation time: treat
17729 // this as a dependent elaborated-type-specifier.
17730 // But this only makes any sense for reference-like lookups.
17731 if (Previous.wasNotFoundInCurrentInstantiation() &&
17732 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
17733 IsDependent = true;
17734 return true;
17735 }
17736
17737 // A tag 'foo::bar' must already exist.
17738 Diag(Loc: NameLoc, DiagID: diag::err_not_tag_in_scope)
17739 << Kind << Name << DC << SS.getRange();
17740 Name = nullptr;
17741 Invalid = true;
17742 goto CreateNewDecl;
17743 }
17744 } else if (Name) {
17745 // C++14 [class.mem]p14:
17746 // If T is the name of a class, then each of the following shall have a
17747 // name different from T:
17748 // -- every member of class T that is itself a type
17749 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
17750 DiagnoseClassNameShadow(DC: SearchDC, NameInfo: DeclarationNameInfo(Name, NameLoc)))
17751 return true;
17752
17753 // If this is a named struct, check to see if there was a previous forward
17754 // declaration or definition.
17755 // FIXME: We're looking into outer scopes here, even when we
17756 // shouldn't be. Doing so can result in ambiguities that we
17757 // shouldn't be diagnosing.
17758 LookupName(R&: Previous, S);
17759
17760 // When declaring or defining a tag, ignore ambiguities introduced
17761 // by types using'ed into this scope.
17762 if (Previous.isAmbiguous() &&
17763 (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) {
17764 LookupResult::Filter F = Previous.makeFilter();
17765 while (F.hasNext()) {
17766 NamedDecl *ND = F.next();
17767 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17768 DC: SearchDC->getRedeclContext()))
17769 F.erase();
17770 }
17771 F.done();
17772 }
17773
17774 // C++11 [namespace.memdef]p3:
17775 // If the name in a friend declaration is neither qualified nor
17776 // a template-id and the declaration is a function or an
17777 // elaborated-type-specifier, the lookup to determine whether
17778 // the entity has been previously declared shall not consider
17779 // any scopes outside the innermost enclosing namespace.
17780 //
17781 // MSVC doesn't implement the above rule for types, so a friend tag
17782 // declaration may be a redeclaration of a type declared in an enclosing
17783 // scope. They do implement this rule for friend functions.
17784 //
17785 // Does it matter that this should be by scope instead of by
17786 // semantic context?
17787 if (!Previous.empty() && TUK == TagUseKind::Friend) {
17788 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17789 LookupResult::Filter F = Previous.makeFilter();
17790 bool FriendSawTagOutsideEnclosingNamespace = false;
17791 while (F.hasNext()) {
17792 NamedDecl *ND = F.next();
17793 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17794 if (DC->isFileContext() &&
17795 !EnclosingNS->Encloses(DC: ND->getDeclContext())) {
17796 if (getLangOpts().MSVCCompat)
17797 FriendSawTagOutsideEnclosingNamespace = true;
17798 else
17799 F.erase();
17800 }
17801 }
17802 F.done();
17803
17804 // Diagnose this MSVC extension in the easy case where lookup would have
17805 // unambiguously found something outside the enclosing namespace.
17806 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17807 NamedDecl *ND = Previous.getFoundDecl();
17808 Diag(Loc: NameLoc, DiagID: diag::ext_friend_tag_redecl_outside_namespace)
17809 << createFriendTagNNSFixIt(SemaRef&: *this, ND, S, NameLoc);
17810 }
17811 }
17812
17813 // Note: there used to be some attempt at recovery here.
17814 if (Previous.isAmbiguous())
17815 return true;
17816
17817 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
17818 // FIXME: This makes sure that we ignore the contexts associated
17819 // with C structs, unions, and enums when looking for a matching
17820 // tag declaration or definition. See the similar lookup tweak
17821 // in Sema::LookupName; is there a better way to deal with this?
17822 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(Val: SearchDC))
17823 SearchDC = SearchDC->getParent();
17824 } else if (getLangOpts().CPlusPlus) {
17825 // Inside ObjCContainer want to keep it as a lexical decl context but go
17826 // past it (most often to TranslationUnit) to find the semantic decl
17827 // context.
17828 while (isa<ObjCContainerDecl>(Val: SearchDC))
17829 SearchDC = SearchDC->getParent();
17830 }
17831 } else if (getLangOpts().CPlusPlus) {
17832 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17833 // TagDecl the same way as we skip it for named TagDecl.
17834 while (isa<ObjCContainerDecl>(Val: SearchDC))
17835 SearchDC = SearchDC->getParent();
17836 }
17837
17838 if (Previous.isSingleResult() &&
17839 Previous.getFoundDecl()->isTemplateParameter()) {
17840 // Maybe we will complain about the shadowed template parameter.
17841 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl: Previous.getFoundDecl());
17842 // Just pretend that we didn't see the previous declaration.
17843 Previous.clear();
17844 }
17845
17846 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17847 DC->Equals(DC: getStdNamespace())) {
17848 if (Name->isStr(Str: "bad_alloc")) {
17849 // This is a declaration of or a reference to "std::bad_alloc".
17850 isStdBadAlloc = true;
17851
17852 // If std::bad_alloc has been implicitly declared (but made invisible to
17853 // name lookup), fill in this implicit declaration as the previous
17854 // declaration, so that the declarations get chained appropriately.
17855 if (Previous.empty() && StdBadAlloc)
17856 Previous.addDecl(D: getStdBadAlloc());
17857 } else if (Name->isStr(Str: "align_val_t")) {
17858 isStdAlignValT = true;
17859 if (Previous.empty() && StdAlignValT)
17860 Previous.addDecl(D: getStdAlignValT());
17861 }
17862 }
17863
17864 // If we didn't find a previous declaration, and this is a reference
17865 // (or friend reference), move to the correct scope. In C++, we
17866 // also need to do a redeclaration lookup there, just in case
17867 // there's a shadow friend decl.
17868 if (Name && Previous.empty() &&
17869 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17870 IsTemplateParamOrArg)) {
17871 if (Invalid) goto CreateNewDecl;
17872 assert(SS.isEmpty());
17873
17874 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
17875 // C++ [basic.scope.pdecl]p5:
17876 // -- for an elaborated-type-specifier of the form
17877 //
17878 // class-key identifier
17879 //
17880 // if the elaborated-type-specifier is used in the
17881 // decl-specifier-seq or parameter-declaration-clause of a
17882 // function defined in namespace scope, the identifier is
17883 // declared as a class-name in the namespace that contains
17884 // the declaration; otherwise, except as a friend
17885 // declaration, the identifier is declared in the smallest
17886 // non-class, non-function-prototype scope that contains the
17887 // declaration.
17888 //
17889 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17890 // C structs and unions.
17891 //
17892 // It is an error in C++ to declare (rather than define) an enum
17893 // type, including via an elaborated type specifier. We'll
17894 // diagnose that later; for now, declare the enum in the same
17895 // scope as we would have picked for any other tag type.
17896 //
17897 // GNU C also supports this behavior as part of its incomplete
17898 // enum types extension, while GNU C++ does not.
17899 //
17900 // Find the context where we'll be declaring the tag.
17901 // FIXME: We would like to maintain the current DeclContext as the
17902 // lexical context,
17903 SearchDC = getTagInjectionContext(DC: SearchDC);
17904
17905 // Find the scope where we'll be declaring the tag.
17906 S = getTagInjectionScope(S, LangOpts: getLangOpts());
17907 } else {
17908 assert(TUK == TagUseKind::Friend);
17909 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: SearchDC);
17910
17911 // C++ [namespace.memdef]p3:
17912 // If a friend declaration in a non-local class first declares a
17913 // class or function, the friend class or function is a member of
17914 // the innermost enclosing namespace.
17915 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17916 : SearchDC->getEnclosingNamespaceContext();
17917 }
17918
17919 // In C++, we need to do a redeclaration lookup to properly
17920 // diagnose some problems.
17921 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17922 // hidden declaration so that we don't get ambiguity errors when using a
17923 // type declared by an elaborated-type-specifier. In C that is not correct
17924 // and we should instead merge compatible types found by lookup.
17925 if (getLangOpts().CPlusPlus) {
17926 // FIXME: This can perform qualified lookups into function contexts,
17927 // which are meaningless.
17928 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17929 LookupQualifiedName(R&: Previous, LookupCtx: SearchDC);
17930 } else {
17931 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17932 LookupName(R&: Previous, S);
17933 }
17934 }
17935
17936 // If we have a known previous declaration to use, then use it.
17937 if (Previous.empty() && SkipBody && SkipBody->Previous)
17938 Previous.addDecl(D: SkipBody->Previous);
17939
17940 if (!Previous.empty()) {
17941 NamedDecl *PrevDecl = Previous.getFoundDecl();
17942 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17943
17944 // It's okay to have a tag decl in the same scope as a typedef
17945 // which hides a tag decl in the same scope. Finding this
17946 // with a redeclaration lookup can only actually happen in C++.
17947 //
17948 // This is also okay for elaborated-type-specifiers, which is
17949 // technically forbidden by the current standard but which is
17950 // okay according to the likely resolution of an open issue;
17951 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17952 if (getLangOpts().CPlusPlus) {
17953 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
17954 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17955 TagDecl *Tag = TT->getDecl();
17956 if (Tag->getDeclName() == Name &&
17957 Tag->getDeclContext()->getRedeclContext()
17958 ->Equals(DC: TD->getDeclContext()->getRedeclContext())) {
17959 PrevDecl = Tag;
17960 Previous.clear();
17961 Previous.addDecl(D: Tag);
17962 Previous.resolveKind();
17963 }
17964 }
17965 }
17966 }
17967
17968 // If this is a redeclaration of a using shadow declaration, it must
17969 // declare a tag in the same context. In MSVC mode, we allow a
17970 // redefinition if either context is within the other.
17971 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: DirectPrevDecl)) {
17972 auto *OldTag = dyn_cast<TagDecl>(Val: PrevDecl);
17973 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
17974 TUK != TagUseKind::Friend &&
17975 isDeclInScope(D: Shadow, Ctx: SearchDC, S, AllowInlineNamespace: isMemberSpecialization) &&
17976 !(OldTag && isAcceptableTagRedeclContext(
17977 S&: *this, OldDC: OldTag->getDeclContext(), NewDC: SearchDC))) {
17978 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
17979 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
17980 DiagID: diag::note_using_decl_target);
17981 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
17982 << 0;
17983 // Recover by ignoring the old declaration.
17984 Previous.clear();
17985 goto CreateNewDecl;
17986 }
17987 }
17988
17989 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(Val: PrevDecl)) {
17990 // If this is a use of a previous tag, or if the tag is already declared
17991 // in the same scope (so that the definition/declaration completes or
17992 // rementions the tag), reuse the decl.
17993 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17994 isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
17995 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
17996 // Make sure that this wasn't declared as an enum and now used as a
17997 // struct or something similar.
17998 if (!isAcceptableTagRedeclaration(Previous: PrevTagDecl, NewTag: Kind,
17999 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
18000 Name)) {
18001 bool SafeToContinue =
18002 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18003 Kind != TagTypeKind::Enum);
18004 if (SafeToContinue)
18005 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
18006 << Name
18007 << FixItHint::CreateReplacement(RemoveRange: SourceRange(KWLoc),
18008 Code: PrevTagDecl->getKindName());
18009 else
18010 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag) << Name;
18011 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_use);
18012
18013 if (SafeToContinue)
18014 Kind = PrevTagDecl->getTagKind();
18015 else {
18016 // Recover by making this an anonymous redefinition.
18017 Name = nullptr;
18018 Previous.clear();
18019 Invalid = true;
18020 }
18021 }
18022
18023 if (Kind == TagTypeKind::Enum &&
18024 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18025 const EnumDecl *PrevEnum = cast<EnumDecl>(Val: PrevTagDecl);
18026 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18027 return PrevTagDecl;
18028
18029 QualType EnumUnderlyingTy;
18030 if (TypeSourceInfo *TI =
18031 dyn_cast_if_present<TypeSourceInfo *>(Val&: EnumUnderlying))
18032 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18033 else if (const Type *T =
18034 dyn_cast_if_present<const Type *>(Val&: EnumUnderlying))
18035 EnumUnderlyingTy = QualType(T, 0);
18036
18037 // All conflicts with previous declarations are recovered by
18038 // returning the previous declaration, unless this is a definition,
18039 // in which case we want the caller to bail out.
18040 if (CheckEnumRedeclaration(EnumLoc: NameLoc.isValid() ? NameLoc : KWLoc,
18041 IsScoped: ScopedEnum, EnumUnderlyingTy,
18042 IsFixed, Prev: PrevEnum))
18043 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18044 }
18045
18046 // C++11 [class.mem]p1:
18047 // A member shall not be declared twice in the member-specification,
18048 // except that a nested class or member class template can be declared
18049 // and then later defined.
18050 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18051 S->isDeclScope(D: PrevDecl)) {
18052 Diag(Loc: NameLoc, DiagID: diag::ext_member_redeclared);
18053 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_declaration);
18054 }
18055
18056 if (!Invalid) {
18057 // If this is a use, just return the declaration we found, unless
18058 // we have attributes.
18059 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18060 if (!Attrs.empty()) {
18061 // FIXME: Diagnose these attributes. For now, we create a new
18062 // declaration to hold them.
18063 } else if (TUK == TagUseKind::Reference &&
18064 (PrevTagDecl->getFriendObjectKind() ==
18065 Decl::FOK_Undeclared ||
18066 PrevDecl->getOwningModule() != getCurrentModule()) &&
18067 SS.isEmpty()) {
18068 // This declaration is a reference to an existing entity, but
18069 // has different visibility from that entity: it either makes
18070 // a friend visible or it makes a type visible in a new module.
18071 // In either case, create a new declaration. We only do this if
18072 // the declaration would have meant the same thing if no prior
18073 // declaration were found, that is, if it was found in the same
18074 // scope where we would have injected a declaration.
18075 if (!getTagInjectionContext(DC: CurContext)->getRedeclContext()
18076 ->Equals(DC: PrevDecl->getDeclContext()->getRedeclContext()))
18077 return PrevTagDecl;
18078 // This is in the injected scope, create a new declaration in
18079 // that scope.
18080 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18081 } else {
18082 return PrevTagDecl;
18083 }
18084 }
18085
18086 // Diagnose attempts to redefine a tag.
18087 if (TUK == TagUseKind::Definition) {
18088 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
18089 // If we're defining a specialization and the previous definition
18090 // is from an implicit instantiation, don't emit an error
18091 // here; we'll catch this in the general case below.
18092 bool IsExplicitSpecializationAfterInstantiation = false;
18093 if (isMemberSpecialization) {
18094 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Def))
18095 IsExplicitSpecializationAfterInstantiation =
18096 RD->getTemplateSpecializationKind() !=
18097 TSK_ExplicitSpecialization;
18098 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: Def))
18099 IsExplicitSpecializationAfterInstantiation =
18100 ED->getTemplateSpecializationKind() !=
18101 TSK_ExplicitSpecialization;
18102 }
18103
18104 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
18105 // not keep more that one definition around (merge them). However,
18106 // ensure the decl passes the structural compatibility check in
18107 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18108 NamedDecl *Hidden = nullptr;
18109 if (SkipBody &&
18110 (!hasVisibleDefinition(D: Def, Suggested: &Hidden) || getLangOpts().C23)) {
18111 // There is a definition of this tag, but it is not visible. We
18112 // explicitly make use of C++'s one definition rule here, and
18113 // assume that this definition is identical to the hidden one
18114 // we already have. Make the existing definition visible and
18115 // use it in place of this one.
18116 if (!getLangOpts().CPlusPlus) {
18117 // Postpone making the old definition visible until after we
18118 // complete parsing the new one and do the structural
18119 // comparison.
18120 SkipBody->CheckSameAsPrevious = true;
18121 SkipBody->New = createTagFromNewDecl();
18122 SkipBody->Previous = Def;
18123
18124 ProcessDeclAttributeList(S, D: SkipBody->New, AttrList: Attrs);
18125 return Def;
18126 } else {
18127 SkipBody->ShouldSkip = true;
18128 SkipBody->Previous = Def;
18129 makeMergedDefinitionVisible(ND: Hidden);
18130 // Carry on and handle it like a normal definition. We'll
18131 // skip starting the definition later.
18132 }
18133 } else if (!IsExplicitSpecializationAfterInstantiation) {
18134 // A redeclaration in function prototype scope in C isn't
18135 // visible elsewhere, so merely issue a warning.
18136 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
18137 Diag(Loc: NameLoc, DiagID: diag::warn_redefinition_in_param_list) << Name;
18138 else
18139 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
18140 notePreviousDefinition(Old: Def,
18141 New: NameLoc.isValid() ? NameLoc : KWLoc);
18142 // If this is a redefinition, recover by making this
18143 // struct be anonymous, which will make any later
18144 // references get the previous definition.
18145 Name = nullptr;
18146 Previous.clear();
18147 Invalid = true;
18148 }
18149 } else {
18150 // If the type is currently being defined, complain
18151 // about a nested redefinition.
18152 auto *TD = Context.getTagDeclType(Decl: PrevTagDecl)->getAsTagDecl();
18153 if (TD->isBeingDefined()) {
18154 Diag(Loc: NameLoc, DiagID: diag::err_nested_redefinition) << Name;
18155 Diag(Loc: PrevTagDecl->getLocation(),
18156 DiagID: diag::note_previous_definition);
18157 Name = nullptr;
18158 Previous.clear();
18159 Invalid = true;
18160 }
18161 }
18162
18163 // Okay, this is definition of a previously declared or referenced
18164 // tag. We're going to create a new Decl for it.
18165 }
18166
18167 // Okay, we're going to make a redeclaration. If this is some kind
18168 // of reference, make sure we build the redeclaration in the same DC
18169 // as the original, and ignore the current access specifier.
18170 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18171 SearchDC = PrevTagDecl->getDeclContext();
18172 AS = AS_none;
18173 }
18174 }
18175 // If we get here we have (another) forward declaration or we
18176 // have a definition. Just create a new decl.
18177
18178 } else {
18179 // If we get here, this is a definition of a new tag type in a nested
18180 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18181 // new decl/type. We set PrevDecl to NULL so that the entities
18182 // have distinct types.
18183 Previous.clear();
18184 }
18185 // If we get here, we're going to create a new Decl. If PrevDecl
18186 // is non-NULL, it's a definition of the tag declared by
18187 // PrevDecl. If it's NULL, we have a new definition.
18188
18189 // Otherwise, PrevDecl is not a tag, but was found with tag
18190 // lookup. This is only actually possible in C++, where a few
18191 // things like templates still live in the tag namespace.
18192 } else {
18193 // Use a better diagnostic if an elaborated-type-specifier
18194 // found the wrong kind of type on the first
18195 // (non-redeclaration) lookup.
18196 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18197 !Previous.isForRedeclaration()) {
18198 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18199 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_non_tag)
18200 << PrevDecl << NTK << Kind;
18201 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_declared_at);
18202 Invalid = true;
18203
18204 // Otherwise, only diagnose if the declaration is in scope.
18205 } else if (!isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18206 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18207 // do nothing
18208
18209 // Diagnose implicit declarations introduced by elaborated types.
18210 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18211 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18212 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_conflict) << NTK;
18213 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18214 Invalid = true;
18215
18216 // Otherwise it's a declaration. Call out a particularly common
18217 // case here.
18218 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18219 unsigned Kind = 0;
18220 if (isa<TypeAliasDecl>(Val: PrevDecl)) Kind = 1;
18221 Diag(Loc: NameLoc, DiagID: diag::err_tag_definition_of_typedef)
18222 << Name << Kind << TND->getUnderlyingType();
18223 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18224 Invalid = true;
18225
18226 // Otherwise, diagnose.
18227 } else {
18228 // The tag name clashes with something else in the target scope,
18229 // issue an error and recover by making this tag be anonymous.
18230 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
18231 notePreviousDefinition(Old: PrevDecl, New: NameLoc);
18232 Name = nullptr;
18233 Invalid = true;
18234 }
18235
18236 // The existing declaration isn't relevant to us; we're in a
18237 // new scope, so clear out the previous declaration.
18238 Previous.clear();
18239 }
18240 }
18241
18242CreateNewDecl:
18243
18244 TagDecl *PrevDecl = nullptr;
18245 if (Previous.isSingleResult())
18246 PrevDecl = cast<TagDecl>(Val: Previous.getFoundDecl());
18247
18248 // If there is an identifier, use the location of the identifier as the
18249 // location of the decl, otherwise use the location of the struct/union
18250 // keyword.
18251 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18252
18253 // Otherwise, create a new declaration. If there is a previous
18254 // declaration of the same entity, the two will be linked via
18255 // PrevDecl.
18256 TagDecl *New;
18257
18258 if (Kind == TagTypeKind::Enum) {
18259 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18260 // enum X { A, B, C } D; D should chain to X.
18261 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18262 PrevDecl: cast_or_null<EnumDecl>(Val: PrevDecl), IsScoped: ScopedEnum,
18263 IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18264
18265 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18266 StdAlignValT = cast<EnumDecl>(Val: New);
18267
18268 // If this is an undefined enum, warn.
18269 if (TUK != TagUseKind::Definition && !Invalid) {
18270 TagDecl *Def;
18271 if (IsFixed && cast<EnumDecl>(Val: New)->isFixed()) {
18272 // C++0x: 7.2p2: opaque-enum-declaration.
18273 // Conflicts are diagnosed above. Do nothing.
18274 }
18275 else if (PrevDecl && (Def = cast<EnumDecl>(Val: PrevDecl)->getDefinition())) {
18276 Diag(Loc, DiagID: diag::ext_forward_ref_enum_def)
18277 << New;
18278 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
18279 } else {
18280 unsigned DiagID = diag::ext_forward_ref_enum;
18281 if (getLangOpts().MSVCCompat)
18282 DiagID = diag::ext_ms_forward_ref_enum;
18283 else if (getLangOpts().CPlusPlus)
18284 DiagID = diag::err_forward_ref_enum;
18285 Diag(Loc, DiagID);
18286 }
18287 }
18288
18289 if (EnumUnderlying) {
18290 EnumDecl *ED = cast<EnumDecl>(Val: New);
18291 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
18292 ED->setIntegerTypeSourceInfo(TI);
18293 else
18294 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
18295 QualType EnumTy = ED->getIntegerType();
18296 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
18297 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
18298 : EnumTy);
18299 assert(ED->isComplete() && "enum with type should be complete");
18300 }
18301 } else {
18302 // struct/union/class
18303
18304 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18305 // struct X { int A; } D; D should chain to X.
18306 if (getLangOpts().CPlusPlus) {
18307 // FIXME: Look for a way to use RecordDecl for simple structs.
18308 New = CXXRecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18309 PrevDecl: cast_or_null<CXXRecordDecl>(Val: PrevDecl));
18310
18311 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18312 StdBadAlloc = cast<CXXRecordDecl>(Val: New);
18313 } else
18314 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18315 PrevDecl: cast_or_null<RecordDecl>(Val: PrevDecl));
18316 }
18317
18318 // Only C23 and later allow defining new types in 'offsetof()'.
18319 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18320 !getLangOpts().CPlusPlus && !getLangOpts().C23)
18321 Diag(Loc: New->getLocation(), DiagID: diag::ext_type_defined_in_offsetof)
18322 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18323
18324 // C++11 [dcl.type]p3:
18325 // A type-specifier-seq shall not define a class or enumeration [...].
18326 if (!Invalid && getLangOpts().CPlusPlus &&
18327 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18328 TUK == TagUseKind::Definition) {
18329 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_type_specifier)
18330 << Context.getTagDeclType(Decl: New);
18331 Invalid = true;
18332 }
18333
18334 if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition &&
18335 DC->getDeclKind() == Decl::Enum) {
18336 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_enum)
18337 << Context.getTagDeclType(Decl: New);
18338 Invalid = true;
18339 }
18340
18341 // Maybe add qualifier info.
18342 if (SS.isNotEmpty()) {
18343 if (SS.isSet()) {
18344 // If this is either a declaration or a definition, check the
18345 // nested-name-specifier against the current context.
18346 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18347 diagnoseQualifiedDeclaration(SS, DC, Name: OrigName, Loc,
18348 /*TemplateId=*/nullptr,
18349 IsMemberSpecialization: isMemberSpecialization))
18350 Invalid = true;
18351
18352 New->setQualifierInfo(SS.getWithLocInContext(Context));
18353 if (TemplateParameterLists.size() > 0) {
18354 New->setTemplateParameterListsInfo(Context, TPLists: TemplateParameterLists);
18355 }
18356 }
18357 else
18358 Invalid = true;
18359 }
18360
18361 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18362 // Add alignment attributes if necessary; these attributes are checked when
18363 // the ASTContext lays out the structure.
18364 //
18365 // It is important for implementing the correct semantics that this
18366 // happen here (in ActOnTag). The #pragma pack stack is
18367 // maintained as a result of parser callbacks which can occur at
18368 // many points during the parsing of a struct declaration (because
18369 // the #pragma tokens are effectively skipped over during the
18370 // parsing of the struct).
18371 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18372 if (LangOpts.HLSL)
18373 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
18374 AddAlignmentAttributesForRecord(RD);
18375 AddMsStructLayoutForRecord(RD);
18376 }
18377 }
18378
18379 if (ModulePrivateLoc.isValid()) {
18380 if (isMemberSpecialization)
18381 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_specialization)
18382 << 2
18383 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
18384 // __module_private__ does not apply to local classes. However, we only
18385 // diagnose this as an error when the declaration specifiers are
18386 // freestanding. Here, we just ignore the __module_private__.
18387 else if (!SearchDC->isFunctionOrMethod())
18388 New->setModulePrivate();
18389 }
18390
18391 // If this is a specialization of a member class (of a class template),
18392 // check the specialization.
18393 if (isMemberSpecialization && CheckMemberSpecialization(Member: New, Previous))
18394 Invalid = true;
18395
18396 // If we're declaring or defining a tag in function prototype scope in C,
18397 // note that this type can only be used within the function and add it to
18398 // the list of decls to inject into the function definition scope. However,
18399 // in C23 and later, while the type is only visible within the function, the
18400 // function can be called with a compatible type defined in the same TU, so
18401 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18402 if ((Name || Kind == TagTypeKind::Enum) &&
18403 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18404 if (getLangOpts().CPlusPlus) {
18405 // C++ [dcl.fct]p6:
18406 // Types shall not be defined in return or parameter types.
18407 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18408 Diag(Loc, DiagID: diag::err_type_defined_in_param_type)
18409 << Name;
18410 Invalid = true;
18411 }
18412 if (TUK == TagUseKind::Declaration)
18413 Invalid = true;
18414 } else if (!PrevDecl) {
18415 // In C23 mode, if the declaration is complete, we do not want to
18416 // diagnose.
18417 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
18418 Diag(Loc, DiagID: diag::warn_decl_in_param_list) << Context.getTagDeclType(Decl: New);
18419 }
18420 }
18421
18422 if (Invalid)
18423 New->setInvalidDecl();
18424
18425 // Set the lexical context. If the tag has a C++ scope specifier, the
18426 // lexical context will be different from the semantic context.
18427 New->setLexicalDeclContext(CurContext);
18428
18429 // Mark this as a friend decl if applicable.
18430 // In Microsoft mode, a friend declaration also acts as a forward
18431 // declaration so we always pass true to setObjectOfFriendDecl to make
18432 // the tag name visible.
18433 if (TUK == TagUseKind::Friend)
18434 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18435
18436 // Set the access specifier.
18437 if (!Invalid && SearchDC->isRecord())
18438 SetMemberAccessSpecifier(MemberDecl: New, PrevMemberDecl: PrevDecl, LexicalAS: AS);
18439
18440 if (PrevDecl)
18441 CheckRedeclarationInModule(New, Old: PrevDecl);
18442
18443 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
18444 New->startDefinition();
18445
18446 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
18447 AddPragmaAttributes(S, D: New);
18448
18449 // If this has an identifier, add it to the scope stack.
18450 if (TUK == TagUseKind::Friend) {
18451 // We might be replacing an existing declaration in the lookup tables;
18452 // if so, borrow its access specifier.
18453 if (PrevDecl)
18454 New->setAccess(PrevDecl->getAccess());
18455
18456 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18457 DC->makeDeclVisibleInContext(D: New);
18458 if (Name) // can be null along some error paths
18459 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18460 PushOnScopeChains(D: New, S: EnclosingScope, /* AddToContext = */ false);
18461 } else if (Name) {
18462 S = getNonFieldDeclScope(S);
18463 PushOnScopeChains(D: New, S, AddToContext: true);
18464 } else {
18465 CurContext->addDecl(D: New);
18466 }
18467
18468 // If this is the C FILE type, notify the AST context.
18469 if (IdentifierInfo *II = New->getIdentifier())
18470 if (!New->isInvalidDecl() &&
18471 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18472 II->isStr(Str: "FILE"))
18473 Context.setFILEDecl(New);
18474
18475 if (PrevDecl)
18476 mergeDeclAttributes(New, Old: PrevDecl);
18477
18478 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: New)) {
18479 inferGslOwnerPointerAttribute(Record: CXXRD);
18480 inferNullableClassAttribute(CRD: CXXRD);
18481 }
18482
18483 // If there's a #pragma GCC visibility in scope, set the visibility of this
18484 // record.
18485 AddPushedVisibilityAttribute(RD: New);
18486
18487 if (isMemberSpecialization && !New->isInvalidDecl())
18488 CompleteMemberSpecialization(Member: New, Previous);
18489
18490 OwnedDecl = true;
18491 // In C++, don't return an invalid declaration. We can't recover well from
18492 // the cases where we make the type anonymous.
18493 if (Invalid && getLangOpts().CPlusPlus) {
18494 if (New->isBeingDefined())
18495 if (auto RD = dyn_cast<RecordDecl>(Val: New))
18496 RD->completeDefinition();
18497 return true;
18498 } else if (SkipBody && SkipBody->ShouldSkip) {
18499 return SkipBody->Previous;
18500 } else {
18501 return New;
18502 }
18503}
18504
18505void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
18506 AdjustDeclIfTemplate(Decl&: TagD);
18507 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18508
18509 // Enter the tag context.
18510 PushDeclContext(S, DC: Tag);
18511
18512 ActOnDocumentableDecl(D: TagD);
18513
18514 // If there's a #pragma GCC visibility in scope, set the visibility of this
18515 // record.
18516 AddPushedVisibilityAttribute(RD: Tag);
18517}
18518
18519bool Sema::ActOnDuplicateDefinition(Scope *S, Decl *Prev,
18520 SkipBodyInfo &SkipBody) {
18521 if (!hasStructuralCompatLayout(D: Prev, Suggested: SkipBody.New))
18522 return false;
18523
18524 // Make the previous decl visible.
18525 makeMergedDefinitionVisible(ND: SkipBody.Previous);
18526 CleanupMergedEnum(S, New: SkipBody.New);
18527 return true;
18528}
18529
18530void Sema::ActOnStartCXXMemberDeclarations(
18531 Scope *S, Decl *TagD, SourceLocation FinalLoc, bool IsFinalSpelledSealed,
18532 bool IsAbstract, SourceLocation TriviallyRelocatable,
18533 SourceLocation Replaceable, SourceLocation LBraceLoc) {
18534 AdjustDeclIfTemplate(Decl&: TagD);
18535 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: TagD);
18536
18537 FieldCollector->StartClass();
18538
18539 if (!Record->getIdentifier())
18540 return;
18541
18542 if (IsAbstract)
18543 Record->markAbstract();
18544
18545 if (FinalLoc.isValid()) {
18546 Record->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: FinalLoc,
18547 S: IsFinalSpelledSealed
18548 ? FinalAttr::Keyword_sealed
18549 : FinalAttr::Keyword_final));
18550 }
18551
18552 if (TriviallyRelocatable.isValid())
18553 Record->addAttr(
18554 A: TriviallyRelocatableAttr::Create(Ctx&: Context, Range: TriviallyRelocatable));
18555
18556 if (Replaceable.isValid())
18557 Record->addAttr(A: ReplaceableAttr::Create(Ctx&: Context, Range: Replaceable));
18558
18559 // C++ [class]p2:
18560 // [...] The class-name is also inserted into the scope of the
18561 // class itself; this is known as the injected-class-name. For
18562 // purposes of access checking, the injected-class-name is treated
18563 // as if it were a public member name.
18564 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18565 C: Context, TK: Record->getTagKind(), DC: CurContext, StartLoc: Record->getBeginLoc(),
18566 IdLoc: Record->getLocation(), Id: Record->getIdentifier(),
18567 /*PrevDecl=*/nullptr,
18568 /*DelayTypeCreation=*/true);
18569 Context.getTypeDeclType(Decl: InjectedClassName, PrevDecl: Record);
18570 InjectedClassName->setImplicit();
18571 InjectedClassName->setAccess(AS_public);
18572 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18573 InjectedClassName->setDescribedClassTemplate(Template);
18574 PushOnScopeChains(D: InjectedClassName, S);
18575 assert(InjectedClassName->isInjectedClassName() &&
18576 "Broken injected-class-name");
18577}
18578
18579void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
18580 SourceRange BraceRange) {
18581 AdjustDeclIfTemplate(Decl&: TagD);
18582 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18583 Tag->setBraceRange(BraceRange);
18584
18585 // Make sure we "complete" the definition even it is invalid.
18586 if (Tag->isBeingDefined()) {
18587 assert(Tag->isInvalidDecl() && "We should already have completed it");
18588 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
18589 RD->completeDefinition();
18590 }
18591
18592 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
18593 FieldCollector->FinishClass();
18594 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18595 auto *Def = RD->getDefinition();
18596 assert(Def && "The record is expected to have a completed definition");
18597 unsigned NumInitMethods = 0;
18598 for (auto *Method : Def->methods()) {
18599 if (!Method->getIdentifier())
18600 continue;
18601 if (Method->getName() == "__init")
18602 NumInitMethods++;
18603 }
18604 if (NumInitMethods > 1 || !Def->hasInitMethod())
18605 Diag(Loc: RD->getLocation(), DiagID: diag::err_sycl_special_type_num_init_method);
18606 }
18607
18608 // If we're defining a dynamic class in a module interface unit, we always
18609 // need to produce the vtable for it, even if the vtable is not used in the
18610 // current TU.
18611 //
18612 // The case where the current class is not dynamic is handled in
18613 // MarkVTableUsed.
18614 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18615 MarkVTableUsed(Loc: RD->getLocation(), Class: RD, /*DefinitionRequired=*/true);
18616 }
18617
18618 // Exit this scope of this tag's definition.
18619 PopDeclContext();
18620
18621 if (getCurLexicalContext()->isObjCContainer() &&
18622 Tag->getDeclContext()->isFileContext())
18623 Tag->setTopLevelDeclInObjCContainer();
18624
18625 // Notify the consumer that we've defined a tag.
18626 if (!Tag->isInvalidDecl())
18627 Consumer.HandleTagDeclDefinition(D: Tag);
18628
18629 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18630 // from XLs and instead matches the XL #pragma pack(1) behavior.
18631 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18632 AlignPackStack.hasValue()) {
18633 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18634 // Only diagnose #pragma align(packed).
18635 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18636 return;
18637 const RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag);
18638 if (!RD)
18639 return;
18640 // Only warn if there is at least 1 bitfield member.
18641 if (llvm::any_of(Range: RD->fields(),
18642 P: [](const FieldDecl *FD) { return FD->isBitField(); }))
18643 Diag(Loc: BraceRange.getBegin(), DiagID: diag::warn_pragma_align_not_xl_compatible);
18644 }
18645}
18646
18647void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
18648 AdjustDeclIfTemplate(Decl&: TagD);
18649 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18650 Tag->setInvalidDecl();
18651
18652 // Make sure we "complete" the definition even it is invalid.
18653 if (Tag->isBeingDefined()) {
18654 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
18655 RD->completeDefinition();
18656 }
18657
18658 // We're undoing ActOnTagStartDefinition here, not
18659 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18660 // the FieldCollector.
18661
18662 PopDeclContext();
18663}
18664
18665// Note that FieldName may be null for anonymous bitfields.
18666ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
18667 const IdentifierInfo *FieldName,
18668 QualType FieldTy, bool IsMsStruct,
18669 Expr *BitWidth) {
18670 assert(BitWidth);
18671 if (BitWidth->containsErrors())
18672 return ExprError();
18673
18674 // C99 6.7.2.1p4 - verify the field type.
18675 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18676 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18677 // Handle incomplete and sizeless types with a specific error.
18678 if (RequireCompleteSizedType(Loc: FieldLoc, T: FieldTy,
18679 DiagID: diag::err_field_incomplete_or_sizeless))
18680 return ExprError();
18681 if (FieldName)
18682 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_bitfield)
18683 << FieldName << FieldTy << BitWidth->getSourceRange();
18684 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_anon_bitfield)
18685 << FieldTy << BitWidth->getSourceRange();
18686 } else if (DiagnoseUnexpandedParameterPack(E: BitWidth, UPPC: UPPC_BitFieldWidth))
18687 return ExprError();
18688
18689 // If the bit-width is type- or value-dependent, don't try to check
18690 // it now.
18691 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18692 return BitWidth;
18693
18694 llvm::APSInt Value;
18695 ExprResult ICE =
18696 VerifyIntegerConstantExpression(E: BitWidth, Result: &Value, CanFold: AllowFoldKind::Allow);
18697 if (ICE.isInvalid())
18698 return ICE;
18699 BitWidth = ICE.get();
18700
18701 // Zero-width bitfield is ok for anonymous field.
18702 if (Value == 0 && FieldName)
18703 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_zero_width)
18704 << FieldName << BitWidth->getSourceRange();
18705
18706 if (Value.isSigned() && Value.isNegative()) {
18707 if (FieldName)
18708 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_negative_width)
18709 << FieldName << toString(I: Value, Radix: 10);
18710 return Diag(Loc: FieldLoc, DiagID: diag::err_anon_bitfield_has_negative_width)
18711 << toString(I: Value, Radix: 10);
18712 }
18713
18714 // The size of the bit-field must not exceed our maximum permitted object
18715 // size.
18716 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18717 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_too_wide)
18718 << !FieldName << FieldName << toString(I: Value, Radix: 10);
18719 }
18720
18721 if (!FieldTy->isDependentType()) {
18722 uint64_t TypeStorageSize = Context.getTypeSize(T: FieldTy);
18723 uint64_t TypeWidth = Context.getIntWidth(T: FieldTy);
18724 bool BitfieldIsOverwide = Value.ugt(RHS: TypeWidth);
18725
18726 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18727 // ABI.
18728 bool CStdConstraintViolation =
18729 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18730 bool MSBitfieldViolation =
18731 Value.ugt(RHS: TypeStorageSize) &&
18732 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18733 if (CStdConstraintViolation || MSBitfieldViolation) {
18734 unsigned DiagWidth =
18735 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18736 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_width_exceeds_type_width)
18737 << (bool)FieldName << FieldName << toString(I: Value, Radix: 10)
18738 << !CStdConstraintViolation << DiagWidth;
18739 }
18740
18741 // Warn on types where the user might conceivably expect to get all
18742 // specified bits as value bits: that's all integral types other than
18743 // 'bool'.
18744 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18745 Diag(Loc: FieldLoc, DiagID: diag::warn_bitfield_width_exceeds_type_width)
18746 << FieldName << toString(I: Value, Radix: 10)
18747 << (unsigned)TypeWidth;
18748 }
18749 }
18750
18751 if (isa<ConstantExpr>(Val: BitWidth))
18752 return BitWidth;
18753 return ConstantExpr::Create(Context: getASTContext(), E: BitWidth, Result: APValue{Value});
18754}
18755
18756Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
18757 Declarator &D, Expr *BitfieldWidth) {
18758 FieldDecl *Res = HandleField(S, TagD: cast_if_present<RecordDecl>(Val: TagD), DeclStart,
18759 D, BitfieldWidth,
18760 /*InitStyle=*/ICIS_NoInit, AS: AS_public);
18761 return Res;
18762}
18763
18764FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
18765 SourceLocation DeclStart,
18766 Declarator &D, Expr *BitWidth,
18767 InClassInitStyle InitStyle,
18768 AccessSpecifier AS) {
18769 if (D.isDecompositionDeclarator()) {
18770 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18771 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
18772 << Decomp.getSourceRange();
18773 return nullptr;
18774 }
18775
18776 const IdentifierInfo *II = D.getIdentifier();
18777 SourceLocation Loc = DeclStart;
18778 if (II) Loc = D.getIdentifierLoc();
18779
18780 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18781 QualType T = TInfo->getType();
18782 if (getLangOpts().CPlusPlus) {
18783 CheckExtraCXXDefaultArguments(D);
18784
18785 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
18786 UPPC: UPPC_DataMemberType)) {
18787 D.setInvalidType();
18788 T = Context.IntTy;
18789 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18790 }
18791 }
18792
18793 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
18794
18795 if (D.getDeclSpec().isInlineSpecified())
18796 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
18797 << getLangOpts().CPlusPlus17;
18798 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18799 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
18800 DiagID: diag::err_invalid_thread)
18801 << DeclSpec::getSpecifierName(S: TSCS);
18802
18803 // Check to see if this name was declared as a member previously
18804 NamedDecl *PrevDecl = nullptr;
18805 LookupResult Previous(*this, II, Loc, LookupMemberName,
18806 RedeclarationKind::ForVisibleRedeclaration);
18807 LookupName(R&: Previous, S);
18808 switch (Previous.getResultKind()) {
18809 case LookupResultKind::Found:
18810 case LookupResultKind::FoundUnresolvedValue:
18811 PrevDecl = Previous.getAsSingle<NamedDecl>();
18812 break;
18813
18814 case LookupResultKind::FoundOverloaded:
18815 PrevDecl = Previous.getRepresentativeDecl();
18816 break;
18817
18818 case LookupResultKind::NotFound:
18819 case LookupResultKind::NotFoundInCurrentInstantiation:
18820 case LookupResultKind::Ambiguous:
18821 break;
18822 }
18823 Previous.suppressDiagnostics();
18824
18825 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18826 // Maybe we will complain about the shadowed template parameter.
18827 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
18828 // Just pretend that we didn't see the previous declaration.
18829 PrevDecl = nullptr;
18830 }
18831
18832 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
18833 PrevDecl = nullptr;
18834
18835 bool Mutable
18836 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18837 SourceLocation TSSL = D.getBeginLoc();
18838 FieldDecl *NewFD
18839 = CheckFieldDecl(Name: II, T, TInfo, Record, Loc, Mutable, BitfieldWidth: BitWidth, InitStyle,
18840 TSSL, AS, PrevDecl, D: &D);
18841
18842 if (NewFD->isInvalidDecl())
18843 Record->setInvalidDecl();
18844
18845 if (D.getDeclSpec().isModulePrivateSpecified())
18846 NewFD->setModulePrivate();
18847
18848 if (NewFD->isInvalidDecl() && PrevDecl) {
18849 // Don't introduce NewFD into scope; there's already something
18850 // with the same name in the same scope.
18851 } else if (II) {
18852 PushOnScopeChains(D: NewFD, S);
18853 } else
18854 Record->addDecl(D: NewFD);
18855
18856 return NewFD;
18857}
18858
18859FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
18860 TypeSourceInfo *TInfo,
18861 RecordDecl *Record, SourceLocation Loc,
18862 bool Mutable, Expr *BitWidth,
18863 InClassInitStyle InitStyle,
18864 SourceLocation TSSL,
18865 AccessSpecifier AS, NamedDecl *PrevDecl,
18866 Declarator *D) {
18867 const IdentifierInfo *II = Name.getAsIdentifierInfo();
18868 bool InvalidDecl = false;
18869 if (D) InvalidDecl = D->isInvalidType();
18870
18871 // If we receive a broken type, recover by assuming 'int' and
18872 // marking this declaration as invalid.
18873 if (T.isNull() || T->containsErrors()) {
18874 InvalidDecl = true;
18875 T = Context.IntTy;
18876 }
18877
18878 QualType EltTy = Context.getBaseElementType(QT: T);
18879 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18880 bool isIncomplete =
18881 LangOpts.HLSL // HLSL allows sizeless builtin types
18882 ? RequireCompleteType(Loc, T: EltTy, DiagID: diag::err_incomplete_type)
18883 : RequireCompleteSizedType(Loc, T: EltTy,
18884 DiagID: diag::err_field_incomplete_or_sizeless);
18885 if (isIncomplete) {
18886 // Fields of incomplete type force their record to be invalid.
18887 Record->setInvalidDecl();
18888 InvalidDecl = true;
18889 } else {
18890 NamedDecl *Def;
18891 EltTy->isIncompleteType(Def: &Def);
18892 if (Def && Def->isInvalidDecl()) {
18893 Record->setInvalidDecl();
18894 InvalidDecl = true;
18895 }
18896 }
18897 }
18898
18899 // TR 18037 does not allow fields to be declared with address space
18900 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18901 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
18902 Diag(Loc, DiagID: diag::err_field_with_address_space);
18903 Record->setInvalidDecl();
18904 InvalidDecl = true;
18905 }
18906
18907 if (LangOpts.OpenCL) {
18908 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18909 // used as structure or union field: image, sampler, event or block types.
18910 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18911 T->isBlockPointerType()) {
18912 Diag(Loc, DiagID: diag::err_opencl_type_struct_or_union_field) << T;
18913 Record->setInvalidDecl();
18914 InvalidDecl = true;
18915 }
18916 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18917 // is enabled.
18918 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18919 Ext: "__cl_clang_bitfields", LO: LangOpts)) {
18920 Diag(Loc, DiagID: diag::err_opencl_bitfields);
18921 InvalidDecl = true;
18922 }
18923 }
18924
18925 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18926 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18927 T.hasQualifiers()) {
18928 InvalidDecl = true;
18929 Diag(Loc, DiagID: diag::err_anon_bitfield_qualifiers);
18930 }
18931
18932 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18933 // than a variably modified type.
18934 if (!InvalidDecl && T->isVariablyModifiedType()) {
18935 if (!tryToFixVariablyModifiedVarType(
18936 TInfo, T, Loc, FailedFoldDiagID: diag::err_typecheck_field_variable_size))
18937 InvalidDecl = true;
18938 }
18939
18940 // Fields can not have abstract class types
18941 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18942 DiagID: diag::err_abstract_type_in_decl,
18943 Args: AbstractFieldType))
18944 InvalidDecl = true;
18945
18946 if (InvalidDecl)
18947 BitWidth = nullptr;
18948 // If this is declared as a bit-field, check the bit-field.
18949 if (BitWidth) {
18950 BitWidth =
18951 VerifyBitField(FieldLoc: Loc, FieldName: II, FieldTy: T, IsMsStruct: Record->isMsStruct(C: Context), BitWidth).get();
18952 if (!BitWidth) {
18953 InvalidDecl = true;
18954 BitWidth = nullptr;
18955 }
18956 }
18957
18958 // Check that 'mutable' is consistent with the type of the declaration.
18959 if (!InvalidDecl && Mutable) {
18960 unsigned DiagID = 0;
18961 if (T->isReferenceType())
18962 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18963 : diag::err_mutable_reference;
18964 else if (T.isConstQualified())
18965 DiagID = diag::err_mutable_const;
18966
18967 if (DiagID) {
18968 SourceLocation ErrLoc = Loc;
18969 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18970 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18971 Diag(Loc: ErrLoc, DiagID);
18972 if (DiagID != diag::ext_mutable_reference) {
18973 Mutable = false;
18974 InvalidDecl = true;
18975 }
18976 }
18977 }
18978
18979 // C++11 [class.union]p8 (DR1460):
18980 // At most one variant member of a union may have a
18981 // brace-or-equal-initializer.
18982 if (InitStyle != ICIS_NoInit)
18983 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Record), DefaultInitLoc: Loc);
18984
18985 FieldDecl *NewFD = FieldDecl::Create(C: Context, DC: Record, StartLoc: TSSL, IdLoc: Loc, Id: II, T, TInfo,
18986 BW: BitWidth, Mutable, InitStyle);
18987 if (InvalidDecl)
18988 NewFD->setInvalidDecl();
18989
18990 if (!InvalidDecl)
18991 warnOnCTypeHiddenInCPlusPlus(D: NewFD);
18992
18993 if (PrevDecl && !isa<TagDecl>(Val: PrevDecl) &&
18994 !PrevDecl->isPlaceholderVar(LangOpts: getLangOpts())) {
18995 Diag(Loc, DiagID: diag::err_duplicate_member) << II;
18996 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
18997 NewFD->setInvalidDecl();
18998 }
18999
19000 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19001 if (Record->isUnion()) {
19002 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
19003 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(Val: RT->getDecl());
19004 if (RDecl->getDefinition()) {
19005 // C++ [class.union]p1: An object of a class with a non-trivial
19006 // constructor, a non-trivial copy constructor, a non-trivial
19007 // destructor, or a non-trivial copy assignment operator
19008 // cannot be a member of a union, nor can an array of such
19009 // objects.
19010 if (CheckNontrivialField(FD: NewFD))
19011 NewFD->setInvalidDecl();
19012 }
19013 }
19014
19015 // C++ [class.union]p1: If a union contains a member of reference type,
19016 // the program is ill-formed, except when compiling with MSVC extensions
19017 // enabled.
19018 if (EltTy->isReferenceType()) {
19019 const bool HaveMSExt =
19020 getLangOpts().MicrosoftExt &&
19021 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
19022
19023 Diag(Loc: NewFD->getLocation(),
19024 DiagID: HaveMSExt ? diag::ext_union_member_of_reference_type
19025 : diag::err_union_member_of_reference_type)
19026 << NewFD->getDeclName() << EltTy;
19027 if (!HaveMSExt)
19028 NewFD->setInvalidDecl();
19029 }
19030 }
19031 }
19032
19033 // FIXME: We need to pass in the attributes given an AST
19034 // representation, not a parser representation.
19035 if (D) {
19036 // FIXME: The current scope is almost... but not entirely... correct here.
19037 ProcessDeclAttributes(S: getCurScope(), D: NewFD, PD: *D);
19038
19039 if (NewFD->hasAttrs())
19040 CheckAlignasUnderalignment(D: NewFD);
19041 }
19042
19043 // In auto-retain/release, infer strong retension for fields of
19044 // retainable type.
19045 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewFD))
19046 NewFD->setInvalidDecl();
19047
19048 if (T.isObjCGCWeak())
19049 Diag(Loc, DiagID: diag::warn_attribute_weak_on_field);
19050
19051 // PPC MMA non-pointer types are not allowed as field types.
19052 if (Context.getTargetInfo().getTriple().isPPC64() &&
19053 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewFD->getLocation()))
19054 NewFD->setInvalidDecl();
19055
19056 NewFD->setAccess(AS);
19057 return NewFD;
19058}
19059
19060bool Sema::CheckNontrivialField(FieldDecl *FD) {
19061 assert(FD);
19062 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19063
19064 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19065 return false;
19066
19067 QualType EltTy = Context.getBaseElementType(QT: FD->getType());
19068 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
19069 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(Val: RT->getDecl());
19070 if (RDecl->getDefinition()) {
19071 // We check for copy constructors before constructors
19072 // because otherwise we'll never get complaints about
19073 // copy constructors.
19074
19075 CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;
19076 // We're required to check for any non-trivial constructors. Since the
19077 // implicit default constructor is suppressed if there are any
19078 // user-declared constructors, we just need to check that there is a
19079 // trivial default constructor and a trivial copy constructor. (We don't
19080 // worry about move constructors here, since this is a C++98 check.)
19081 if (RDecl->hasNonTrivialCopyConstructor())
19082 member = CXXSpecialMemberKind::CopyConstructor;
19083 else if (!RDecl->hasTrivialDefaultConstructor())
19084 member = CXXSpecialMemberKind::DefaultConstructor;
19085 else if (RDecl->hasNonTrivialCopyAssignment())
19086 member = CXXSpecialMemberKind::CopyAssignment;
19087 else if (RDecl->hasNonTrivialDestructor())
19088 member = CXXSpecialMemberKind::Destructor;
19089
19090 if (member != CXXSpecialMemberKind::Invalid) {
19091 if (!getLangOpts().CPlusPlus11 &&
19092 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
19093 // Objective-C++ ARC: it is an error to have a non-trivial field of
19094 // a union. However, system headers in Objective-C programs
19095 // occasionally have Objective-C lifetime objects within unions,
19096 // and rather than cause the program to fail, we make those
19097 // members unavailable.
19098 SourceLocation Loc = FD->getLocation();
19099 if (getSourceManager().isInSystemHeader(Loc)) {
19100 if (!FD->hasAttr<UnavailableAttr>())
19101 FD->addAttr(A: UnavailableAttr::CreateImplicit(Ctx&: Context, Message: "",
19102 ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership, Range: Loc));
19103 return false;
19104 }
19105 }
19106
19107 Diag(
19108 Loc: FD->getLocation(),
19109 DiagID: getLangOpts().CPlusPlus11
19110 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19111 : diag::err_illegal_union_or_anon_struct_member)
19112 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19113 DiagnoseNontrivial(Record: RDecl, CSM: member);
19114 return !getLangOpts().CPlusPlus11;
19115 }
19116 }
19117 }
19118
19119 return false;
19120}
19121
19122void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
19123 SmallVectorImpl<Decl *> &AllIvarDecls) {
19124 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19125 return;
19126
19127 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19128 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Val: ivarDecl);
19129
19130 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19131 return;
19132 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: CurContext);
19133 if (!ID) {
19134 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(Val: CurContext)) {
19135 if (!CD->IsClassExtension())
19136 return;
19137 }
19138 // No need to add this to end of @implementation.
19139 else
19140 return;
19141 }
19142 // All conditions are met. Add a new bitfield to the tail end of ivars.
19143 llvm::APInt Zero(Context.getTypeSize(T: Context.IntTy), 0);
19144 Expr * BW = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: DeclLoc);
19145 Expr *BitWidth =
19146 ConstantExpr::Create(Context, E: BW, Result: APValue(llvm::APSInt(Zero)));
19147
19148 Ivar = ObjCIvarDecl::Create(
19149 C&: Context, DC: cast<ObjCContainerDecl>(Val: CurContext), StartLoc: DeclLoc, IdLoc: DeclLoc, Id: nullptr,
19150 T: Context.CharTy, TInfo: Context.getTrivialTypeSourceInfo(T: Context.CharTy, Loc: DeclLoc),
19151 ac: ObjCIvarDecl::Private, BW: BitWidth, synthesized: true);
19152 AllIvarDecls.push_back(Elt: Ivar);
19153}
19154
19155/// [class.dtor]p4:
19156/// At the end of the definition of a class, overload resolution is
19157/// performed among the prospective destructors declared in that class with
19158/// an empty argument list to select the destructor for the class, also
19159/// known as the selected destructor.
19160///
19161/// We do the overload resolution here, then mark the selected constructor in the AST.
19162/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19163static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
19164 if (!Record->hasUserDeclaredDestructor()) {
19165 return;
19166 }
19167
19168 SourceLocation Loc = Record->getLocation();
19169 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
19170
19171 for (auto *Decl : Record->decls()) {
19172 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: Decl)) {
19173 if (DD->isInvalidDecl())
19174 continue;
19175 S.AddOverloadCandidate(Function: DD, FoundDecl: DeclAccessPair::make(D: DD, AS: DD->getAccess()), Args: {},
19176 CandidateSet&: OCS);
19177 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19178 }
19179 }
19180
19181 if (OCS.empty()) {
19182 return;
19183 }
19184 OverloadCandidateSet::iterator Best;
19185 unsigned Msg = 0;
19186 OverloadCandidateDisplayKind DisplayKind;
19187
19188 switch (OCS.BestViableFunction(S, Loc, Best)) {
19189 case OR_Success:
19190 case OR_Deleted:
19191 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: Best->Function));
19192 break;
19193
19194 case OR_Ambiguous:
19195 Msg = diag::err_ambiguous_destructor;
19196 DisplayKind = OCD_AmbiguousCandidates;
19197 break;
19198
19199 case OR_No_Viable_Function:
19200 Msg = diag::err_no_viable_destructor;
19201 DisplayKind = OCD_AllCandidates;
19202 break;
19203 }
19204
19205 if (Msg) {
19206 // OpenCL have got their own thing going with destructors. It's slightly broken,
19207 // but we allow it.
19208 if (!S.LangOpts.OpenCL) {
19209 PartialDiagnostic Diag = S.PDiag(DiagID: Msg) << Record;
19210 OCS.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, OCD: DisplayKind, Args: {});
19211 Record->setInvalidDecl();
19212 }
19213 // It's a bit hacky: At this point we've raised an error but we want the
19214 // rest of the compiler to continue somehow working. However almost
19215 // everything we'll try to do with the class will depend on there being a
19216 // destructor. So let's pretend the first one is selected and hope for the
19217 // best.
19218 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: OCS.begin()->Function));
19219 }
19220}
19221
19222/// [class.mem.special]p5
19223/// Two special member functions are of the same kind if:
19224/// - they are both default constructors,
19225/// - they are both copy or move constructors with the same first parameter
19226/// type, or
19227/// - they are both copy or move assignment operators with the same first
19228/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19229static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
19230 CXXMethodDecl *M1,
19231 CXXMethodDecl *M2,
19232 CXXSpecialMemberKind CSM) {
19233 // We don't want to compare templates to non-templates: See
19234 // https://github.com/llvm/llvm-project/issues/59206
19235 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
19236 return bool(M1->getDescribedFunctionTemplate()) ==
19237 bool(M2->getDescribedFunctionTemplate());
19238 // FIXME: better resolve CWG
19239 // https://cplusplus.github.io/CWG/issues/2787.html
19240 if (!Context.hasSameType(T1: M1->getNonObjectParameter(I: 0)->getType(),
19241 T2: M2->getNonObjectParameter(I: 0)->getType()))
19242 return false;
19243 if (!Context.hasSameType(T1: M1->getFunctionObjectParameterReferenceType(),
19244 T2: M2->getFunctionObjectParameterReferenceType()))
19245 return false;
19246
19247 return true;
19248}
19249
19250/// [class.mem.special]p6:
19251/// An eligible special member function is a special member function for which:
19252/// - the function is not deleted,
19253/// - the associated constraints, if any, are satisfied, and
19254/// - no special member function of the same kind whose associated constraints
19255/// [CWG2595], if any, are satisfied is more constrained.
19256static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
19257 ArrayRef<CXXMethodDecl *> Methods,
19258 CXXSpecialMemberKind CSM) {
19259 SmallVector<bool, 4> SatisfactionStatus;
19260
19261 for (CXXMethodDecl *Method : Methods) {
19262 if (!Method->getTrailingRequiresClause())
19263 SatisfactionStatus.push_back(Elt: true);
19264 else {
19265 ConstraintSatisfaction Satisfaction;
19266 if (S.CheckFunctionConstraints(FD: Method, Satisfaction))
19267 SatisfactionStatus.push_back(Elt: false);
19268 else
19269 SatisfactionStatus.push_back(Elt: Satisfaction.IsSatisfied);
19270 }
19271 }
19272
19273 for (size_t i = 0; i < Methods.size(); i++) {
19274 if (!SatisfactionStatus[i])
19275 continue;
19276 CXXMethodDecl *Method = Methods[i];
19277 CXXMethodDecl *OrigMethod = Method;
19278 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19279 OrigMethod = cast<CXXMethodDecl>(Val: MF);
19280
19281 AssociatedConstraint Orig = OrigMethod->getTrailingRequiresClause();
19282 bool AnotherMethodIsMoreConstrained = false;
19283 for (size_t j = 0; j < Methods.size(); j++) {
19284 if (i == j || !SatisfactionStatus[j])
19285 continue;
19286 CXXMethodDecl *OtherMethod = Methods[j];
19287 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19288 OtherMethod = cast<CXXMethodDecl>(Val: MF);
19289
19290 if (!AreSpecialMemberFunctionsSameKind(Context&: S.Context, M1: OrigMethod, M2: OtherMethod,
19291 CSM))
19292 continue;
19293
19294 AssociatedConstraint Other = OtherMethod->getTrailingRequiresClause();
19295 if (!Other)
19296 continue;
19297 if (!Orig) {
19298 AnotherMethodIsMoreConstrained = true;
19299 break;
19300 }
19301 if (S.IsAtLeastAsConstrained(D1: OtherMethod, AC1: {Other}, D2: OrigMethod, AC2: {Orig},
19302 Result&: AnotherMethodIsMoreConstrained)) {
19303 // There was an error with the constraints comparison. Exit the loop
19304 // and don't consider this function eligible.
19305 AnotherMethodIsMoreConstrained = true;
19306 }
19307 if (AnotherMethodIsMoreConstrained)
19308 break;
19309 }
19310 // FIXME: Do not consider deleted methods as eligible after implementing
19311 // DR1734 and DR1496.
19312 if (!AnotherMethodIsMoreConstrained) {
19313 Method->setIneligibleOrNotSelected(false);
19314 Record->addedEligibleSpecialMemberFunction(MD: Method,
19315 SMKind: 1 << llvm::to_underlying(E: CSM));
19316 }
19317 }
19318}
19319
19320static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
19321 CXXRecordDecl *Record) {
19322 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19323 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19324 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19325 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19326 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19327
19328 for (auto *Decl : Record->decls()) {
19329 auto *MD = dyn_cast<CXXMethodDecl>(Val: Decl);
19330 if (!MD) {
19331 auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Decl);
19332 if (FTD)
19333 MD = dyn_cast<CXXMethodDecl>(Val: FTD->getTemplatedDecl());
19334 }
19335 if (!MD)
19336 continue;
19337 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD)) {
19338 if (CD->isInvalidDecl())
19339 continue;
19340 if (CD->isDefaultConstructor())
19341 DefaultConstructors.push_back(Elt: MD);
19342 else if (CD->isCopyConstructor())
19343 CopyConstructors.push_back(Elt: MD);
19344 else if (CD->isMoveConstructor())
19345 MoveConstructors.push_back(Elt: MD);
19346 } else if (MD->isCopyAssignmentOperator()) {
19347 CopyAssignmentOperators.push_back(Elt: MD);
19348 } else if (MD->isMoveAssignmentOperator()) {
19349 MoveAssignmentOperators.push_back(Elt: MD);
19350 }
19351 }
19352
19353 SetEligibleMethods(S, Record, Methods: DefaultConstructors,
19354 CSM: CXXSpecialMemberKind::DefaultConstructor);
19355 SetEligibleMethods(S, Record, Methods: CopyConstructors,
19356 CSM: CXXSpecialMemberKind::CopyConstructor);
19357 SetEligibleMethods(S, Record, Methods: MoveConstructors,
19358 CSM: CXXSpecialMemberKind::MoveConstructor);
19359 SetEligibleMethods(S, Record, Methods: CopyAssignmentOperators,
19360 CSM: CXXSpecialMemberKind::CopyAssignment);
19361 SetEligibleMethods(S, Record, Methods: MoveAssignmentOperators,
19362 CSM: CXXSpecialMemberKind::MoveAssignment);
19363}
19364
19365bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19366 // Check to see if a FieldDecl is a pointer to a function.
19367 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19368 const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
19369 if (!FD) {
19370 // Check whether this is a forward declaration that was inserted by
19371 // Clang. This happens when a non-forward declared / defined type is
19372 // used, e.g.:
19373 //
19374 // struct foo {
19375 // struct bar *(*f)();
19376 // struct bar *(*g)();
19377 // };
19378 //
19379 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19380 // incomplete definition.
19381 if (const auto *TD = dyn_cast<TagDecl>(Val: D))
19382 return !TD->isCompleteDefinition();
19383 return false;
19384 }
19385 QualType FieldType = FD->getType().getDesugaredType(Context);
19386 if (isa<PointerType>(Val: FieldType)) {
19387 QualType PointeeType = cast<PointerType>(Val&: FieldType)->getPointeeType();
19388 return PointeeType.getDesugaredType(Context)->isFunctionType();
19389 }
19390 // If a member is a struct entirely of function pointers, that counts too.
19391 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
19392 const RecordDecl *Record = RT->getDecl();
19393 if (Record->isStruct() && EntirelyFunctionPointers(Record))
19394 return true;
19395 }
19396 return false;
19397 };
19398
19399 return llvm::all_of(Range: Record->decls(), P: IsFunctionPointerOrForwardDecl);
19400}
19401
19402void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19403 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19404 SourceLocation RBrac,
19405 const ParsedAttributesView &Attrs) {
19406 assert(EnclosingDecl && "missing record or interface decl");
19407
19408 // If this is an Objective-C @implementation or category and we have
19409 // new fields here we should reset the layout of the interface since
19410 // it will now change.
19411 if (!Fields.empty() && isa<ObjCContainerDecl>(Val: EnclosingDecl)) {
19412 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(Val: EnclosingDecl);
19413 switch (DC->getKind()) {
19414 default: break;
19415 case Decl::ObjCCategory:
19416 Context.ResetObjCLayout(D: cast<ObjCCategoryDecl>(Val: DC)->getClassInterface());
19417 break;
19418 case Decl::ObjCImplementation:
19419 Context.
19420 ResetObjCLayout(D: cast<ObjCImplementationDecl>(Val: DC)->getClassInterface());
19421 break;
19422 }
19423 }
19424
19425 RecordDecl *Record = dyn_cast<RecordDecl>(Val: EnclosingDecl);
19426 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Val: EnclosingDecl);
19427
19428 // Start counting up the number of named members; make sure to include
19429 // members of anonymous structs and unions in the total.
19430 unsigned NumNamedMembers = 0;
19431 if (Record) {
19432 for (const auto *I : Record->decls()) {
19433 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
19434 if (IFD->getDeclName())
19435 ++NumNamedMembers;
19436 }
19437 }
19438
19439 // Verify that all the fields are okay.
19440 SmallVector<FieldDecl*, 32> RecFields;
19441 const FieldDecl *PreviousField = nullptr;
19442 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19443 i != end; PreviousField = cast<FieldDecl>(Val: *i), ++i) {
19444 FieldDecl *FD = cast<FieldDecl>(Val: *i);
19445
19446 // Get the type for the field.
19447 const Type *FDTy = FD->getType().getTypePtr();
19448
19449 if (!FD->isAnonymousStructOrUnion()) {
19450 // Remember all fields written by the user.
19451 RecFields.push_back(Elt: FD);
19452 }
19453
19454 // If the field is already invalid for some reason, don't emit more
19455 // diagnostics about it.
19456 if (FD->isInvalidDecl()) {
19457 EnclosingDecl->setInvalidDecl();
19458 continue;
19459 }
19460
19461 // C99 6.7.2.1p2:
19462 // A structure or union shall not contain a member with
19463 // incomplete or function type (hence, a structure shall not
19464 // contain an instance of itself, but may contain a pointer to
19465 // an instance of itself), except that the last member of a
19466 // structure with more than one named member may have incomplete
19467 // array type; such a structure (and any union containing,
19468 // possibly recursively, a member that is such a structure)
19469 // shall not be a member of a structure or an element of an
19470 // array.
19471 bool IsLastField = (i + 1 == Fields.end());
19472 if (FDTy->isFunctionType()) {
19473 // Field declared as a function.
19474 Diag(Loc: FD->getLocation(), DiagID: diag::err_field_declared_as_function)
19475 << FD->getDeclName();
19476 FD->setInvalidDecl();
19477 EnclosingDecl->setInvalidDecl();
19478 continue;
19479 } else if (FDTy->isIncompleteArrayType() &&
19480 (Record || isa<ObjCContainerDecl>(Val: EnclosingDecl))) {
19481 if (Record) {
19482 // Flexible array member.
19483 // Microsoft and g++ is more permissive regarding flexible array.
19484 // It will accept flexible array in union and also
19485 // as the sole element of a struct/class.
19486 unsigned DiagID = 0;
19487 if (!Record->isUnion() && !IsLastField) {
19488 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_not_at_end)
19489 << FD->getDeclName() << FD->getType() << Record->getTagKind();
19490 Diag(Loc: (*(i + 1))->getLocation(), DiagID: diag::note_next_field_declaration);
19491 FD->setInvalidDecl();
19492 EnclosingDecl->setInvalidDecl();
19493 continue;
19494 } else if (Record->isUnion())
19495 DiagID = getLangOpts().MicrosoftExt
19496 ? diag::ext_flexible_array_union_ms
19497 : diag::ext_flexible_array_union_gnu;
19498 else if (NumNamedMembers < 1)
19499 DiagID = getLangOpts().MicrosoftExt
19500 ? diag::ext_flexible_array_empty_aggregate_ms
19501 : diag::ext_flexible_array_empty_aggregate_gnu;
19502
19503 if (DiagID)
19504 Diag(Loc: FD->getLocation(), DiagID)
19505 << FD->getDeclName() << Record->getTagKind();
19506 // While the layout of types that contain virtual bases is not specified
19507 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19508 // virtual bases after the derived members. This would make a flexible
19509 // array member declared at the end of an object not adjacent to the end
19510 // of the type.
19511 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19512 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_virtual_base)
19513 << FD->getDeclName() << Record->getTagKind();
19514 if (!getLangOpts().C99)
19515 Diag(Loc: FD->getLocation(), DiagID: diag::ext_c99_flexible_array_member)
19516 << FD->getDeclName() << Record->getTagKind();
19517
19518 // If the element type has a non-trivial destructor, we would not
19519 // implicitly destroy the elements, so disallow it for now.
19520 //
19521 // FIXME: GCC allows this. We should probably either implicitly delete
19522 // the destructor of the containing class, or just allow this.
19523 QualType BaseElem = Context.getBaseElementType(QT: FD->getType());
19524 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19525 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_has_nontrivial_dtor)
19526 << FD->getDeclName() << FD->getType();
19527 FD->setInvalidDecl();
19528 EnclosingDecl->setInvalidDecl();
19529 continue;
19530 }
19531 // Okay, we have a legal flexible array member at the end of the struct.
19532 Record->setHasFlexibleArrayMember(true);
19533 } else {
19534 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19535 // unless they are followed by another ivar. That check is done
19536 // elsewhere, after synthesized ivars are known.
19537 }
19538 } else if (!FDTy->isDependentType() &&
19539 (LangOpts.HLSL // HLSL allows sizeless builtin types
19540 ? RequireCompleteType(Loc: FD->getLocation(), T: FD->getType(),
19541 DiagID: diag::err_incomplete_type)
19542 : RequireCompleteSizedType(
19543 Loc: FD->getLocation(), T: FD->getType(),
19544 DiagID: diag::err_field_incomplete_or_sizeless))) {
19545 // Incomplete type
19546 FD->setInvalidDecl();
19547 EnclosingDecl->setInvalidDecl();
19548 continue;
19549 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19550 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
19551 // A type which contains a flexible array member is considered to be a
19552 // flexible array member.
19553 Record->setHasFlexibleArrayMember(true);
19554 if (!Record->isUnion()) {
19555 // If this is a struct/class and this is not the last element, reject
19556 // it. Note that GCC supports variable sized arrays in the middle of
19557 // structures.
19558 if (!IsLastField)
19559 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variable_sized_type_in_struct)
19560 << FD->getDeclName() << FD->getType();
19561 else {
19562 // We support flexible arrays at the end of structs in
19563 // other structs as an extension.
19564 Diag(Loc: FD->getLocation(), DiagID: diag::ext_flexible_array_in_struct)
19565 << FD->getDeclName();
19566 }
19567 }
19568 }
19569 if (isa<ObjCContainerDecl>(Val: EnclosingDecl) &&
19570 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getType(),
19571 DiagID: diag::err_abstract_type_in_decl,
19572 Args: AbstractIvarType)) {
19573 // Ivars can not have abstract class types
19574 FD->setInvalidDecl();
19575 }
19576 if (Record && FDTTy->getDecl()->hasObjectMember())
19577 Record->setHasObjectMember(true);
19578 if (Record && FDTTy->getDecl()->hasVolatileMember())
19579 Record->setHasVolatileMember(true);
19580 } else if (FDTy->isObjCObjectType()) {
19581 /// A field cannot be an Objective-c object
19582 Diag(Loc: FD->getLocation(), DiagID: diag::err_statically_allocated_object)
19583 << FixItHint::CreateInsertion(InsertionLoc: FD->getLocation(), Code: "*");
19584 QualType T = Context.getObjCObjectPointerType(OIT: FD->getType());
19585 FD->setType(T);
19586 } else if (Record && Record->isUnion() &&
19587 FD->getType().hasNonTrivialObjCLifetime() &&
19588 getSourceManager().isInSystemHeader(Loc: FD->getLocation()) &&
19589 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19590 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
19591 !Context.hasDirectOwnershipQualifier(Ty: FD->getType()))) {
19592 // For backward compatibility, fields of C unions declared in system
19593 // headers that have non-trivial ObjC ownership qualifications are marked
19594 // as unavailable unless the qualifier is explicit and __strong. This can
19595 // break ABI compatibility between programs compiled with ARC and MRR, but
19596 // is a better option than rejecting programs using those unions under
19597 // ARC.
19598 FD->addAttr(A: UnavailableAttr::CreateImplicit(
19599 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership,
19600 Range: FD->getLocation()));
19601 } else if (getLangOpts().ObjC &&
19602 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19603 !Record->hasObjectMember()) {
19604 if (FD->getType()->isObjCObjectPointerType() ||
19605 FD->getType().isObjCGCStrong())
19606 Record->setHasObjectMember(true);
19607 else if (Context.getAsArrayType(T: FD->getType())) {
19608 QualType BaseType = Context.getBaseElementType(QT: FD->getType());
19609 if (BaseType->isRecordType() &&
19610 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19611 Record->setHasObjectMember(true);
19612 else if (BaseType->isObjCObjectPointerType() ||
19613 BaseType.isObjCGCStrong())
19614 Record->setHasObjectMember(true);
19615 }
19616 }
19617
19618 if (Record && !getLangOpts().CPlusPlus &&
19619 !shouldIgnoreForRecordTriviality(FD)) {
19620 QualType FT = FD->getType();
19621 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
19622 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19623 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
19624 Record->isUnion())
19625 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19626 }
19627 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
19628 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
19629 Record->setNonTrivialToPrimitiveCopy(true);
19630 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19631 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19632 }
19633 if (FD->hasAttr<ExplicitInitAttr>())
19634 Record->setHasUninitializedExplicitInitFields(true);
19635 if (FT.isDestructedType()) {
19636 Record->setNonTrivialToPrimitiveDestroy(true);
19637 Record->setParamDestroyedInCallee(true);
19638 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19639 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19640 }
19641
19642 if (const auto *RT = FT->getAs<RecordType>()) {
19643 if (RT->getDecl()->getArgPassingRestrictions() ==
19644 RecordArgPassingKind::CanNeverPassInRegs)
19645 Record->setArgPassingRestrictions(
19646 RecordArgPassingKind::CanNeverPassInRegs);
19647 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
19648 Record->setArgPassingRestrictions(
19649 RecordArgPassingKind::CanNeverPassInRegs);
19650 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
19651 Q && Q.isAddressDiscriminated()) {
19652 Record->setArgPassingRestrictions(
19653 RecordArgPassingKind::CanNeverPassInRegs);
19654 Record->setNonTrivialToPrimitiveCopy(true);
19655 }
19656 }
19657
19658 if (Record && FD->getType().isVolatileQualified())
19659 Record->setHasVolatileMember(true);
19660 bool ReportMSBitfieldStoragePacking =
19661 Record && PreviousField &&
19662 !Diags.isIgnored(DiagID: diag::warn_ms_bitfield_mismatched_storage_packing,
19663 Loc: Record->getLocation());
19664 auto IsNonDependentBitField = [](const FieldDecl *FD) {
19665 return FD->isBitField() && !FD->getType()->isDependentType();
19666 };
19667
19668 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
19669 IsNonDependentBitField(PreviousField)) {
19670 CharUnits FDStorageSize = Context.getTypeSizeInChars(T: FD->getType());
19671 CharUnits PreviousFieldStorageSize =
19672 Context.getTypeSizeInChars(T: PreviousField->getType());
19673 if (FDStorageSize != PreviousFieldStorageSize) {
19674 Diag(Loc: FD->getLocation(),
19675 DiagID: diag::warn_ms_bitfield_mismatched_storage_packing)
19676 << FD << FD->getType() << FDStorageSize.getQuantity()
19677 << PreviousFieldStorageSize.getQuantity();
19678 Diag(Loc: PreviousField->getLocation(),
19679 DiagID: diag::note_ms_bitfield_mismatched_storage_size_previous)
19680 << PreviousField << PreviousField->getType();
19681 }
19682 }
19683 // Keep track of the number of named members.
19684 if (FD->getIdentifier())
19685 ++NumNamedMembers;
19686 }
19687
19688 // Okay, we successfully defined 'Record'.
19689 if (Record) {
19690 bool Completed = false;
19691 if (S) {
19692 Scope *Parent = S->getParent();
19693 if (Parent && Parent->isTypeAliasScope() &&
19694 Parent->isTemplateParamScope())
19695 Record->setInvalidDecl();
19696 }
19697
19698 if (CXXRecord) {
19699 if (!CXXRecord->isInvalidDecl()) {
19700 // Set access bits correctly on the directly-declared conversions.
19701 for (CXXRecordDecl::conversion_iterator
19702 I = CXXRecord->conversion_begin(),
19703 E = CXXRecord->conversion_end(); I != E; ++I)
19704 I.setAccess((*I)->getAccess());
19705 }
19706
19707 // Add any implicitly-declared members to this class.
19708 AddImplicitlyDeclaredMembersToClass(ClassDecl: CXXRecord);
19709
19710 if (!CXXRecord->isDependentType()) {
19711 if (!CXXRecord->isInvalidDecl()) {
19712 // If we have virtual base classes, we may end up finding multiple
19713 // final overriders for a given virtual function. Check for this
19714 // problem now.
19715 if (CXXRecord->getNumVBases()) {
19716 CXXFinalOverriderMap FinalOverriders;
19717 CXXRecord->getFinalOverriders(FinaOverriders&: FinalOverriders);
19718
19719 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19720 MEnd = FinalOverriders.end();
19721 M != MEnd; ++M) {
19722 for (OverridingMethods::iterator SO = M->second.begin(),
19723 SOEnd = M->second.end();
19724 SO != SOEnd; ++SO) {
19725 assert(SO->second.size() > 0 &&
19726 "Virtual function without overriding functions?");
19727 if (SO->second.size() == 1)
19728 continue;
19729
19730 // C++ [class.virtual]p2:
19731 // In a derived class, if a virtual member function of a base
19732 // class subobject has more than one final overrider the
19733 // program is ill-formed.
19734 Diag(Loc: Record->getLocation(), DiagID: diag::err_multiple_final_overriders)
19735 << (const NamedDecl *)M->first << Record;
19736 Diag(Loc: M->first->getLocation(),
19737 DiagID: diag::note_overridden_virtual_function);
19738 for (OverridingMethods::overriding_iterator
19739 OM = SO->second.begin(),
19740 OMEnd = SO->second.end();
19741 OM != OMEnd; ++OM)
19742 Diag(Loc: OM->Method->getLocation(), DiagID: diag::note_final_overrider)
19743 << (const NamedDecl *)M->first << OM->Method->getParent();
19744
19745 Record->setInvalidDecl();
19746 }
19747 }
19748 CXXRecord->completeDefinition(FinalOverriders: &FinalOverriders);
19749 Completed = true;
19750 }
19751 }
19752 ComputeSelectedDestructor(S&: *this, Record: CXXRecord);
19753 ComputeSpecialMemberFunctionsEligiblity(S&: *this, Record: CXXRecord);
19754 }
19755 }
19756
19757 if (!Completed)
19758 Record->completeDefinition();
19759
19760 // Handle attributes before checking the layout.
19761 ProcessDeclAttributeList(S, D: Record, AttrList: Attrs);
19762
19763 // Maybe randomize the record's decls. We automatically randomize a record
19764 // of function pointers, unless it has the "no_randomize_layout" attribute.
19765 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
19766 !Record->isRandomized() && !Record->isUnion() &&
19767 (Record->hasAttr<RandomizeLayoutAttr>() ||
19768 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19769 EntirelyFunctionPointers(Record)))) {
19770 SmallVector<Decl *, 32> NewDeclOrdering;
19771 if (randstruct::randomizeStructureLayout(Context, RD: Record,
19772 FinalOrdering&: NewDeclOrdering))
19773 Record->reorderDecls(Decls: NewDeclOrdering);
19774 }
19775
19776 // We may have deferred checking for a deleted destructor. Check now.
19777 if (CXXRecord) {
19778 auto *Dtor = CXXRecord->getDestructor();
19779 if (Dtor && Dtor->isImplicit() &&
19780 ShouldDeleteSpecialMember(MD: Dtor, CSM: CXXSpecialMemberKind::Destructor)) {
19781 CXXRecord->setImplicitDestructorIsDeleted();
19782 SetDeclDeleted(dcl: Dtor, DelLoc: CXXRecord->getLocation());
19783 }
19784 }
19785
19786 if (Record->hasAttrs()) {
19787 CheckAlignasUnderalignment(D: Record);
19788
19789 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19790 checkMSInheritanceAttrOnDefinition(RD: cast<CXXRecordDecl>(Val: Record),
19791 Range: IA->getRange(), BestCase: IA->getBestCase(),
19792 SemanticSpelling: IA->getInheritanceModel());
19793 }
19794
19795 // Check if the structure/union declaration is a type that can have zero
19796 // size in C. For C this is a language extension, for C++ it may cause
19797 // compatibility problems.
19798 bool CheckForZeroSize;
19799 if (!getLangOpts().CPlusPlus) {
19800 CheckForZeroSize = true;
19801 } else {
19802 // For C++ filter out types that cannot be referenced in C code.
19803 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record);
19804 CheckForZeroSize =
19805 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19806 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19807 CXXRecord->isCLike();
19808 }
19809 if (CheckForZeroSize) {
19810 bool ZeroSize = true;
19811 bool IsEmpty = true;
19812 unsigned NonBitFields = 0;
19813 for (RecordDecl::field_iterator I = Record->field_begin(),
19814 E = Record->field_end();
19815 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19816 IsEmpty = false;
19817 if (I->isUnnamedBitField()) {
19818 if (!I->isZeroLengthBitField())
19819 ZeroSize = false;
19820 } else {
19821 ++NonBitFields;
19822 QualType FieldType = I->getType();
19823 if (FieldType->isIncompleteType() ||
19824 !Context.getTypeSizeInChars(T: FieldType).isZero())
19825 ZeroSize = false;
19826 }
19827 }
19828
19829 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19830 // allowed in C++, but warn if its declaration is inside
19831 // extern "C" block.
19832 if (ZeroSize) {
19833 Diag(Loc: RecLoc, DiagID: getLangOpts().CPlusPlus ?
19834 diag::warn_zero_size_struct_union_in_extern_c :
19835 diag::warn_zero_size_struct_union_compat)
19836 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19837 }
19838
19839 // Structs without named members are extension in C (C99 6.7.2.1p7),
19840 // but are accepted by GCC. In C2y, this became implementation-defined
19841 // (C2y 6.7.3.2p10).
19842 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
19843 Diag(Loc: RecLoc, DiagID: IsEmpty ? diag::ext_empty_struct_union
19844 : diag::ext_no_named_members_in_struct_union)
19845 << Record->isUnion();
19846 }
19847 }
19848 } else {
19849 ObjCIvarDecl **ClsFields =
19850 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19851 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: EnclosingDecl)) {
19852 ID->setEndOfDefinitionLoc(RBrac);
19853 // Add ivar's to class's DeclContext.
19854 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19855 ClsFields[i]->setLexicalDeclContext(ID);
19856 ID->addDecl(D: ClsFields[i]);
19857 }
19858 // Must enforce the rule that ivars in the base classes may not be
19859 // duplicates.
19860 if (ID->getSuperClass())
19861 ObjC().DiagnoseDuplicateIvars(ID, SID: ID->getSuperClass());
19862 } else if (ObjCImplementationDecl *IMPDecl =
19863 dyn_cast<ObjCImplementationDecl>(Val: EnclosingDecl)) {
19864 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19865 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19866 // Ivar declared in @implementation never belongs to the implementation.
19867 // Only it is in implementation's lexical context.
19868 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19869 ObjC().CheckImplementationIvars(ImpDecl: IMPDecl, Fields: ClsFields, nIvars: RecFields.size(),
19870 Loc: RBrac);
19871 IMPDecl->setIvarLBraceLoc(LBrac);
19872 IMPDecl->setIvarRBraceLoc(RBrac);
19873 } else if (ObjCCategoryDecl *CDecl =
19874 dyn_cast<ObjCCategoryDecl>(Val: EnclosingDecl)) {
19875 // case of ivars in class extension; all other cases have been
19876 // reported as errors elsewhere.
19877 // FIXME. Class extension does not have a LocEnd field.
19878 // CDecl->setLocEnd(RBrac);
19879 // Add ivar's to class extension's DeclContext.
19880 // Diagnose redeclaration of private ivars.
19881 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19882 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19883 if (IDecl) {
19884 if (const ObjCIvarDecl *ClsIvar =
19885 IDecl->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
19886 Diag(Loc: ClsFields[i]->getLocation(),
19887 DiagID: diag::err_duplicate_ivar_declaration);
19888 Diag(Loc: ClsIvar->getLocation(), DiagID: diag::note_previous_definition);
19889 continue;
19890 }
19891 for (const auto *Ext : IDecl->known_extensions()) {
19892 if (const ObjCIvarDecl *ClsExtIvar
19893 = Ext->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
19894 Diag(Loc: ClsFields[i]->getLocation(),
19895 DiagID: diag::err_duplicate_ivar_declaration);
19896 Diag(Loc: ClsExtIvar->getLocation(), DiagID: diag::note_previous_definition);
19897 continue;
19898 }
19899 }
19900 }
19901 ClsFields[i]->setLexicalDeclContext(CDecl);
19902 CDecl->addDecl(D: ClsFields[i]);
19903 }
19904 CDecl->setIvarLBraceLoc(LBrac);
19905 CDecl->setIvarRBraceLoc(RBrac);
19906 }
19907 }
19908 ProcessAPINotes(D: Record);
19909}
19910
19911// Given an integral type, return the next larger integral type
19912// (or a NULL type of no such type exists).
19913static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
19914 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19915 // enum checking below.
19916 assert((T->isIntegralType(Context) ||
19917 T->isEnumeralType()) && "Integral type required!");
19918 const unsigned NumTypes = 4;
19919 QualType SignedIntegralTypes[NumTypes] = {
19920 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19921 };
19922 QualType UnsignedIntegralTypes[NumTypes] = {
19923 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19924 Context.UnsignedLongLongTy
19925 };
19926
19927 unsigned BitWidth = Context.getTypeSize(T);
19928 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19929 : UnsignedIntegralTypes;
19930 for (unsigned I = 0; I != NumTypes; ++I)
19931 if (Context.getTypeSize(T: Types[I]) > BitWidth)
19932 return Types[I];
19933
19934 return QualType();
19935}
19936
19937EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
19938 EnumConstantDecl *LastEnumConst,
19939 SourceLocation IdLoc,
19940 IdentifierInfo *Id,
19941 Expr *Val) {
19942 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19943 llvm::APSInt EnumVal(IntWidth);
19944 QualType EltTy;
19945
19946 if (Val && DiagnoseUnexpandedParameterPack(E: Val, UPPC: UPPC_EnumeratorValue))
19947 Val = nullptr;
19948
19949 if (Val)
19950 Val = DefaultLvalueConversion(E: Val).get();
19951
19952 if (Val) {
19953 if (Enum->isDependentType() || Val->isTypeDependent() ||
19954 Val->containsErrors())
19955 EltTy = Context.DependentTy;
19956 else {
19957 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19958 // underlying type, but do allow it in all other contexts.
19959 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19960 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19961 // constant-expression in the enumerator-definition shall be a converted
19962 // constant expression of the underlying type.
19963 EltTy = Enum->getIntegerType();
19964 ExprResult Converted = CheckConvertedConstantExpression(
19965 From: Val, T: EltTy, Value&: EnumVal, CCE: CCEKind::Enumerator);
19966 if (Converted.isInvalid())
19967 Val = nullptr;
19968 else
19969 Val = Converted.get();
19970 } else if (!Val->isValueDependent() &&
19971 !(Val = VerifyIntegerConstantExpression(E: Val, Result: &EnumVal,
19972 CanFold: AllowFoldKind::Allow)
19973 .get())) {
19974 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19975 } else {
19976 if (Enum->isComplete()) {
19977 EltTy = Enum->getIntegerType();
19978
19979 // In Obj-C and Microsoft mode, require the enumeration value to be
19980 // representable in the underlying type of the enumeration. In C++11,
19981 // we perform a non-narrowing conversion as part of converted constant
19982 // expression checking.
19983 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
19984 if (Context.getTargetInfo()
19985 .getTriple()
19986 .isWindowsMSVCEnvironment()) {
19987 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_too_large) << EltTy;
19988 } else {
19989 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_too_large) << EltTy;
19990 }
19991 }
19992
19993 // Cast to the underlying type.
19994 Val = ImpCastExprToType(E: Val, Type: EltTy,
19995 CK: EltTy->isBooleanType() ? CK_IntegralToBoolean
19996 : CK_IntegralCast)
19997 .get();
19998 } else if (getLangOpts().CPlusPlus) {
19999 // C++11 [dcl.enum]p5:
20000 // If the underlying type is not fixed, the type of each enumerator
20001 // is the type of its initializing value:
20002 // - If an initializer is specified for an enumerator, the
20003 // initializing value has the same type as the expression.
20004 EltTy = Val->getType();
20005 } else {
20006 // C99 6.7.2.2p2:
20007 // The expression that defines the value of an enumeration constant
20008 // shall be an integer constant expression that has a value
20009 // representable as an int.
20010
20011 // Complain if the value is not representable in an int.
20012 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: Context.IntTy)) {
20013 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20014 ? diag::warn_c17_compat_enum_value_not_int
20015 : diag::ext_c23_enum_value_not_int)
20016 << 0 << toString(I: EnumVal, Radix: 10) << Val->getSourceRange()
20017 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20018 } else if (!Context.hasSameType(T1: Val->getType(), T2: Context.IntTy)) {
20019 // Force the type of the expression to 'int'.
20020 Val = ImpCastExprToType(E: Val, Type: Context.IntTy, CK: CK_IntegralCast).get();
20021 }
20022 EltTy = Val->getType();
20023 }
20024 }
20025 }
20026 }
20027
20028 if (!Val) {
20029 if (Enum->isDependentType())
20030 EltTy = Context.DependentTy;
20031 else if (!LastEnumConst) {
20032 // C++0x [dcl.enum]p5:
20033 // If the underlying type is not fixed, the type of each enumerator
20034 // is the type of its initializing value:
20035 // - If no initializer is specified for the first enumerator, the
20036 // initializing value has an unspecified integral type.
20037 //
20038 // GCC uses 'int' for its unspecified integral type, as does
20039 // C99 6.7.2.2p3.
20040 if (Enum->isFixed()) {
20041 EltTy = Enum->getIntegerType();
20042 }
20043 else {
20044 EltTy = Context.IntTy;
20045 }
20046 } else {
20047 // Assign the last value + 1.
20048 EnumVal = LastEnumConst->getInitVal();
20049 ++EnumVal;
20050 EltTy = LastEnumConst->getType();
20051
20052 // Check for overflow on increment.
20053 if (EnumVal < LastEnumConst->getInitVal()) {
20054 // C++0x [dcl.enum]p5:
20055 // If the underlying type is not fixed, the type of each enumerator
20056 // is the type of its initializing value:
20057 //
20058 // - Otherwise the type of the initializing value is the same as
20059 // the type of the initializing value of the preceding enumerator
20060 // unless the incremented value is not representable in that type,
20061 // in which case the type is an unspecified integral type
20062 // sufficient to contain the incremented value. If no such type
20063 // exists, the program is ill-formed.
20064 QualType T = getNextLargerIntegralType(Context, T: EltTy);
20065 if (T.isNull() || Enum->isFixed()) {
20066 // There is no integral type larger enough to represent this
20067 // value. Complain, then allow the value to wrap around.
20068 EnumVal = LastEnumConst->getInitVal();
20069 EnumVal = EnumVal.zext(width: EnumVal.getBitWidth() * 2);
20070 ++EnumVal;
20071 if (Enum->isFixed())
20072 // When the underlying type is fixed, this is ill-formed.
20073 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_wrapped)
20074 << toString(I: EnumVal, Radix: 10)
20075 << EltTy;
20076 else
20077 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_increment_too_large)
20078 << toString(I: EnumVal, Radix: 10);
20079 } else {
20080 EltTy = T;
20081 }
20082
20083 // Retrieve the last enumerator's value, extent that type to the
20084 // type that is supposed to be large enough to represent the incremented
20085 // value, then increment.
20086 EnumVal = LastEnumConst->getInitVal();
20087 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20088 EnumVal = EnumVal.zextOrTrunc(width: Context.getIntWidth(T: EltTy));
20089 ++EnumVal;
20090
20091 // If we're not in C++, diagnose the overflow of enumerator values,
20092 // which in C99 means that the enumerator value is not representable in
20093 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20094 // are representable in some larger integral type and we allow it in
20095 // older language modes as an extension.
20096 // Exclude fixed enumerators since they are diagnosed with an error for
20097 // this case.
20098 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20099 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20100 ? diag::warn_c17_compat_enum_value_not_int
20101 : diag::ext_c23_enum_value_not_int)
20102 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20103 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20104 !Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20105 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20106 Diag(Loc: IdLoc, DiagID: getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20107 : diag::ext_c23_enum_value_not_int)
20108 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20109 }
20110 }
20111 }
20112
20113 if (!EltTy->isDependentType()) {
20114 // Make the enumerator value match the signedness and size of the
20115 // enumerator's type.
20116 EnumVal = EnumVal.extOrTrunc(width: Context.getIntWidth(T: EltTy));
20117 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20118 }
20119
20120 return EnumConstantDecl::Create(C&: Context, DC: Enum, L: IdLoc, Id, T: EltTy,
20121 E: Val, V: EnumVal);
20122}
20123
20124SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
20125 SourceLocation IILoc) {
20126 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20127 !getLangOpts().CPlusPlus)
20128 return SkipBodyInfo();
20129
20130 // We have an anonymous enum definition. Look up the first enumerator to
20131 // determine if we should merge the definition with an existing one and
20132 // skip the body.
20133 NamedDecl *PrevDecl = LookupSingleName(S, Name: II, Loc: IILoc, NameKind: LookupOrdinaryName,
20134 Redecl: forRedeclarationInCurContext());
20135 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(Val: PrevDecl);
20136 if (!PrevECD)
20137 return SkipBodyInfo();
20138
20139 EnumDecl *PrevED = cast<EnumDecl>(Val: PrevECD->getDeclContext());
20140 NamedDecl *Hidden;
20141 if (!PrevED->getDeclName() && !hasVisibleDefinition(D: PrevED, Suggested: &Hidden)) {
20142 SkipBodyInfo Skip;
20143 Skip.Previous = Hidden;
20144 return Skip;
20145 }
20146
20147 return SkipBodyInfo();
20148}
20149
20150Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20151 SourceLocation IdLoc, IdentifierInfo *Id,
20152 const ParsedAttributesView &Attrs,
20153 SourceLocation EqualLoc, Expr *Val,
20154 SkipBodyInfo *SkipBody) {
20155 EnumDecl *TheEnumDecl = cast<EnumDecl>(Val: theEnumDecl);
20156 EnumConstantDecl *LastEnumConst =
20157 cast_or_null<EnumConstantDecl>(Val: lastEnumConst);
20158
20159 // The scope passed in may not be a decl scope. Zip up the scope tree until
20160 // we find one that is.
20161 S = getNonFieldDeclScope(S);
20162
20163 // Verify that there isn't already something declared with this name in this
20164 // scope.
20165 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20166 RedeclarationKind::ForVisibleRedeclaration);
20167 LookupName(R, S);
20168 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20169
20170 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20171 // Maybe we will complain about the shadowed template parameter.
20172 DiagnoseTemplateParameterShadow(Loc: IdLoc, PrevDecl);
20173 // Just pretend that we didn't see the previous declaration.
20174 PrevDecl = nullptr;
20175 }
20176
20177 // C++ [class.mem]p15:
20178 // If T is the name of a class, then each of the following shall have a name
20179 // different from T:
20180 // - every enumerator of every member of class T that is an unscoped
20181 // enumerated type
20182 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
20183 DiagnoseClassNameShadow(DC: TheEnumDecl->getDeclContext(),
20184 NameInfo: DeclarationNameInfo(Id, IdLoc));
20185
20186 EnumConstantDecl *New =
20187 CheckEnumConstant(Enum: TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20188 if (!New)
20189 return nullptr;
20190
20191 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20192 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(Val: PrevDecl)) {
20193 // Check for other kinds of shadowing not already handled.
20194 CheckShadow(D: New, ShadowedDecl: PrevDecl, R);
20195 }
20196
20197 // When in C++, we may get a TagDecl with the same name; in this case the
20198 // enum constant will 'hide' the tag.
20199 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20200 "Received TagDecl when not in C++!");
20201 if (!isa<TagDecl>(Val: PrevDecl) && isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
20202 if (isa<EnumConstantDecl>(Val: PrevDecl))
20203 Diag(Loc: IdLoc, DiagID: diag::err_redefinition_of_enumerator) << Id;
20204 else
20205 Diag(Loc: IdLoc, DiagID: diag::err_redefinition) << Id;
20206 notePreviousDefinition(Old: PrevDecl, New: IdLoc);
20207 return nullptr;
20208 }
20209 }
20210
20211 // Process attributes.
20212 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
20213 AddPragmaAttributes(S, D: New);
20214 ProcessAPINotes(D: New);
20215
20216 // Register this decl in the current scope stack.
20217 New->setAccess(TheEnumDecl->getAccess());
20218 PushOnScopeChains(D: New, S);
20219
20220 ActOnDocumentableDecl(D: New);
20221
20222 return New;
20223}
20224
20225// Returns true when the enum initial expression does not trigger the
20226// duplicate enum warning. A few common cases are exempted as follows:
20227// Element2 = Element1
20228// Element2 = Element1 + 1
20229// Element2 = Element1 - 1
20230// Where Element2 and Element1 are from the same enum.
20231static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
20232 Expr *InitExpr = ECD->getInitExpr();
20233 if (!InitExpr)
20234 return true;
20235 InitExpr = InitExpr->IgnoreImpCasts();
20236
20237 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: InitExpr)) {
20238 if (!BO->isAdditiveOp())
20239 return true;
20240 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: BO->getRHS());
20241 if (!IL)
20242 return true;
20243 if (IL->getValue() != 1)
20244 return true;
20245
20246 InitExpr = BO->getLHS();
20247 }
20248
20249 // This checks if the elements are from the same enum.
20250 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InitExpr);
20251 if (!DRE)
20252 return true;
20253
20254 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(Val: DRE->getDecl());
20255 if (!EnumConstant)
20256 return true;
20257
20258 if (cast<EnumDecl>(Val: TagDecl::castFromDeclContext(DC: ECD->getDeclContext())) !=
20259 Enum)
20260 return true;
20261
20262 return false;
20263}
20264
20265// Emits a warning when an element is implicitly set a value that
20266// a previous element has already been set to.
20267static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
20268 EnumDecl *Enum, QualType EnumType) {
20269 // Avoid anonymous enums
20270 if (!Enum->getIdentifier())
20271 return;
20272
20273 // Only check for small enums.
20274 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20275 return;
20276
20277 if (S.Diags.isIgnored(DiagID: diag::warn_duplicate_enum_values, Loc: Enum->getLocation()))
20278 return;
20279
20280 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20281 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20282
20283 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20284
20285 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20286 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20287
20288 // Use int64_t as a key to avoid needing special handling for map keys.
20289 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20290 llvm::APSInt Val = D->getInitVal();
20291 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20292 };
20293
20294 DuplicatesVector DupVector;
20295 ValueToVectorMap EnumMap;
20296
20297 // Populate the EnumMap with all values represented by enum constants without
20298 // an initializer.
20299 for (auto *Element : Elements) {
20300 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: Element);
20301
20302 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20303 // this constant. Skip this enum since it may be ill-formed.
20304 if (!ECD) {
20305 return;
20306 }
20307
20308 // Constants with initializers are handled in the next loop.
20309 if (ECD->getInitExpr())
20310 continue;
20311
20312 // Duplicate values are handled in the next loop.
20313 EnumMap.insert(x: {EnumConstantToKey(ECD), ECD});
20314 }
20315
20316 if (EnumMap.size() == 0)
20317 return;
20318
20319 // Create vectors for any values that has duplicates.
20320 for (auto *Element : Elements) {
20321 // The last loop returned if any constant was null.
20322 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Val: Element);
20323 if (!ValidDuplicateEnum(ECD, Enum))
20324 continue;
20325
20326 auto Iter = EnumMap.find(x: EnumConstantToKey(ECD));
20327 if (Iter == EnumMap.end())
20328 continue;
20329
20330 DeclOrVector& Entry = Iter->second;
20331 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Val&: Entry)) {
20332 // Ensure constants are different.
20333 if (D == ECD)
20334 continue;
20335
20336 // Create new vector and push values onto it.
20337 auto Vec = std::make_unique<ECDVector>();
20338 Vec->push_back(Elt: D);
20339 Vec->push_back(Elt: ECD);
20340
20341 // Update entry to point to the duplicates vector.
20342 Entry = Vec.get();
20343
20344 // Store the vector somewhere we can consult later for quick emission of
20345 // diagnostics.
20346 DupVector.emplace_back(Args: std::move(Vec));
20347 continue;
20348 }
20349
20350 ECDVector *Vec = cast<ECDVector *>(Val&: Entry);
20351 // Make sure constants are not added more than once.
20352 if (*Vec->begin() == ECD)
20353 continue;
20354
20355 Vec->push_back(Elt: ECD);
20356 }
20357
20358 // Emit diagnostics.
20359 for (const auto &Vec : DupVector) {
20360 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20361
20362 // Emit warning for one enum constant.
20363 auto *FirstECD = Vec->front();
20364 S.Diag(Loc: FirstECD->getLocation(), DiagID: diag::warn_duplicate_enum_values)
20365 << FirstECD << toString(I: FirstECD->getInitVal(), Radix: 10)
20366 << FirstECD->getSourceRange();
20367
20368 // Emit one note for each of the remaining enum constants with
20369 // the same value.
20370 for (auto *ECD : llvm::drop_begin(RangeOrContainer&: *Vec))
20371 S.Diag(Loc: ECD->getLocation(), DiagID: diag::note_duplicate_element)
20372 << ECD << toString(I: ECD->getInitVal(), Radix: 10)
20373 << ECD->getSourceRange();
20374 }
20375}
20376
20377bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20378 bool AllowMask) const {
20379 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20380 assert(ED->isCompleteDefinition() && "expected enum definition");
20381
20382 auto R = FlagBitsCache.try_emplace(Key: ED);
20383 llvm::APInt &FlagBits = R.first->second;
20384
20385 if (R.second) {
20386 for (auto *E : ED->enumerators()) {
20387 const auto &EVal = E->getInitVal();
20388 // Only single-bit enumerators introduce new flag values.
20389 if (EVal.isPowerOf2())
20390 FlagBits = FlagBits.zext(width: EVal.getBitWidth()) | EVal;
20391 }
20392 }
20393
20394 // A value is in a flag enum if either its bits are a subset of the enum's
20395 // flag bits (the first condition) or we are allowing masks and the same is
20396 // true of its complement (the second condition). When masks are allowed, we
20397 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20398 //
20399 // While it's true that any value could be used as a mask, the assumption is
20400 // that a mask will have all of the insignificant bits set. Anything else is
20401 // likely a logic error.
20402 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(width: Val.getBitWidth());
20403 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20404}
20405
20406void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
20407 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20408 const ParsedAttributesView &Attrs) {
20409 EnumDecl *Enum = cast<EnumDecl>(Val: EnumDeclX);
20410 QualType EnumType = Context.getTypeDeclType(Decl: Enum);
20411
20412 ProcessDeclAttributeList(S, D: Enum, AttrList: Attrs);
20413 ProcessAPINotes(D: Enum);
20414
20415 if (Enum->isDependentType()) {
20416 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20417 EnumConstantDecl *ECD =
20418 cast_or_null<EnumConstantDecl>(Val: Elements[i]);
20419 if (!ECD) continue;
20420
20421 ECD->setType(EnumType);
20422 }
20423
20424 Enum->completeDefinition(NewType: Context.DependentTy, PromotionType: Context.DependentTy, NumPositiveBits: 0, NumNegativeBits: 0);
20425 return;
20426 }
20427
20428 // Verify that all the values are okay, compute the size of the values, and
20429 // reverse the list.
20430 unsigned NumNegativeBits = 0;
20431 unsigned NumPositiveBits = 0;
20432 bool MembersRepresentableByInt =
20433 Context.computeEnumBits(EnumConstants: Elements, NumNegativeBits, NumPositiveBits);
20434
20435 // Figure out the type that should be used for this enum.
20436 QualType BestType;
20437 unsigned BestWidth;
20438
20439 // C++0x N3000 [conv.prom]p3:
20440 // An rvalue of an unscoped enumeration type whose underlying
20441 // type is not fixed can be converted to an rvalue of the first
20442 // of the following types that can represent all the values of
20443 // the enumeration: int, unsigned int, long int, unsigned long
20444 // int, long long int, or unsigned long long int.
20445 // C99 6.4.4.3p2:
20446 // An identifier declared as an enumeration constant has type int.
20447 // The C99 rule is modified by C23.
20448 QualType BestPromotionType;
20449
20450 bool Packed = Enum->hasAttr<PackedAttr>();
20451 // -fshort-enums is the equivalent to specifying the packed attribute on all
20452 // enum definitions.
20453 if (LangOpts.ShortEnums)
20454 Packed = true;
20455
20456 // If the enum already has a type because it is fixed or dictated by the
20457 // target, promote that type instead of analyzing the enumerators.
20458 if (Enum->isComplete()) {
20459 BestType = Enum->getIntegerType();
20460 if (Context.isPromotableIntegerType(T: BestType))
20461 BestPromotionType = Context.getPromotedIntegerType(PromotableType: BestType);
20462 else
20463 BestPromotionType = BestType;
20464
20465 BestWidth = Context.getIntWidth(T: BestType);
20466 } else {
20467 bool EnumTooLarge = Context.computeBestEnumTypes(
20468 IsPacked: Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
20469 BestWidth = Context.getIntWidth(T: BestType);
20470 if (EnumTooLarge)
20471 Diag(Loc: Enum->getLocation(), DiagID: diag::ext_enum_too_large);
20472 }
20473
20474 // Loop over all of the enumerator constants, changing their types to match
20475 // the type of the enum if needed.
20476 for (auto *D : Elements) {
20477 auto *ECD = cast_or_null<EnumConstantDecl>(Val: D);
20478 if (!ECD) continue; // Already issued a diagnostic.
20479
20480 // C99 says the enumerators have int type, but we allow, as an
20481 // extension, the enumerators to be larger than int size. If each
20482 // enumerator value fits in an int, type it as an int, otherwise type it the
20483 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20484 // that X has type 'int', not 'unsigned'.
20485
20486 // Determine whether the value fits into an int.
20487 llvm::APSInt InitVal = ECD->getInitVal();
20488
20489 // If it fits into an integer type, force it. Otherwise force it to match
20490 // the enum decl type.
20491 QualType NewTy;
20492 unsigned NewWidth;
20493 bool NewSign;
20494 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
20495 MembersRepresentableByInt) {
20496 // C23 6.7.3.3.3p15:
20497 // The enumeration member type for an enumerated type without fixed
20498 // underlying type upon completion is:
20499 // - int if all the values of the enumeration are representable as an
20500 // int; or,
20501 // - the enumerated type
20502 NewTy = Context.IntTy;
20503 NewWidth = Context.getTargetInfo().getIntWidth();
20504 NewSign = true;
20505 } else if (ECD->getType() == BestType) {
20506 // Already the right type!
20507 if (getLangOpts().CPlusPlus)
20508 // C++ [dcl.enum]p4: Following the closing brace of an
20509 // enum-specifier, each enumerator has the type of its
20510 // enumeration.
20511 ECD->setType(EnumType);
20512 continue;
20513 } else {
20514 NewTy = BestType;
20515 NewWidth = BestWidth;
20516 NewSign = BestType->isSignedIntegerOrEnumerationType();
20517 }
20518
20519 // Adjust the APSInt value.
20520 InitVal = InitVal.extOrTrunc(width: NewWidth);
20521 InitVal.setIsSigned(NewSign);
20522 ECD->setInitVal(C: Context, V: InitVal);
20523
20524 // Adjust the Expr initializer and type.
20525 if (ECD->getInitExpr() &&
20526 !Context.hasSameType(T1: NewTy, T2: ECD->getInitExpr()->getType()))
20527 ECD->setInitExpr(ImplicitCastExpr::Create(
20528 Context, T: NewTy, Kind: CK_IntegralCast, Operand: ECD->getInitExpr(),
20529 /*base paths*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()));
20530 if (getLangOpts().CPlusPlus)
20531 // C++ [dcl.enum]p4: Following the closing brace of an
20532 // enum-specifier, each enumerator has the type of its
20533 // enumeration.
20534 ECD->setType(EnumType);
20535 else
20536 ECD->setType(NewTy);
20537 }
20538
20539 Enum->completeDefinition(NewType: BestType, PromotionType: BestPromotionType,
20540 NumPositiveBits, NumNegativeBits);
20541
20542 CheckForDuplicateEnumValues(S&: *this, Elements, Enum, EnumType);
20543
20544 if (Enum->isClosedFlag()) {
20545 for (Decl *D : Elements) {
20546 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: D);
20547 if (!ECD) continue; // Already issued a diagnostic.
20548
20549 llvm::APSInt InitVal = ECD->getInitVal();
20550 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20551 !IsValueInFlagEnum(ED: Enum, Val: InitVal, AllowMask: true))
20552 Diag(Loc: ECD->getLocation(), DiagID: diag::warn_flag_enum_constant_out_of_range)
20553 << ECD << Enum;
20554 }
20555 }
20556
20557 // Now that the enum type is defined, ensure it's not been underaligned.
20558 if (Enum->hasAttrs())
20559 CheckAlignasUnderalignment(D: Enum);
20560}
20561
20562Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, SourceLocation StartLoc,
20563 SourceLocation EndLoc) {
20564
20565 FileScopeAsmDecl *New =
20566 FileScopeAsmDecl::Create(C&: Context, DC: CurContext, Str: expr, AsmLoc: StartLoc, RParenLoc: EndLoc);
20567 CurContext->addDecl(D: New);
20568 return New;
20569}
20570
20571TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {
20572 auto *New = TopLevelStmtDecl::Create(C&: Context, /*Statement=*/nullptr);
20573 CurContext->addDecl(D: New);
20574 PushDeclContext(S, DC: New);
20575 PushFunctionScope();
20576 PushCompoundScope(IsStmtExpr: false);
20577 return New;
20578}
20579
20580void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {
20581 D->setStmt(Statement);
20582 PopCompoundScope();
20583 PopFunctionScopeInfo();
20584 PopDeclContext();
20585}
20586
20587void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
20588 IdentifierInfo* AliasName,
20589 SourceLocation PragmaLoc,
20590 SourceLocation NameLoc,
20591 SourceLocation AliasNameLoc) {
20592 NamedDecl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc,
20593 NameKind: LookupOrdinaryName);
20594 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20595 AttributeCommonInfo::Form::Pragma());
20596 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20597 Ctx&: Context, Label: AliasName->getName(), /*IsLiteralLabel=*/true, CommonInfo: Info);
20598
20599 // If a declaration that:
20600 // 1) declares a function or a variable
20601 // 2) has external linkage
20602 // already exists, add a label attribute to it.
20603 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
20604 if (isDeclExternC(D: PrevDecl))
20605 PrevDecl->addAttr(A: Attr);
20606 else
20607 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
20608 << /*Variable*/(isa<FunctionDecl>(Val: PrevDecl) ? 0 : 1) << PrevDecl;
20609 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20610 } else
20611 (void)ExtnameUndeclaredIdentifiers.insert(KV: std::make_pair(x&: Name, y&: Attr));
20612}
20613
20614void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
20615 SourceLocation PragmaLoc,
20616 SourceLocation NameLoc) {
20617 Decl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc, NameKind: LookupOrdinaryName);
20618
20619 if (PrevDecl) {
20620 PrevDecl->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context, Range: PragmaLoc));
20621 } else {
20622 (void)WeakUndeclaredIdentifiers[Name].insert(X: WeakInfo(nullptr, NameLoc));
20623 }
20624}
20625
20626void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
20627 IdentifierInfo* AliasName,
20628 SourceLocation PragmaLoc,
20629 SourceLocation NameLoc,
20630 SourceLocation AliasNameLoc) {
20631 Decl *PrevDecl = LookupSingleName(S: TUScope, Name: AliasName, Loc: AliasNameLoc,
20632 NameKind: LookupOrdinaryName);
20633 WeakInfo W = WeakInfo(Name, NameLoc);
20634
20635 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
20636 if (!PrevDecl->hasAttr<AliasAttr>())
20637 if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: PrevDecl))
20638 DeclApplyPragmaWeak(S: TUScope, ND, W);
20639 } else {
20640 (void)WeakUndeclaredIdentifiers[AliasName].insert(X: W);
20641 }
20642}
20643
20644Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
20645 bool Final) {
20646 assert(FD && "Expected non-null FunctionDecl");
20647
20648 // SYCL functions can be template, so we check if they have appropriate
20649 // attribute prior to checking if it is a template.
20650 if (LangOpts.SYCLIsDevice && FD->hasAttr<DeviceKernelAttr>())
20651 return FunctionEmissionStatus::Emitted;
20652
20653 // Templates are emitted when they're instantiated.
20654 if (FD->isDependentContext())
20655 return FunctionEmissionStatus::TemplateDiscarded;
20656
20657 // Check whether this function is an externally visible definition.
20658 auto IsEmittedForExternalSymbol = [this, FD]() {
20659 // We have to check the GVA linkage of the function's *definition* -- if we
20660 // only have a declaration, we don't know whether or not the function will
20661 // be emitted, because (say) the definition could include "inline".
20662 const FunctionDecl *Def = FD->getDefinition();
20663
20664 // We can't compute linkage when we skip function bodies.
20665 return Def && !Def->hasSkippedBody() &&
20666 !isDiscardableGVALinkage(
20667 L: getASTContext().GetGVALinkageForFunction(FD: Def));
20668 };
20669
20670 if (LangOpts.OpenMPIsTargetDevice) {
20671 // In OpenMP device mode we will not emit host only functions, or functions
20672 // we don't need due to their linkage.
20673 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20674 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
20675 // DevTy may be changed later by
20676 // #pragma omp declare target to(*) device_type(*).
20677 // Therefore DevTy having no value does not imply host. The emission status
20678 // will be checked again at the end of compilation unit with Final = true.
20679 if (DevTy)
20680 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20681 return FunctionEmissionStatus::OMPDiscarded;
20682 // If we have an explicit value for the device type, or we are in a target
20683 // declare context, we need to emit all extern and used symbols.
20684 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20685 if (IsEmittedForExternalSymbol())
20686 return FunctionEmissionStatus::Emitted;
20687 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20688 // we'll omit it.
20689 if (Final)
20690 return FunctionEmissionStatus::OMPDiscarded;
20691 } else if (LangOpts.OpenMP > 45) {
20692 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20693 // function. In 5.0, no_host was introduced which might cause a function to
20694 // be omitted.
20695 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20696 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
20697 if (DevTy)
20698 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20699 return FunctionEmissionStatus::OMPDiscarded;
20700 }
20701
20702 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20703 return FunctionEmissionStatus::Emitted;
20704
20705 if (LangOpts.CUDA) {
20706 // When compiling for device, host functions are never emitted. Similarly,
20707 // when compiling for host, device and global functions are never emitted.
20708 // (Technically, we do emit a host-side stub for global functions, but this
20709 // doesn't count for our purposes here.)
20710 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: FD);
20711 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20712 return FunctionEmissionStatus::CUDADiscarded;
20713 if (!LangOpts.CUDAIsDevice &&
20714 (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))
20715 return FunctionEmissionStatus::CUDADiscarded;
20716
20717 if (IsEmittedForExternalSymbol())
20718 return FunctionEmissionStatus::Emitted;
20719
20720 // If FD is a virtual destructor of an explicit instantiation
20721 // of a template class, return Emitted.
20722 if (auto *Destructor = dyn_cast<CXXDestructorDecl>(Val: FD)) {
20723 if (Destructor->isVirtual()) {
20724 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(
20725 Val: Destructor->getParent())) {
20726 TemplateSpecializationKind TSK =
20727 Spec->getTemplateSpecializationKind();
20728 if (TSK == TSK_ExplicitInstantiationDeclaration ||
20729 TSK == TSK_ExplicitInstantiationDefinition)
20730 return FunctionEmissionStatus::Emitted;
20731 }
20732 }
20733 }
20734 }
20735
20736 // Otherwise, the function is known-emitted if it's in our set of
20737 // known-emitted functions.
20738 return FunctionEmissionStatus::Unknown;
20739}
20740
20741bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
20742 // Host-side references to a __global__ function refer to the stub, so the
20743 // function itself is never emitted and therefore should not be marked.
20744 // If we have host fn calls kernel fn calls host+device, the HD function
20745 // does not get instantiated on the host. We model this by omitting at the
20746 // call to the kernel from the callgraph. This ensures that, when compiling
20747 // for host, only HD functions actually called from the host get marked as
20748 // known-emitted.
20749 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20750 CUDA().IdentifyTarget(D: Callee) == CUDAFunctionTarget::Global;
20751}
20752

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